Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implements a button tag to form_for helper?

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?

like image 640
jrdi Avatar asked Oct 18 '25 14:10

jrdi


1 Answers

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 %>
like image 130
fny Avatar answered Oct 20 '25 07:10

fny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!