Symfony2 go through the service to shape the theme
Good evening,
I just need to access the service from form_theme, something like myService.myFunction(param1, param2)
where myService is the variable that contains this service. I need to get a parameter block('form_label')
that gives me an attribute for html.
I tried to access myService via Request
using the method $request->attributes->set()
. It worked, but not 100% because I needed the entityManager in myService and it was set to null. So I think this is not the correct method.
I wanted to try with formExtensions, but I need this for many formsTypes (about 10) and the extension only works with one FormType ...
Are there any better solutions to access the service (with an entity manager) from my template?
source to share
Just pass it using a controller action:
$service = $this->get('MY_SERVICE');
...
return $this->render(..., ['service' => $service]);
OR use TwigExtension (no controller):
private $myService;
public function __construct(MyService $myService)
{
$this->myService = $myService;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('my_service', [$this, 'getMyService']);
];
}
public function getMyService()
{
return $this->myService;
}
and use it globally in templates, for example:
{{ my_service().myDesiredMethod() }}
source to share