简体   繁体   中英

Custom Form Builder in Rails 5.1

In my Rails 5.1 app, I wish to build a custom form builder (to style certain labels).

So, as often I do, I started from the basic and try to add the example shown the Rails documentation .

I have added

#app/form_builders/custom_form_builder.rb
class CustomFormBuilder < ActionView::Helpers::FormBuilder
  def div_radio_button(method, tag_value, options = {})
    @template.content_tag(:div,
      @template.radio_button(
        @object_name, method, tag_value, objectify_options(options)
      )
    )
  end
end 

and in my form

<%= form_with model: @user, url: users_path, method: :post do |f|  %>
  ...
  <%= f.div_radio_button(:admin, "child") %>
<% end %>

But I get

ActionView::Template::Error (undefined method `div_radio_button' for
#<ActionView::Helpers::FormBuilder:0x00007fb6e933d5b8>)

Am I missing anything here?

The only difference I see is that the example uses form_for and I use form_with but since all the standard builders work with both I guess that is not the issue.

Thanks

PS - I have restarted the server many times after adding CustomFormBuilder .

Shouldn't it be

 
 
 
  
   <%= f.radio_button(:admin, "child") %>
 
  

instead of

 
 
 
  
   <%= f.div_radio_button(:admin, "child") %>
 
  

UPDATE

Sorry I hurriedly answered this yesterday. Looking at it again you seem to be missing the builder option of the form so you are still using the ActionView::Helpers::FormBuilder instead of your custom form builder class .

 <%= form_for @person, :builder => MyFormBuilder do |f| %> I am a child: <%= f.div_radio_button(:admin, "child") %> I am an adult: <%= f.div_radio_button(:admin, "adult") %> <% end -%> 

The snippet above is from the docs

So what you need is probably this

 <%= form_with model: @user, url: users_path, method: :post, builder: CustomFormBuilder do |f| %> ... <%= f.div_radio_button(:admin, "child") %> <% end %> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM