将表单数据保存到会话中,在刷新时重新填充表单(Symfony)


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

我愿意在提交给会话时保存表单(使用FormBuilder创建)。一旦用户返回到同一页面,就应该用之前提交的信息重新填充表单(如果存在的话)。

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

MappingType表单是有子的,但是顶层的字段似乎不会再次填充。child主要由ChoiceType字段组成。

会话数据用所有表单数据填充。由于我没有使用Doctrine,而只是一个普通的实体,因此我认为持久性没有问题。

表单在POST请求(handleRequest)上得到正确填充,但当我再次加载它(GET)时就不正确了。

任何想法?

正如Veve所说,在创建表单之前必须设置数据:

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

编辑

如果对象存在,例如在数据库

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