简体   繁体   中英

Custom Form Builder in Rails 3

I'm trying to write a custom form builder in Rails to (among other things) automatically add a CSS class to each field I create.

I'd like to extend, for example, text_field to add in the class I need. But the code below, which I would expect would just pass behavior to the standard FormBuilder, fails with an error of the wrong number of arguments. "wrong number of arguments (3 for 1..2)"

class BootstrapFormBuilder < ActionView::Helpers::FormBuilder
    def text_field(object_name, method, options = {})
        super(object_name, method, options)
    end
end

If I look at the Rails source, I see the definition of text_field as:

def text_field(object_name, method, options = {})

Help please! (Bonus points if you throw in the code to merge ":class => 'some_class'" into the options hash along the way.

Thanks!

The Rails source you are referring to shows that text_field has two parameters not three. See FormBuilder source from github.

So update your form builder class as:

class BootstrapFormBuilder < ActionView::Helpers::FormBuilder
    def text_field(method, options = {})
        super(method, options)
    end
end

Then the usage of this, including the class option you want to add:

<%= form_for :foo, builder: BootstrapFormBuilder do |f| %>
  <%= f.text_field :foo_field, class: 'bootstrap_text_field' %>
<% end %>

Any options you pass in to the default FormBuilder are also available to this child class, so use the class option as you would for default form builder.

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