如何从控制器传递参数到FormType构造函数

Muz*_*Ali 25 symfony-forms symfony

在Symfony2.7中,我可以在创建表单时直接从控制器将参数传递给Form Type构造函数,但是在Symfony3中我无法做到!

在Symfony2.7之前

$form = $this->createForm(new NewsType("posted_by_name"));
Run Code Online (Sandbox Code Playgroud)

在Symfony3之后

$form = $this->createForm(NewsType::class); // no idea how to pass parameter?
Run Code Online (Sandbox Code Playgroud)

更新: 我还想从以下位置访问它:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    // how to access posted_by_name here which is sent from controller
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将受到高度赞赏..

Muz*_*Ali 46

谢谢你的时间!我自己解决了这个问题

我从NewsType构造函数中删除了参数,并使用$ options数组将数据添加到了postedBy表单字段,并将数据从控制器传递给$ options数组,请检查以下内容:

NewsType

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('postedBy', HiddenType::class, array(
            'data' => $options['postedBy']
            )
        )
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'postedBy' => null,
    ));
}
Run Code Online (Sandbox Code Playgroud)

调节器

$form = $this->createForm(NewsType::class, $news, array(
    'postedBy' => $this->getUser()->getFullname(),
);
Run Code Online (Sandbox Code Playgroud)

更新: 如果要从addEventListener访问$ options数组,请使用下面的代码:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $postedBy = $event->getForm()->getConfig()->getOptions()['postedBy'];
}
Run Code Online (Sandbox Code Playgroud)

希望它能帮助别人! 


jku*_*vic 11

您需要将表单定义为服务.

namespace AppBundle\Form\Type;

use App\Utility\MyCustomService;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class NewsType extends AbstractType
{
    private $myCustomService;

    private $myStringParameter;

    public function __construct(MyCustomService $service, $stringParameter)
    {
        $this->myCustomService   = $service;
        $this->myStringParameter = $stringParameter;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Your code
    }
}
Run Code Online (Sandbox Code Playgroud)

添加到您的服务配置:

#src/AppBundle/Resources/config/services.yml
services:
    app.form.type.task:
        class: AppBundle\Form\Type\NewsType
        arguments:
            - "@app.my_service"
            - "posted_by_name"
        tags:
            - { name: form.type }
Run Code Online (Sandbox Code Playgroud)


Mic*_*ick 10

你是对的.

@Muzafar和@jkucharovic,问题是何时使用哪个......

正如Bernard Schussek在Symfony Forms 101中所展示的那样:

1不要将动态数据传递给构造函数..

在此输入图像描述

2......但使用自定义选项,而不是

在此输入图像描述

3全局设置传递给构造函数(或服务)

在此输入图像描述

在此输入图像描述