Ger*_*rit 7 symfony symfony-2.3
我尝试从AbstractType扩展的FormType访问服务.我怎样才能做到这一点?
谢谢!
作为基于之前答案/评论的完整答案:
要从您的表单类型访问服务,您必须:
1)将您的表单类型定义为服务,并将所需的服务注入其中:
# src/AppBundle/Resources/config/services.yml
services:
app.my.form.type:
class: AppBundle\Form\MyFormType # this is your form type class
arguments:
- '@my.service' # this is the ID of the service you want to inject
tags:
- { name: form.type }
Run Code Online (Sandbox Code Playgroud)
2)现在在表单类型类中,将其注入构造函数:
// src/AppBundle/Form/MyFormType.php
class MyFormType extends AbstractType
{
protected $myService;
public function __construct(MyServiceClass $myService)
{
$this->myService = $myService;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->myService->someMethod();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
只需通过构造函数将您想要的服务注入到表单类型中即可。
class FooType extends AbstractType
{
protected $barService;
public function __construct(BarService $barService)
{
$this->barService = $barService;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->barService->doSomething();
// (...)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5153 次 |
| 最近记录: |