简体   繁体   English

symfony2传递服务以形成主题

[英]symfony2 pass service to form theming

Good evenning, 晚上好,

I simply need to access a service from a form_theme, something like myService.myFunction(param1, param2) where myService is the variable which holds the service itself. 我只需要从form_theme访问一个服务,比如myService.myFunction(param1, param2) ,其中myService是保存服务本身的变量。 The parameter I need to access is block('form_label') which gives me the for html attribute. 我需要访问的参数是block('form_label')这给了我 HTML属性。

I tried to access myService through the Request by using $request->attributes->set() method. 我尝试使用$request->attributes->set()方法通过Request访问myService。 This worked, but not at 100%, because I need the entityManager in myService, and it was set to null. 这有效,但不是100%,因为我需要myService中的entityManager,并且它被设置为null。 So I guess it's not the correct method. 所以我想这不是正确的方法。

I wanted to try with formExtensions, but I need this for many formTypes (around 10), and an extension works with only one FormType... 我想尝试使用formExtensions,但是对于许多formTypes(大约10个)我需要这个,并且扩展只能使用一个FormType ...

Is there any better solutions to access a service (with the entity manager) from my template ? 是否有更好的解决方案可以从我的模板访问服务(使用实体管理器)?

Just pass it by controller action: 只需通过控制器操作传递它:

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

...

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

OR use TwigExtension (without controller): 或使用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;
}

and use it globally in templates like this: 并在这样的模板中全局使用它:

{{ my_service().myDesiredMethod() }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM