在getForm()symfony2.8之后更改表单对象的默认参数的最佳实践

时间:2017-08-17 14:16:28

标签: php symfony

我更新并总结了这个问题。

我想要做的是在getForm()

之后更改表单对象的默认值
public function newAction(Request $request)
{
    $task = new Task();   
    $form = $this->createFormBuilder($task)
        ->add('task', TextType::class,array('data' => 'default text data') // Set the default data for loaded first time. 
        ->add('save', SubmitType::class, array('label' => 'Save'))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        //I want change the default value of task, I tried a few methods.
         $d = $form->getData();
         $form->get('task')->setData('replace text data'); // not work
         $d->setData('second data'); // notwork

    }

可能或如何?

1 个答案:

答案 0 :(得分:2)

Try this one.

 $builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $even) {
        $data = $event->getData();
        $form = $event->getForm();
        if (isset($data['task'])) {

            $data['task'] = "Default Task1";              
            $event->setData($data); 
        }
    });