ppoz21
ppoz21

Reputation: 89

Symfony router link in form label

I'm looking for possibility to embed router link in Symfony 5 form label. I need to add link to Terms of use page in registartion form type.

Here is part of my code:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // some code
        ->add('terms', CheckboxType::class, [
            'label' => 'I accept <a href="/terms" target="_blank">Terms of use</a>', // <= here I need router link instead of '/terms' 
            'label_attr' => [
                'class' => 'form-check-label'
            ],
            'label_html' => true,
            'mapped' => false
        ])
        //some other code
    ;
}

I know, that I can use TWIG, but I'm looking for PHP possibility ;)

Upvotes: 1

Views: 322

Answers (1)

thomas.drbg
thomas.drbg

Reputation: 1118

You could inject the router in your FormType and generate the link with it.

class FormType extends AbstractType{

    private $router;

    function __construct(RouterInterface $router){
        $this->router = $router;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $tosUrl = $this->router->generate('terms');
        
        $builder
            // some code
            ->add('terms', CheckboxType::class, [
                'label' => 'I accept <a href="' . $tosUrl .'" target="_blank">Terms of use</a>',
                'label_attr' => [
                    'class' => 'form-check-label'
                ],
                'label_html' => true,
                'mapped' => false
            ])
            //some other code
        ;
    }
}

Upvotes: 1

Related Questions