Symfony2如何将服务传递给表单主题?

3

晚上好,

我只需要从一个表单主题访问一个服务,类似于myService.myFunction(param1, param2),其中myService是保存服务本身的变量。我需要访问的参数是block('form_label'),它给我for html属性。

我尝试通过Request使用$request->attributes->set()方法访问myService。这个方法有效,但并不完美,因为我需要在myService中使用entityManager,而它被设置为null。所以我猜这不是正确的方法。

我想尝试使用formExtensions,但我需要它用于许多FormTypes(大约10个),而一个扩展仅适用于一个FormType...

有更好的解决方案可以从我的模板中访问一个带有entityManager的服务吗?

1个回答

2

只需通过控制器操作传递它:

$service = $this->get('MY_SERVICE');

...

return $this->render(..., ['service' => $service]);

或者使用TwigExtension(不需要控制器):

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;
}

并且可以在模板中全局使用,像这样:

{{ my_service().myDesiredMethod() }}

好的,谢谢!我已经通过Twig扩展解决了问题。 - ovesco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接