gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:39:37 25 4
gpt4 key购买 nike

我尝试从由 AbstractType 扩展的 FormType 访问服务。我怎样才能做到这一点?

谢谢!

最佳答案

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

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

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

# 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)现在在您的表单类型类中,将其注入(inject)构造函数:
// 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();
// ...
}
}

关于symfony - 如何访问 Symfony FormType 中的其他服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18127287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com