diff --git a/.changeset/quiet-singers-smoke.md b/.changeset/quiet-singers-smoke.md new file mode 100644 index 0000000000..fb71c94184 --- /dev/null +++ b/.changeset/quiet-singers-smoke.md @@ -0,0 +1,5 @@ +--- +"@primer/view-components": patch +--- + +Make sure labels and form inputs are properly associated when a custom ID is provided diff --git a/lib/primer/forms/dsl/input.rb b/lib/primer/forms/dsl/input.rb index 03771b9e7a..8203dd3a8a 100644 --- a/lib/primer/forms/dsl/input.rb +++ b/lib/primer/forms/dsl/input.rb @@ -56,7 +56,9 @@ def initialize(builder:, form:, **system_arguments) @form = form @input_arguments = system_arguments + @input_arguments.delete(:id) unless @input_arguments[:id].present? @label_arguments = @input_arguments.delete(:label_arguments) || {} + @label_arguments[:for] = id if id.present? @label_arguments[:class] = class_names( @label_arguments[:class], @@ -240,6 +242,10 @@ def autofocus! input_arguments[:autofocus] = true end + def id + @input_arguments[:id] + end + # :nocov: def name raise_for_abstract_method!(__method__) diff --git a/test/lib/primer/forms/form_control_test.rb b/test/lib/primer/forms/form_control_test.rb index 5f4915e23e..9eaf1af7d5 100644 --- a/test/lib/primer/forms/form_control_test.rb +++ b/test/lib/primer/forms/form_control_test.rb @@ -41,4 +41,17 @@ def test_auto_check_generates_validation_elements # there are validation-related elements, but they're hidden assert_selector(".FormControl-inlineValidation", visible: false) end + + def test_labels_use_custom_ids_when_provided + render_in_view_context do + primer_form_with(url: "/foo") do |f| + render_inline_form(f) do |test_form| + test_form.text_field(name: :foobar, id: "bazboo", label: "Foos and bars y'all") + end + end + end + + assert_selector "input[id=bazboo]" + assert_selector "label[for=bazboo]" + end end