How to implement button tag for form_for helper?

I need to implement a helper creating a tag <button>...</button>, I need to do something similar to this:

<%= form_for(some_var) do |f| %>
  <%= f.submit '+' %>
<% end %>

The assistant should work as follows:

<%= 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 is not implemented in Rails 3.0.7.

What do I need to do to implement this helper in my application?

+3
source share
2 answers

You can create a special form helper that inherits FormBuilder for use in creating forms. I created this button method for use with Twitter Bootstrap.

"Bootstrap" . (, 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

.

1.

, , , ...

<%= form_for @duck, :builder => BootstrapFormBuilder do |form|%>

2. DRY

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

...

<%= bootstrap_form_for @person do |form| %>
  <%= form.button 'Click Me' %>
<% end %>
+8

. . , , . :

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

<%= submit_button @admission %>

:

enter image description here

+2

All Articles