Creating a minimalist form (no labels just placeholders)

Roland Schilter edited this page Apr 30, 2016 · 11 revisions

Create a minimalist form

Creating a minimalist form, that is a form without labels where the placeholder text contains the label text, is pretty straightforward.

app/helpers/minimal_form_helper.rb

require "minimal_form_builder"
module MinimalFormHelper
  def minimal_form_for(object, *args, &block)
    options = args.extract_options!
    simple_form_for(object, *(args << options.merge(:builder => MinimalFormBuilder)), &block)
  end

  def minimal_fields_for(*args, &block)
    options = args.extract_options!
    simple_fields_for(*(args << options.merge(:builder => MinimalFormBuilder)), &block)
  end
end

lib/minimal_form_builder.rb

class MinimalFormBuilder < SimpleForm::FormBuilder
  def input(attribute_name, options = {}, &block)
    type = options.fetch(:as, nil) || default_input_type(
        attribute_name,
        find_attribute_column(attribute_name),
        options
    )

    if type != :boolean
      if options[:placeholder].nil?
        options[:placeholder] ||= if object.class.respond_to?(:human_attribute_name)
                                    object.class.human_attribute_name(attribute_name.to_s)
                                  else
                                    attribute_name.to_s.humanize
                                  end
      end
      options[:label] = false if options[:label].nil?
    end

    super
  end
end

Then, instead of using simple_form_for in your views, simply use minimal_form_for. That's it!

Minimal forms are great for mobile and clean interfaces.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.