如果在Symfony2中无效,如何重定向到带有错误的表单?

时间:2014-02-28 10:45:56

标签: validation symfony

我不知道如果将错误重定向到表单,如果它对Symfony2无效?

所以我在我的实体中使用Assert:

/**
 * @ORM\Column(type="string", length=255, nullable=false)
 * @Assert\NotBlank()
 */
private $title;

这是我的createAction方法:

public function createAction(Request $request)
{
    $task = new Task();

    $form = $this->createForm(new TaskType(), $task);

    if ($request->getMethod() == 'POST') {
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($task);
            $em->flush();
        }

        // What should I do here if the form is not valid

        $this->get('session')->getFlashBag()->add('success', 'The task has been added successfully!');

        return $this->redirect($this->generateUrl('crm_tasks'));
    }

    return $this->render('LanCrmBundle:Task:create.html.twig', array(
        'form' => $form->createView(),
    ));

}

如何将错误返回到表单?

1 个答案:

答案 0 :(得分:0)

您应该在if($ form-> isValid)条件中包含FlashBag()和返回语句

 if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($task);
        $em->flush();

        $this->get('session')->getFlashBag()->add('success', 'The task has been added successfully!');

        return $this->redirect($this->generateUrl('crm_tasks'));
 }

如果无效,用户将被重定向到表单,如果Symfony捕获它,则显示错误。