How to redirect to form with errors if not valid in Symfony2?

I don't know how to redirect errors to a form if it's not valid with Symfony2?

So I use the Assert in my entity like that:

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

And this is my createAction method :

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(),
    ));

}

What should I do to return errors to the form?

Answers


You should include the FlashBag() and return statement inside the if($form->isValid) condition.

 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'));
 }

If not valid, the user will be redirected to the form, displaying the error if Symfony catched it.


Need Your Help

PLSQL Developer 10.0.2 lost all table reference key when export then import Oracle 11g tables?

oracle plsql oracle10g oracle11g plsqldeveloper

I use PLSQL Developer 10.0.2 (the latest registered version) to export Oracle 11g tables. After I import these tables, I found all the tables lost reference key. I don't want to use SQL Plus.

WPF: Getting System.Windows.Data Error's on changing rows in a grid

c# wpf windows

I have a grid that I dynamically need to resize in the number of columns based on the size of my window.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.