Symfony 3 - Form model data loses property values which are not represented by fields

前端 未结 3 578
有刺的猬
有刺的猬 2021-01-25 05:07

I have a controller action method which should handle a two-splitted form. Each form handles just a few properties of my Entity Workflow. After submitting the first

3条回答
  •  滥情空心
    2021-01-25 05:16

    Because the form is submitted again with only the secondForm data, you are losing the firstForm data.

    You have 3 ways to keep them:

    1) Set the data from the firstForm into the query

    // Insert that instead of the `return $this->render` for the second form
    $url = $this->generateUrl(
        $request->attributes->get('_route'),
        array_merge(
            $request->query->all(),
            array('secondForm' => true, 'name' => $workflow->getName(), 'states' => $workflow->getStates()) // change the param
        )
    );
    return $this->redirect($url);
    

    Before $secondFormPart = $this->createForm(WorkflowTransitionsType::class, $workflow);

    Set back the name and states into the $workflow entity, in this example you can check the query variable secondForm to know if the first form was submitted or not

    2) Set the data from the firstForm into the next PATCH request with some hidden field

    You have to modify the secondForm to handle the data from the firstForm with some hidden form type

    3) Set the data in the session before returning the second form

    First of all, your entity will have to implement the interface Serializable and declare the method serialize and unserialize

    like that

    $this->get('session')->set('workflow', $workflow);
    

    The method serialize will be used to store it.

    You can set in back with the method unserialize

    $session = $this->get('session');
    $workflow = new Workflow();
    $workflow->unserialize($session->get('workflow'));
    

    Because you are storing the whole entity into the session, this solution will decrease a lot the performance of your application

提交回复
热议问题