Skip to content

Create a fake input that does NOT read attributes

gudata edited this page Dec 21, 2020 · 6 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 %>


Boolean Input

app/inputs/fake_checkbox_input.rb:

class FakeCheckboxInput < 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)
    tag_name = "#{@builder.object_name}[#{attribute_name}]"
    template.check_box_tag(tag_name, options['value'] || 1, options['checked'], merged_input_options)
  end
end

Then you can do <%= form.input :remove_avatar, as: :fake_checkbox, wrapper: :vertical_boolean %>


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.