Skip to content

Add label_for option to wrappers#1868

Open
55728 wants to merge 1 commit intoheartcombo:mainfrom
55728:add-label-for-option-to-wrappers
Open

Add label_for option to wrappers#1868
55728 wants to merge 1 commit intoheartcombo:mainfrom
55728:add-label-for-option-to-wrappers

Conversation

@55728
Copy link
Copy Markdown

@55728 55728 commented Apr 20, 2026

Closes #1800

When building custom wrappers with tag: :label, there was no way to automatically add the for attribute pointing to the corresponding input element.

This PR adds a label_for option to the wrapper DSL. When set to true, the wrapper resolves the input's id and adds it as the for attribute on the wrapping element.

Usage

config.wrappers :custom_label do |b|
  b.wrapper tag: :label, label_for: true, class: "custom-label" do |c|
    c.use :input
    c.wrapper tag: :div do |d|
      d.use :hint
    end
  end
end

This produces:

<label for="user_name" class="custom-label">
  <input type="text" id="user_name" />
  <div>
    <span class="hint">...</span>
  </div>
</label>

How it works

  • label_for: true is opt-in — existing wrappers are not affected
  • If input_html: { id: "custom_id" } is provided, that value is used
  • Otherwise, field_id (Rails 7.0+) generates the standard input ID
  • A for attribute set via html: { for: "..." } takes precedence (||=)
  • Works correctly with nested forms (simple_fields_for) — field_id sanitizes the full object_name path consistently with Rails' input ID generation

When `label_for: true` is set in a wrapper definition, the wrapper
automatically adds the `for` attribute pointing to the corresponding
input element. The value is resolved from `input_html: { id: }` if
present, otherwise from `ActionView::Helpers::FormHelper#field_id`.

This allows label elements used as wrappers to be properly associated
with their input fields, improving accessibility for custom wrapper
layouts. Works correctly with nested forms as `field_id` sanitizes
the full `object_name` path consistently with Rails' input ID
generation.

Closes heartcombo#1800
@55728 55728 force-pushed the add-label-for-option-to-wrappers branch from 673b7fc to e452277 Compare April 20, 2026 15:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Add "for" attribute in label wrapper

1 participant