Extra fields with custom rails form builder
I have a custom form builder, and one of the reasons for this custom builder is that for every form, I need to include some extra para开发者_如何学Cms that I don't want to explicitly put in with hidden field tags in every form I write.
for_for(@foo, :builder => MyBuilder) do |f|
# stuff I shouldn't have to worry about
# this should be put in all the time without me having to do it
hidden_field_tag('extra', 'myextrainfo')
# normal things I would put in
f.text_field(:bar)
end
What do I have to do in my custom form builder, or what can I override or method chain to add some extra hidden things in the form (without just adding URL params)?
It was kinda tricky (reasonable new to Ruby/Rails), but I found a solution. Put it in some helper file (or another location depending on your needs).
module ActionView::Helpers::FormHelper
def form_for_with_updated_code(record_or_name_or_array, *args, &proc)
form_for_without_updated_code(record_or_name_or_array, *args) { |f|
concat(hidden_field_tag('extra','info'))
proc.call(f)
}
end
alias_method_chain :form_for, :updated_code
end
It overrides the form_for method and adds your hidden field. You could add code to extra personal options, for example to fill the hidden field(s), from the *args
parameter using extract_options!
.
精彩评论