Create a fake input that does NOT read attributes

Weston Ganger edited this page Feb 13, 2017 · 5 revisions

Purpose

Sometimes I just need a custom input for extra params But all the existing inputs read from object's attributes


String Input

app/inputs/fake_input.rb:

class FakeInput < SimpleForm::Inputs::StringInput
  # This method only create a basic input without reading any value from object
  def input(wrapper_options = nil)
    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
    template.text_field_tag(attribute_name, nil, merged_input_options)
  end
end

Then you can do <%= f.input :thing, as: :fake %>


Select

app/inputs/fake_select_input.rb:

class FakeSelectInput < SimpleForm::Inputs::CollectionSelectInput
  def input(wrapper_options = nil)
    label_method, value_method = detect_collection_methods

    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options).merge(input_options.slice(:multiple, :include_blank, :disabled, :prompt))

    template.select_tag(
      attribute_name, 
      template.options_from_collection_for_select(collection, value_method, label_method, selected: input_options[:selected], disabled: input_options[:disabled]), 
      merged_input_options
    )
  end
end

Then you can do <%= f.input :thing, as: :fake_select, collection: my_collection, selected: params[:thing] %>


Custom Input for Display

Create an "input" just for displaying attribute value.