Search code examples
formssymfonysymfony-2.3

How do I generate a URL when not in a controller


I have been developing a system using Symfony2(.3) now and came across an issue... I'm trying to build a form class that is supposed to post to /register. How can I do the equivalent of

$url = $this->generateUrl('register'); or $this->get('router')->generate('register');

inside a class that extends AbstractType? Code below.

class RegistrationFormType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        parent::buildForm($builder, $options);

        $builder->setAction(/*I want the URL generated here*/)
                ->add('username', 'string')
                ->add('password', 'repeated', array(

                ))
                ->add('cellphone', 'text', array(
                    'max_length' => 10,
                    'invalid_message' => 'A phone number must be exactly 10 characters long',
                ));

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\MainBundle\Entity\SystemUser',
        ));
    }

    public function getName() {
        return 'user_registration';
    }
} 

Am I just missing the point here? Am I not supposed to do this? I can't find anything useful on Google.

Thanks!


Solution

  • You need to inject the router service into your RegistrationFormType.

    Add this to your Type,

    use Symfony\Bundle\FrameworkBundle\Routing\Router;
    
    class RegistrationFormType extends AbstractType
    {    
        private $router;
    
        public function __construct(Router $router)
        {
           $this->router = $router;
        }
        // ...
    

    Then, if you've defined your type as a service, your should build it as follow (by providing @router service as an argument to the constructor),

    services:
        form.type.user_registration:
            class: path_to_your_type/RegistrationFormType
            arguments: [ @router ]
            tags:
                - { name: form.type }
    

    You may then be able to access the router's generate helper in your Type by calling,

    $this->router->generate('register');
    

    Also, in order to build your Type through the Dependency Injection Container, you'll have to use,

    $form = $this->createForm('user_registration', $systemUserInstance);
    

    instead of,

    $form = $this->createForm(new RegistrationFormType(), $systemUserInstance);