How to Set Raw, html text for checkbox – radio labels when used symfony form builder

As default, Symfony 4 does not allow the set raw label text for form elements. I needed this when I want to show terms of use checkbox in a form. I found a workaround solution to accomplish this.

 

FormType Source Code:

/* ... */

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('termsOfUse', CheckboxType::class, [
            'mapped' => false,
            'label' => 'I agree and accept #TERMS_OF_USE_LINK#',
            'constraints' => new IsTrue(),
        ]);

        /* ... */
    }
}


Twig Template Source Code

{{ form_start(form) }}

{% set termsOfUseFormGroup %}
    {{ form_row(form.termsOfUse) }}
{% endset %}

{{ termsOfUseFormGroup|replace({'#TERMS_OF_USE_LINK#':'<a href="#">Terms of Use</a>'})|raw }}

{{ form_end(form) }}

To explain briefly, I set rendered terms of use form group content (which is {{ form_row(form.termsOfUse) }}) to a variable (which is termsOfUseFormGroup) and replace #TERM_OF_USE_LINK# string to a link.

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *