此语法在symfony2中正常工作,但在Symfony3中更改。
如何使用symfony3检索$em
中的参数FormType
?
$em=$this->getDoctrine()->getManager();
$form=$this->createForm(EtMenusType($em),$menu);
class EtMenusType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function __construct($em)
{
$this->em=$em;
}
答案 0 :(得分:2)
http://symfony.com/doc/current/book/forms#defining-your-forms-as-services
您的表单类型可能有一些外部依赖项。您可以将表单类型定义为服务,并注入所需的所有依赖项。
您可能希望在表单类型中使用定义为app.my_service的服务。为表单类型创建一个构造函数以接收服务:
// src/AppBundle/Form/Type/TaskType.php namespace AppBundle\Form\Type; use App\Utility\MyService; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\SubmitType; class TaskType extends AbstractType { private $myService; public function __construct(MyService $myService) { $this->myService = $myService; } public function buildForm(FormBuilderInterface $builder, array $options) { // You can now use myService. $builder ->add('task') ->add('dueDate', null, array('widget' => 'single_text')) ->add('save', SubmitType::class) ; } }
将表单类型定义为服务。
# src/AppBundle/Resources/config/services.yml services: app.form.type.task: class: AppBundle\Form\Type\TaskType arguments: ["@app.my_service"] tags: - { name: form.type }