Reputation: 458
Is there a possibility to use generateUrl() method outside of controllers?
I tried to use it in a custom repository class with $this->get('router')
, but it didn't work.
update
I've found a temporary solution here:
http://www.phamviet.net/2012/12/09/symfony-2-inject-service-as-dependency-in-to-repository/
I injected the whole service container into my repository, although it's "not recommended".
But it works for now.
update2
Injecting router instead of the whole container is probably a better idea :)
Upvotes: 14
Views: 23729
Reputation: 1
in symfony 4 and Sylius when the FormType extends an (ex.) AbstractResourceType
class PostType extends AbstractResourceType
{
private $router;
public function __construct(RouterInterface $router, $dataClass, $validationGroups = [])
{
$this->router = $router;
parent::__construct($dataClass, $validationGroups);
}
}
Services.yaml :
app.post.form.type:
class: App\Form\Admin\Post\PostType
tags:
- { name: form.type }
arguments: ['@router.default', '%app.model.post.class%' ]
Upvotes: 0
Reputation: 1487
Inject the router itself into your EntityRepsitory (like described on Development Life blog's post Symfony 2: Injecting service as dependency into doctrine repository), then you can use $this->router->generate('acme_route');
Upvotes: 2
Reputation: 700
Don't inject the container into your repository... Really, don't !
If I were you, I would create a service and injects the router in it. In this service, I would create a method, that uses the repository and adds the needed code using the router.
That's way less dirty and easy to use/understand for another developer.
Upvotes: 11
Reputation: 41934
If you take a look in the source code of Controller::generateUrl()
, you see how it's done:
$this->container->get('router')->generate($route, $parameters, $referenceType);
Basically you just enter the name of the route ($route
here); if exists, some parameters ($parameters
) and the type of reference (one of the constants of the UrlGeneratorInterface
)
Upvotes: 18