-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Creating a minimalist form (no labels just placeholders)
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
This page was created by the OSS community and might be outdated or incomplete. Feel free to improve or update this content according to the latest versions of SimpleForm and Rails to help the next developer who visits this wiki after you.
Keep in mind to maintain the guides as simple as possible and to avoid additional dependencies that might be specific to your application or workflow (such as Haml, RSpec, Guard and similars).