module JqueryUiForm module Inputs module CheckBoxesInput def check_boxes_input(method, options = {}) # radio_button(method, tag_value, options) legend, options = label_text(method, options) current_values = options.delete(:values) || current_values_from_association(method) collection = options.delete(:collection) || collection_from_association(method) label_options = options.delete(:html_label) || {} options[:class] = options[:class].gsub('ui-check_boxes-input','ui-boolean-input') buttonset = options.delete(:buttonset) || false fieldset_options = {} fieldset_options[:class] = "to-buttonset" if buttonset label_method = options.delete(:label_method) || :name value_method = options.delete(:value_method) || :id output = fieldset(legend.html_safe, fieldset_options) do template.concat(inline_hint(options.delete(:hint))) template.concat(inline_error(method)) collection.each do |row| label_text = label_from_association(row,label_method) value_text = value_from_association(row,value_method) checked = current_values.include?(value_text.to_s) if buttonset template.concat(template.check_box_tag("#{@object_name}[#{method}][]", value_text, checked, options.merge(:id => name_to_id("#{@object_name}_#{method}_#{value_text}")))) template.concat(label(name_to_id("#{method}_#{value_text}"), label_text, label_options)) else template.concat(column do template.concat(label(name_to_id("#{method}_#{value_text}"), label_text, label_options)) template.concat(template.check_box_tag("#{@object_name}[#{method}][]", value_text, checked, options.merge(:id => name_to_id("#{@object_name}_#{method}_#{value_text}")))) end) end end end end def label_from_association(row, label_method) return row[0] if row.is_a?(Array) return row if row.is_a?(String) if row.respond_to?(label_method) row.send(label_method) else row end end def value_from_association(row, value_method) return row[1] if row.is_a?(Array) return row if row.is_a?(String) if row.respond_to?(value_method) row.send(value_method) else row end end def current_values_from_association(method) return [] unless @object || @object.respond_to?(method) return [] unless @object.send(method).is_a?(Array) @object.send(method).map{|row| row.id.to_s} end def collection_from_association(method) return [] unless @object || @object.respond_to?(method) return [] unless @object.send(method).is_a?(Array) if target = @object.send(method).first target.class.all else begin collection = method.to_s.classify.constantize collection.all rescue return [] end end end end end end