如何访问Symfony FormType中的其他服务?

时间:2013-08-08 13:28:03

标签: symfony symfony-2.3

我尝试从AbstractType扩展的FormType访问服务。我怎么能这样做?

谢谢!

3 个答案:

答案 0 :(得分:5)

作为基于之前答案/评论的完整答案:

要从您的表单类型访问服务,您必须:

1)Define your Form Type as a service并将所需的服务注入其中:

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

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();
        // ...
    }
}

答案 1 :(得分:4)

只需通过构造函数将您想要的服务注入表单类型。

class FooType extends AbstractType
{
    protected $barService;

    public function __construct(BarService $barService)
    {
        $this->barService = $barService;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->barService->doSomething();
        // (...)
    }
}

答案 2 :(得分:3)

查看this page in the sympfony docs,了解如何将表单类型声明为服务。该页面有很多很好的文档和示例。

Cyprian走在正确的轨道上,但链接页面更进一步,将表单类型创建为服务并让DI容器自动注入服务。