How to implements a button tag to form_for helper?
I need imp开发者_StackOverflow社区lements 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.
1. DRY for ducks
Every time you build a form that uses the button, you need to specify the builder...
<%= form_for @duck, :builder => BootstrapFormBuilder do |form|%>
2. DRY for devs
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 %>
I had implemented a similar helper method in one of my applications earlier. I needed the button tag with an image on the button and a class of its own. You can pass either a string which is the text that is displayed on the button or the object itself. It looks like this:
def submit_button(object)
image = "#{image_tag('/images/icons/tick.png', :alt => '')}"
if object.is_a?(String)
value = "#{image}#{object}"
else
name = object.class.to_s.titlecase
value = object.new_record? ? "#{image} Save #{name} Information" : "#{image} Update #{name} Information"
end
content_tag :button, :type => :submit, :class => 'button positive' do
content_tag(:image, '/images/icons/tick.png', :alt => '')
value
end
end
Then you call this in the form <%= submit_button @admission %>
It looks like this:
精彩评论