From e6e0579defcfcf94ef1c4c1c7659f374a5335cdb Mon Sep 17 00:00:00 2001 From: Andy Waite Date: Sun, 5 May 2013 12:32:00 +0100 Subject: [PATCH] Add params option for button_to The parameters are rendered as hidden form fields within the generated form. This is useful for when a record has multiple buttons associated with it, each of which target the same controller method, but which need to submit different attributes. --- actionpack/CHANGELOG.md | 5 +++++ actionview/lib/action_view/helpers/url_helper.rb | 7 +++++++ actionview/test/template/url_helper_test.rb | 7 +++++++ 3 files changed, 19 insertions(+) diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 6e8ba88b77..6bd7b788bb 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,8 @@ +* Add `params` option to `button_to` form helper, which renders the given hash + as hidden form fields. + + *Andy Waite* + * Development mode exceptions are rendered in text format in case of XHR request. *Kir Shatrov* diff --git a/actionview/lib/action_view/helpers/url_helper.rb b/actionview/lib/action_view/helpers/url_helper.rb index 1920a94567..d98141b445 100644 --- a/actionview/lib/action_view/helpers/url_helper.rb +++ b/actionview/lib/action_view/helpers/url_helper.rb @@ -213,6 +213,7 @@ module ActionView # * :form - This hash will be form attributes # * :form_class - This controls the class of the form within which the submit button will # be placed + # * :params - Hash of parameters to be rendered as hidden fields within the form. # # ==== Data attributes # @@ -287,6 +288,7 @@ module ActionView url = options.is_a?(String) ? options : url_for(options) remote = html_options.delete('remote') + params = html_options.delete('params') method = html_options.delete('method').to_s method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : ''.html_safe @@ -310,6 +312,11 @@ module ActionView end inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag) + if params + params.each do |name, value| + inner_tags.safe_concat tag(:input, type: "hidden", name: name, value: value.to_param) + end + end content_tag('form', content_tag('div', inner_tags), form_options) end diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb index d512fa9913..850b8a62e9 100644 --- a/actionview/test/template/url_helper_test.rb +++ b/actionview/test/template/url_helper_test.rb @@ -160,6 +160,13 @@ class UrlHelperTest < ActiveSupport::TestCase ) end + def test_button_to_with_params + assert_dom_equal( + %{
}, + button_to("Hello", "http://www.example.com", params: {foo: :bar, baz: "quux"}) + ) + end + def test_link_tag_with_straight_url assert_dom_equal %{Hello}, link_to("Hello", "http://www.example.com") end