I need to add links to checkbox titles, I can see the link in the render array but when it renders the markup is stripped. How can I get the links to not be stripped?

I am doing this in a form alter, the checkboxes are added to the user registration form in the Drupal UI, i.e. they are form fields.

$tc_link = Link::fromTextAndUrl(new TranslatableMarkup('terms and conditions'), Url::fromRoute('<front>'))->toString();
$tc_link_label = t('You agree to the ') . $tc_link;
$form['field_terms_and_conditions']['#title'] = $tc_link_label;

The markup is like this:

<div class="form-checkboxes" id="edit-field-terms-and-conditions"><div class="js-form-item form-item js-form-type-checkbox form-type-checkbox js-form-item-field-terms-and-conditions-agree-terms-conditions form-item-field-terms-and-conditions-agree-terms-conditions">
        <input name="field_terms_and_conditions[agree_terms_conditions]" class="form-checkbox" id="edit-field-terms-and-conditions-agree-terms-conditions" type="checkbox" value="agree_terms_conditions" data-drupal-selector="edit-field-terms-and-conditions-agree-terms-conditions">

        <label class="option" for="edit-field-terms-and-conditions-agree-terms-conditions">You agree to the terms and conditions</label>

But if I inspect it with kint the links are clearly there.

1 Answer 1


In Drupal, strings need to be passed through the t() function for translation. This function uses string replacement to sanitize text. When passing links, the HTML should be put in the string, and the URL passed as a variable prefixed with a colon:

$tc_link_label = t('You agree to the <a href=":url">terms and conditions</a>', [':url' => Url::fromRoute('<front>')->toString()]);
$form['field_terms_and_conditions']['#title'] = $tc_link_label;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.