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

时间:2016-04-28 04:50:03

标签: symfony-forms symfony

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

之前在Symfony2.7中

$form = $this->createForm(new NewsType("posted_by_name"));

在Symfony3之后

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

更新 我也希望从以下网址访问它:

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

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

3 个答案:

答案 0 :(得分:42)

感谢您的时间!我自己解决了这个问题:

我从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,
    ));
}

<强>控制器

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

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

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

希望它有所帮助!

答案 1 :(得分:11)

您需要定义form as service

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

添加到您的服务配置:

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

答案 2 :(得分:8)

你是对的。

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

正如Bernard Schussek在Symfony Forms 101中所示:

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

enter image description here

2 ...但请使用自定义选项

enter image description here

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

enter image description here

enter image description here