Search code examples
phpsymfonysymfony-2.2

How to redisplay a form with previous values when validation fails?


I have a form, which has to be passed by some other validations than unusual (about 4 fields are depending from each other). Thing is, when its failed, I redirect the user back, but then the form loses its values, I dont want it. I know it can be done with session, but there might be a "sanitier" way. Code is usual:

public function printAction()
{
    if ($this->getRequest()->getMethod() == "POST")
    {
        $form->bindRequest($this->getRequest());
        if ($form->isValid())
        {
             .... more validation.... Failed!
             return $this->redirect($this->generateUrl("SiteHomePeltexStockStockHistory_print"));
             // and this is when I lose the values.... I dont want it
        }
    }
}

Solution

  • You can use the same action for both GET and POST requests related to a form. If validation fails, just don't redirect and the same form will be redisplayed with entered values and validation error messages:

    /**
     * @Template
     */
    public function addAction(Request $request)
    {
        $form = /* ... */;        
    
        if ($request->isMethod('POST')) {
            $form->bind($request);
    
            if ($form->isValid()) {
                // do something and redirect
            }
    
            // the form is not valid, so do nothing and the form will be redisplayed
        }
    
        return [
            'form' => $form->createView(),
        ];
    }