Skip to content

Commit 57b79cf

Browse files
committed
Improve guide for Customizing form builder
Make the example complete so people can follow along insted of having to understand the implicit context that you need an existing helper called `text_field_with_label` to make the example work. Fixes rails#49027.
1 parent 4bbb59c commit 57b79cf

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

guides/source/form_helpers.md

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -714,7 +714,20 @@ Once a file has been uploaded, there are a multitude of potential tasks, ranging
714714
Customizing Form Builders
715715
-------------------------
716716

717-
The object yielded by `form_with` and `fields_for` is an instance of [`ActionView::Helpers::FormBuilder`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html). Form builders encapsulate the notion of displaying form elements for a single object. While you can write helpers for your forms in the usual way, you can also create a subclass of `ActionView::Helpers::FormBuilder`, and add the helpers there. For example,
717+
The object yielded by `form_with` and `fields_for` is an instance of
718+
[`ActionView::Helpers::FormBuilder`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html).
719+
Form builders encapsulate the notion of displaying form elements for a single object. While you can write helpers for
720+
your forms in the usual way, you can also create a subclass of `ActionView::Helpers::FormBuilder`, and add the helpers
721+
there. For example, assuming you have a helper method defined in your application called `text_field_with_label` as the
722+
following
723+
724+
```ruby
725+
module ApplicationHelper
726+
def text_field_with_label(form, attribute)
727+
form.label(attribute) + form.text_field(attribute)
728+
end
729+
end
730+
```
718731

719732
```erb
720733
<%= form_with model: @person do |form| %>
@@ -743,9 +756,11 @@ end
743756
If you reuse this frequently you could define a `labeled_form_with` helper that automatically applies the `builder: LabellingFormBuilder` option:
744757

745758
```ruby
746-
def labeled_form_with(model: nil, scope: nil, url: nil, format: nil, **options, &block)
747-
options[:builder] = LabellingFormBuilder
748-
form_with model: model, scope: scope, url: url, format: format, **options, &block
759+
module ApplicationHelper
760+
def labeled_form_with(model: nil, scope: nil, url: nil, format: nil, **options, &block)
761+
options[:builder] = LabellingFormBuilder
762+
form_with model: model, scope: scope, url: url, format: format, **options, &block
763+
end
749764
end
750765
```
751766

0 commit comments

Comments
 (0)