How to use placeholders instead of labels in simple_form?

青春壹個敷衍的年華 提交于 2019-11-30 11:00:57

You need 3 steps to enable showing placeholders instead of labels automatically and need to do more configurations.

  1. make sure b.use :placeholder in simple_form.rb

  2. make sure b.use :input instead of b.use :label_input

  3. most important, modify your simple_form.en.yml:

    en:
      simple_form:
        "yes": 'Yes'
        "no": 'No'
      required:
        text: 'required'
        mark: '*'
      placeholders:
        user:
          name: 'name'

in your page:

<%= simple_form_for @user do |f|%>
  <%= f.input :name%>
<% end%>

Every placeholder needs to be defined here, or it will not display.

simple_form lets you hide an individual label by passing in label:false to each input. For example: <%= f.input :email, placeholder: 'Email', label:false %> will hide the label for your email input in a form.

You just alter, at initializers/simple_form.rb:

## Inputs
b.use :label_input

to

## Inputs
b.use :input

and, at your views just use attribute :placeholder instead of :label

Solution for bootstrap-enabled forms

In order to get this to work with Bootstrap I had to update simple_form_bootstrap.rb and comment out the b.use :label entries in the config for both vertical_form and horizontal_form:

#b.use :label, class: 'control-label'
b.use :placeholder

Then as @Bigxiang correctly mentioned the placeholders then all need to have a value defined in your simple_form.{LANG}.yml.

en:
  placeholders:
    defaults:
      first_name: First name
      last_name: Last name
    user:
      email: Email

Note that you don't have to specify the model when you use generic defaults translations, like first_name, last_name in my example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!