AbstractType으로 확장 된 FormType에서 서비스에 액세스하려고합니다. 어떻게해야합니까?Symfony FormType 내의 다른 서비스에 액세스하는 방법은 무엇입니까?
감사합니다.
AbstractType으로 확장 된 FormType에서 서비스에 액세스하려고합니다. 어떻게해야합니까?Symfony FormType 내의 다른 서비스에 액세스하는 방법은 무엇입니까?
감사합니다.
생성자를 통해 원하는 서비스를 양식 유형에 삽입하면됩니다.
class FooType extends AbstractType
{
protected $barService;
public function __construct(BarService $barService)
{
$this->barService = $barService;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->barService->doSomething();
// (...)
}
}
양식 유형을 서비스로 선언하는 방법에 대한 설명은 this page in the sympfony docs을 참조하십시오. 이 페이지에는 좋은 문서와 예제가 많이 있습니다.
Cyprian은 제대로 작동하지만 링크 된 페이지는 양식 유형을 서비스로 작성하고 DI 컨테이너에 서비스를 자동으로 주입 시키면 더 나아갑니다. 이전 답변/의견에 따라 완전한 답변으로
:
양식 유형에서 서비스에 액세스하기 위해, 당신은에 있습니다
1) Define your Form Type as a service과 이용에 필요한 서비스를 주입 :
// 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();
// ...
}
}
:
# 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) 이제 폼 타입 클래스, 생성자에 주입3210
또한 서비스 파일의 FormType 선언에 새 인수를 추가해야합니다 (예 : – dxvargas
이 답변을 완벽하게 작동 시키려면 양식 유형을 [서비스로 정의]해야합니다 (http://symfony.com/doc/current/form/create_custom_field_type.html#creating-your-field- 서비스로서의 타입 (type-as-a-service) – ShinDarth