diff --git a/README.md b/README.md index 560127438..7cab82fda 100644 --- a/README.md +++ b/README.md @@ -739,6 +739,28 @@ Collection methods accept these options: * `:help`: Add a help span to the `form_group` * Other options will be forwarded to the `radio_button`/`check_box` method + +To add `data-` attributes to a collection of radio buttons, map your models to an array and add a hash: + +```erb +<%# Use the :first and :second elements of the array to be the value and label repsectively %> +<%- choices = @collection.map { |addr| [ addr.id, addr.street, { 'data-zip-code': addr.zip_code } ] } -%> + +<%= form.collection_radio_buttons :misc, choices, :first, :second %> +``` + +This generates: +```html +
+ + +
+
+ + +
+``` + ## Range Controls You can create a range control like this: diff --git a/lib/bootstrap_form/inputs/inputs_collection.rb b/lib/bootstrap_form/inputs/inputs_collection.rb index e6fc4c637..8194c9628 100644 --- a/lib/bootstrap_form/inputs/inputs_collection.rb +++ b/lib/bootstrap_form/inputs/inputs_collection.rb @@ -29,6 +29,11 @@ def form_group_collection_input_options(options, text, obj, index, input_value, input_options[:checked] = form_group_collection_input_checked?(checked, obj, input_value) end + # add things like 'data-' attributes to the HTML + obj.each do |inner_obj| + input_options.merge!(inner_obj) if inner_obj.is_a?(Hash) + end if obj.respond_to?(:each) + input_options[:error_message] = index == collection.size - 1 input_options.except!(:class) input_options diff --git a/test/bootstrap_checkbox_test.rb b/test/bootstrap_checkbox_test.rb index 64b90c0db..c7fc52519 100644 --- a/test/bootstrap_checkbox_test.rb +++ b/test/bootstrap_checkbox_test.rb @@ -547,6 +547,28 @@ class BootstrapCheckboxTest < ActionView::TestCase assert_equivalent_xml expected, actual end + test "collection_check_boxes renders data attributes" do + collection = [ + ['1', 'Foo', {'data-city': 'east'} ], + ['2', 'Bar', {'data-city': 'west' }], + ] + expected = <<~HTML +
+ +
+ + +
+
+ + +
+
+ HTML + + assert_equivalent_xml expected, @builder.collection_check_boxes(:misc, collection, :first, :second, include_hidden: false) + end + test "collection_check_boxes renders multiple check boxes with error correctly" do @user.errors.add(:misc, "error for test") collection = [Address.new(id: 1, street: "Foo"), Address.new(id: 2, street: "Bar")]