|
| 1 | +# Override Text Displayed By Form Label |
| 2 | + |
| 3 | +Rails does a good job with the default text displayed by a form label. It takes |
| 4 | +the primary symbol value you give it and capitalizes that. And that is often |
| 5 | +good enough. |
| 6 | + |
| 7 | +```ruby |
| 8 | +<%= form_with(model: post) do |form| %> |
| 9 | + <%= form.label :title, class: "text-sm font-medium text-gray-700" %> |
| 10 | + <%= form.text_field :title, required: true, class: "..." %> |
| 11 | +<% end %> |
| 12 | +``` |
| 13 | + |
| 14 | +This will yield a label value of _Title_. |
| 15 | + |
| 16 | +Sometimes, however, the casing needs to be different or you need entirely |
| 17 | +different text. Take this URL field for example. Rails will convert `:url` into |
| 18 | +_Url_ for the label text. Not ideal. I can override the default with a second |
| 19 | +positional argument, in this case, `"URL"`. |
| 20 | + |
| 21 | +```ruby |
| 22 | +<%= form_with(model: post) do |form| %> |
| 23 | + <%= form.label :url, "URL", class: "text-sm font-medium text-gray-700" %> |
| 24 | + <%= form.url_field :url, required: true, class: "..." %> |
| 25 | +<% end %> |
| 26 | +``` |
| 27 | + |
| 28 | +The [Rails docs have another good |
| 29 | +example](https://guides.rubyonrails.org/form_helpers.html#a-generic-search-form). |
| 30 | +A label with a value of `query` that is overridden to display "Search for:". |
| 31 | + |
| 32 | +```ruby |
| 33 | +<%= form_with url: "/search", method: :get do |form| %> |
| 34 | + <%= form.label :query, "Search for:" %> |
| 35 | + <%= form.search_field :query %> |
| 36 | + <%= form.submit "Search" %> |
| 37 | +<% end %> |
| 38 | +``` |
0 commit comments