I need implements a helper that creates <button>...</button>
tag, I need to do some similar to this:
<%= form_for(some_var) do |f| %>
<%= f.submit '+' %>
<% end %>
The helper should work like this:
<%= f.button '+' %>
# Returns
<button type="submit">+</button>
I saw https://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/form_tag_helper.rb#L458 but this isn't implemented in Rails 3.0.7.
What I need to do to implements this helper in my application?
You can create a custom form helper that inherits from FormBuilder to use when creating forms. I created this button method to use with Twitter's Bootstrap.
Replace 'Bootstrap' with whatever fits. (Perhaps CuteAsAButtonBuilder?)
app/helpers/bootstrap_form_builder.rb
class BootstrapFormBuilder < ActionView::Helpers::FormBuilder
def button(label, options={})
# You can also set default options, like a class
default_class = options[:class] || 'btn'
@template.button_tag(label.to_s.humanize, :class => default_class)
end
end
Now you have two ways to use the builder.
Every time you build a form that uses the button, you need to specify the builder...
<%= form_for @duck, :builder => BootstrapFormBuilder do |form|%>
Add the following
app/helpers/application_helper.rb
module ApplicationHelper
def bootstrap_form_for(name, *args, &block)
options = args.extract_options!
form_for(name, *(args << options.merge(:builder => BootstrapFormBuilder)), &block)
end
end
Just call the magic builder...
<%= bootstrap_form_for @person do |form| %>
<%= form.button 'Click Me' %>
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With