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

时间:2016-10-19 09:13:14

标签: php 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表单包含子项,但顶层的字段似乎不会再次填充。儿童主要由ChoiceType字段组成。

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

正如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);