user2012677
user2012677

Reputation: 5745

simple_form accept a hash for collection input

Current behavior

With simple_form you need to pass an array:

<%= f.input :my_field, collection: [[true,"Yes"],[false,"No"]] %>

Expected behavior

It would be nice to be able to pass a hash, so you do not need to do invert.sort on every hash passed. Is there any way to do this for every input?

<%= f.input :my_field, collection: {"true"=> "yes", "false"=>"No" } %>

Is it possible to pass a hash directly into the input without invert.sort?

Upvotes: 0

Views: 1015

Answers (2)

karwan
karwan

Reputation: 252

You can add your own helper my_simple_form_for to use your own YourFormBuilder

module ApplicationHelper
  def my_form_for record, options = {}, &block
    options[:builder] = MyFormBuilder
    simple_form_for(record, options, &block)
  end
end

Or just use it in this way:

<%= simple_form_for @record, builder: MyFormBuilder do |f| %>

In your own builder you can overwrite input:

class YourFormBuilder < SimpleForm::FormBuilder

  def input(attribute_name, options = {}, &block)
    options[:collection] = options[:collection].invert.sort if options[:collection].present? and options[:collection].kind_of? Hash
    super
  end

end

Upvotes: 1

jvillian
jvillian

Reputation: 20263

Based on our earlier Q&A, you could enhance the Hash extension to include as_select_options:

module DropdownExt

  def self.extended(receiver)

    receiver.each do |k,v|
      define_method(k) do 
        v.is_a?(Hash) ? v.extend(DropdownExt) : v
      end
    end

    define_method(:as_select_options) do 
      unless receiver.values.map{|v|v.class}.include?(ActiveSupport::HashWithIndifferentAccess)
        receiver.invert.sort
      else
        []
      end
    end

  end
end

class Dropdowns

  class << self

    private

    def dropdowns_spec
      YAML.load_file("#{path}").with_indifferent_access
    end

    def path
      Rails.root.join("spec/so/dropdowns/dropdowns.yaml") # <== you'll need to change this
    end

  end

  dropdowns_spec[:dropdown].each do |k,v|
    define_singleton_method k do 
      v.extend(DropdownExt)
    end
  end

  %i(
    truck_model
    bike_model
  ).each do |to_alias|
    singleton_class.send(:alias_method, to_alias, :car_model)
  end

end

Which would let you do something like:

Dropdowns.car_model.field1.as_select_options
 => [["false", "no"], ["true", "yes"]]

Or, I suppose:

<%= f.input :my_field, collection: Dropdowns.car_model.field1.as_select_options %>

It doesn't avoid invert.sort. But, it does bury it a little bit and wrap it up in a convenient as_select_options method.

Upvotes: 0

Related Questions