1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Override Text Displayed By Form Label as a Rails TIL

This commit is contained in:
jbranchaud
2025-01-24 12:36:46 -06:00
parent 48278c4908
commit aa71ff5f8b
2 changed files with 40 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1572 TILs and counting..._
_1573 TILs and counting..._
See some of the other learning resources I work on:
- [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators)
@@ -1032,6 +1032,7 @@ See some of the other learning resources I work on:
- [Migrating Up Down Up](rails/migrating-up-down-up.md)
- [Mock Rails Environment With An Inquiry Instance](rails/mock-rails-environment-with-an-inquiry-instance.md)
- [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md)
- [Override Text Displayed By Form Label](rails/override-text-displayed-by-form-label.md)
- [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md)
- [Params Is A Hash With Indifferent Access](rails/params-is-a-hash-with-indifferent-access.md)
- [Parse Query Params From A URL](rails/parse-query-params-from-a-url.md)

View File

@@ -0,0 +1,38 @@
# Override Text Displayed By Form Label
Rails does a good job with the default text displayed by a form label. It takes
the primary symbol value you give it and capitalizes that. And that is often
good enough.
```ruby
<%= form_with(model: post) do |form| %>
<%= form.label :title, class: "text-sm font-medium text-gray-700" %>
<%= form.text_field :title, required: true, class: "..." %>
<% end %>
```
This will yield a label value of _Title_.
Sometimes, however, the casing needs to be different or you need entirely
different text. Take this URL field for example. Rails will convert `:url` into
_Url_ for the label text. Not ideal. I can override the default with a second
positional argument, in this case, `"URL"`.
```ruby
<%= form_with(model: post) do |form| %>
<%= form.label :url, "URL", class: "text-sm font-medium text-gray-700" %>
<%= form.url_field :url, required: true, class: "..." %>
<% end %>
```
The [Rails docs have another good
example](https://guides.rubyonrails.org/form_helpers.html#a-generic-search-form).
A label with a value of `query` that is overridden to display "Search for:".
```ruby
<%= form_with url: "/search", method: :get do |form| %>
<%= form.label :query, "Search for:" %>
<%= form.search_field :query %>
<%= form.submit "Search" %>
<% end %>
```