stefandoorn
stefandoorn

Reputation: 1032

Save form data to session, repopulate form with it on refresh (Symfony)

I'm willing to save a form (created with FormBuilder) on submit to the session. As soon as the user comes back to the same page, the form should be repopulated with the previous submitted information in case it exist.

    // Create form
    $form = $this->createForm(MappingType::class, $mapping);
    $form->handleRequest($request);

    // Populate it if we already have data from the request or from session, only when not submitted
    if (!$form->isSubmitted() && $request->getSession()->has('mapping')) {
       $form->setData($request->getSession()->get('mapping'));
    }

    // Save form data to session
    if ($form->isSubmitted() && $form->isValid()) {
        $request->getSession()->set('mapping', $form->getData());
    }

The MappingType form is with children, but also a field on top level doesn't seem to get populated again. The Children mainly consist of ChoiceType fields.

The session data is populated with all form data. And as I'm not using Doctrine, but just a plain entity, I see no issues with persistence.

The form gets populated correctly on the POST request (handleRequest), but not when I just load it again (GET).

Any ideas?

Upvotes: 1

Views: 4119

Answers (1)

Jsenechal
Jsenechal

Reputation: 663

As Veve said you must set data before create form like that :

if($request->getSession()->has('mapping'))) {
    $mapping->setSomething('value');
    $mapping->setSomethingOhter('value');
}
$form = $this->createForm(MappingType::class, $mapping);

Edit

If object exist for example in data base

$mapping = $em->getRepository('AppBundle:Object')->findBy('field'=>'value');
$form = $this->createForm(MappingType::class, $mapping);

Upvotes: 2

Related Questions