Alexander Theißen Alexander Theißen - 1 year ago 92
PHP Question

How to resolve a path in a non controller class in symfony2

I have a form builder class which inherits from

and I need to resolve a path like this:

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));

Since the class is not a child of
I have no access to the router. Any ideas?

What about passing the router to the class on construction time?

Answer Source

You can pass the router service via constructor to your form type. Register your form as a service with the form.type tag and inject the router service to it.

namespace Vendor\Bundle\AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Bundle\FrameworkBundle\Routing\Router;

class PostType extends AbstractType
     * @var Router
    private $router;

     * @param Router
    public function __construct(Router $router)
        $this->router = $router;

     * @return string
    public function getName()
        return 'post';

    // ...

Register it as a service:

        class: Vendor\Bundle\AppBundle\Form\Type\PostType
        arguments: [ @router ]
            - { name: form.type }

And use it in your controller like this:

public function addAction(Request $request)
    $post = new Post();
    $form = $this->createForm('post', $post);

    // ...

Since you registered your form type as a service with the form.type tag, you can simply use its name instead of new PostType(). And you can access the router service as $this->router in your type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download