Generates a form containing a single button that submits to the URL created by the set of options. This is the safest method to ensure links that cause changes to your data are not triggered by search bots or accelerators. If the HTML button does not work with your layout, you can also consider using the link_to method with the :method modifier as described in the link_to documentation.
The generated FORM element has a class name of button-to to allow styling of the form itself and its children. You can control the form submission and input element behavior using html_options. This method accepts the :method and :confirm modifiers described in the link_to documentation. If no :method modifier is given, it will default to performing a POST operation. You can also disable the button by passing :disabled => true in html_options. If you are using RESTful routes, you can pass the :method to change the HTTP verb used to submit the form.
Options
The options hash accepts the same options at url_for.
There are a few special html_options:
- :method — specifies the anchor name to be appended to the path.
- :disabled — specifies the anchor name to be appended to the path.
- :confirm — This will add a JavaScript confirm prompt with the question specified. If the user accepts, the link is processed normally, otherwise no action is taken.
Examples
<%= button_to "New", :action => "new" %> # => "<form action="/controller/new" method="post"> # <div><input type="submit" value="New" /></div> # </form>" button_to "Delete Image", { :action => "delete", :id => @image.id }, :confirm => "Are you sure?", :method => :delete # => "<form action="/images/delete/1" method="post"> # <div> # <input name="_method" type="hidden" value="delete" /> # <input onclick="return confirm('Are you sure?');" # value="Delete" type="submit" /> # </div> # </form>"
Source Code
# File action_view/helpers/url_helper.rb, line 202 def button_to(name, options = {}, html_options = {}) html_options = html_options.stringify_keys convert_boolean_attributes!(html_options, %w( disabled )) method_tag = '' if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s) method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s) end form_method = method.to_s == 'get' ? 'get' : 'post' request_token_tag = '' if form_method == 'post' && protect_against_forgery? request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) end if confirm = html_options.delete("confirm") html_options["onclick"] = "return #{confirm_javascript_function(confirm)};" end url = options.is_a?(String) ? options : self.url_for(options) name ||= url html_options.merge!("type" => "submit", "value" => name) "<form method=\"#{form_method}\" action=\"#{escape_once url}\" class=\"button-to\"><div>" + method_tag + tag("input", html_options) + request_token_tag + "</div></form>" end
<code/>and<pre/>for code samples.