Permalink
Browse files

Allow data attributes to be set as a first-level option for form_for,…

… so you can write `form_for @record, data: { behavior: 'autosave' }` instead of `form_for @record, html: { data: { behavior: 'autosave' } }` *DHH*
  • Loading branch information...
dhh committed Aug 8, 2012
1 parent c0954a4 commit b540f4c1b812453d680724527635eddbffb980c4
View
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ##
+* Allow data attributes to be set as a first-level option for form_for, so you can write `form_for @record, data: { behavior: 'autosave' }` instead of `form_for @record, html: { data: { behavior: 'autosave' } }` *DHH*
+
* Deprecate `button_to_function` and `link_to_function` helpers.
We recommend the use of Unobtrusive JavaScript instead. For example:
@@ -323,6 +323,24 @@ module FormHelper
# ...
# </form>
#
+ # === Setting HTML options
+ #
+ # You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
+ # the HTML key. Example:
+ #
+ # <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # The HTML generated for this would be:
+ #
+ # <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
+ # <div style='margin:0;padding:0;display:inline'>
+ # <input name='_method' type='hidden' value='put' />
+ # </div>
+ # ...
+ # </form>
+ #
# === Removing hidden model id's
#
# The form_for method automatically includes the model id as a hidden field in the form.
@@ -409,6 +427,7 @@ def form_for(record, options = {}, &proc)
apply_form_for_options!(record, object, options)
end
+ options[:html][:data] = options.delete(:data) if options.has_key?(:data)
options[:html][:remote] = options.delete(:remote) if options.has_key?(:remote)
options[:html][:method] = options.delete(:method) if options.has_key?(:method)
options[:html][:authenticity_token] = options.delete(:authenticity_token)
@@ -2637,6 +2637,12 @@ def test_form_for_with_default_method_as_patch
assert_dom_equal expected, output_buffer
end
+ def test_form_for_with_data_attributes
+ form_for(@post, data: { behavior: "stuff" }, remote: true) {}
+ assert_match %r|data-behavior="stuff"|, output_buffer
+ assert_match %r|data-remote="true"|, output_buffer
+ end
+
def test_fields_for_returns_block_result
output = fields_for(Post.new) { |f| "fields" }
assert_equal "fields", output

2 comments on commit b540f4c

@rafaelfranca

This comment has been minimized.

Show comment
Hide comment
@rafaelfranca

rafaelfranca Aug 8, 2012

Member

❤️

Member

rafaelfranca replied Aug 8, 2012

❤️

@styx

This comment has been minimized.

Show comment
Hide comment

styx replied Aug 10, 2012

👍

Please sign in to comment.