1

I updated and summurized the question.

What I want to do is changing the default value of form object after 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

    }

Is it possible or how??

whitebear
  • 11,200
  • 24
  • 114
  • 237
  • 1
    Just add `$task->setTask('Your Default Text');` prior to your `createFormBuilder` row. (Or set that value in the Task class itself, either in the constructor or as a default for the `$task` class-variable) – ccKep Aug 17 '17 at 14:32
  • Possible duplicate of [How to set default value for form field in Symfony2?](https://stackoverflow.com/questions/7913086/how-to-set-default-value-for-form-field-in-symfony2) – yceruto Aug 17 '17 at 15:07
  • I think I could se the default task but I would like to change this after submitted – whitebear Aug 17 '17 at 16:01
  • @yceruto , I guess myquesion is a bit different so , I updated the question itself – whitebear Aug 17 '17 at 17:12
  • You means the data associated to the task field in the form after submitted? – yceruto Aug 17 '17 at 17:20
  • You cannot change the data of a submitted form, so you might need re-create the form with the new default value. – yceruto Aug 17 '17 at 17:29
  • I see. I solved my problem by making new entity object. – whitebear Aug 25 '17 at 04:45

1 Answers1

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