Skip to content

Creating a minimalist form (no labels just placeholders)

Simon Courtois edited this page Dec 30, 2018 · 12 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.

Important: Note that this solution uses human_attribute_name. This means that the translations for your placeholders should not be placed under placeholders in the YAML file but under the model attribute keys:

fr:
  activerecord:
    attributes:
      article:
        title: Titre