In my drupal project I have a form field:
$form['field_consent_abcd']['widget']['value']['#title'] = t('Test text <a href="@url" target="_blank">target url text</a>.', ['@url' => '/aomething']);
This field is set as a checkbox field in drupal UI.
Problem: Drupal is rendering label and the form field is also rendering a label. so nested label prevents checkbox click from working. However, upon clicking the link text the box gets checked.
HTML structure rendered:
<div class="usa-checkbox...">
<input data-drupal-selector="edit-field-abcd-value" type="checkbox" id="edit-field-abcd-value" name="field_abcd[value]" value="1" class="form-checkbox required form-item form-item__input--form-boolean form-item--type-checkbox usa-checkbox__input" required="required" aria-required="true">
<label #theme="form_element_label" #title="fdfsfsfsf" #title_display="after" #id="edit-field-abcd-value"...>
::before
--labels nested here---
<label for="edit-field-abcd-value" class="form-item form-item__label option">
this is a test <a href="/something>url text</a>
::after
</label>
</label>
</div>
To fix this in my form alter i tried:
$form['field_consent_abcd']['widget']['value']['#title'] = '';
$form['field_consent_abcd']['widget']['value']['#title_display'] = 'none';
$form['field_consent_abcd']['widget']['value']['#attributes']['id'] = 'field-consent-abcd';
$form['field_consent_abcd']['#suffix'] = '
<label for="field-consent-abcd" class="usa-checkbox__label">
This is a test text
<a href="/something" target="_blank">for url</a>.
</label>
';
The above fix renders the below html structure:
<div..
<div...
<input...
<label... -- No label associated with a form field
::before
</label
</div>
</div
"link text" <a href...
Problem:
- My fix is rendering an input and a label but on the label i see "No label associated with a form field" error
- Checkbox click doesn't do anything
originally drupal renders label while my form field is also rendering the label. Any help on how this can be fixed?