diff --git a/lib/govuk_elements_form_builder/form_builder.rb b/lib/govuk_elements_form_builder/form_builder.rb index c9d23da..ba902af 100644 --- a/lib/govuk_elements_form_builder/form_builder.rb +++ b/lib/govuk_elements_form_builder/form_builder.rb @@ -104,9 +104,17 @@ def check_box_inputs attributes def radio_inputs attribute, options choices = options[:choices] || [ :yes, :no ] choices.map do |choice| - label(attribute, class: 'block-label selection-button-radio', value: choice) do |tag| - input = radio_button(attribute, choice) - input + localized_label("#{attribute}.#{choice}") + value = choice.send(options[:value_method] || :to_s) + label attribute, + class: 'block-label selection-button-radio', + value: value do |tag| + input = radio_button(attribute, value) + text = if options[:text_method] + choice.send(options[:text_method]) + else + localized_label("#{attribute}.#{choice}") + end + input + text end end end diff --git a/spec/dummy/app/models/case.rb b/spec/dummy/app/models/case.rb index aa2da26..94e0c45 100644 --- a/spec/dummy/app/models/case.rb +++ b/spec/dummy/app/models/case.rb @@ -1,9 +1,11 @@ class Case include ActiveModel::Model + attr_accessor :id attr_accessor :name attr_accessor :state_machine attr_accessor :subcases + validates_presence_of :name validate :validate_subcases diff --git a/spec/dummy/app/models/person.rb b/spec/dummy/app/models/person.rb index 426e351..22b9803 100644 --- a/spec/dummy/app/models/person.rb +++ b/spec/dummy/app/models/person.rb @@ -12,6 +12,7 @@ class Person attr_accessor :password_confirmation attr_accessor :waste_transport attr_accessor :gender + attr_accessor :case_id validates_presence_of :name, :gender diff --git a/spec/lib/govuk_elements_form_builder/form_builder_spec.rb b/spec/lib/govuk_elements_form_builder/form_builder_spec.rb index 80af51f..d9f9a28 100644 --- a/spec/lib/govuk_elements_form_builder/form_builder_spec.rb +++ b/spec/lib/govuk_elements_form_builder/form_builder_spec.rb @@ -253,6 +253,7 @@ def expected_error_html method, type, attribute, name_value, label, error describe '#radio_button_fieldset' do let(:pretty_output) { HtmlBeautifier.beautify output } + it 'outputs radio buttons wrapped in labels' do output = builder.radio_button_fieldset :location, choices: [:ni, :isle_of_man_channel_islands, :british_abroad] expect_equal output, [ @@ -306,6 +307,35 @@ def expected_error_html method, type, attribute, name_value, label, error ] end + context 'with a couple associated cases' do + let(:case_1) { Case.new(id: 1, name: 'Case One') } + let(:case_2) { Case.new(id: 2, name: 'Case Two') } + let(:cases) { [case_1, case_2] } + + it 'accepts value_method and text_method to better control generated HTML' do + output = builder.radio_button_fieldset :case_id, choices: cases, value_method: :id, text_method: :name, inline: true + expect_equal output, [ + '