Search code examples
symfonysymfony-3.2

Appear old information already entered in a form


I'm trying to show errors validation message with the old The information already entered , but the problém when the form is not valid and it's submitted else if ($form->isSubmitted()&& !$form->isValid()) : the old input content(old The information already entered) will disappear .
By the way i want after avery submition that the url end with #contact that's why i worked with this->redirect .

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {

        $task = $form->getData();


        $em = $this->getDoctrine()->getManager();
        $em->persist($task);
        $em->flush();
        $this->get('session')->getFlashBag()->add(
            'notice',
            'Votre message est bien envoyé !'
        );
    } else if ($form->isSubmitted() && !$form->isValid()) {
        $errors = array();

        foreach ($form->all() as $key => $child) {
            if (!$child->isValid()) {
                foreach ($child->getErrors() as $error) {
                    $errors[$key] = $error->getMessage();
                }
            }
        }


        foreach ($errors as $key => $value) {
            $this->get('session')->getFlashBag()->add('error', $value);
        }


        return $this->redirect($this->generateUrl('index') . '?a#contact');
    }

    return $this->render('front/index.html.twig', array('form' => $form ->createView())); 
}

Solution

  • You should only redirect to your index if the form is valid. Right now that redirect is occurring in } else if ($form->isSubmitted() && !$form->isValid()) {, which means a redirect will occur with invalid data.

    Try:

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
    
        $task = $form->getData();
    
    
        $em = $this->getDoctrine()->getManager();
        $em->persist($task);
        $em->flush();
        $this->get('session')->getFlashBag()->add(
            'notice',
            'Votre message est bien envoyé !'
        );
        return $this->redirect($this->generateUrl('index') . '?a#contact');
    
    } else if ($form->isSubmitted() && !$form->isValid()) {
        $errors = array();
    
        foreach ($form->all() as $key => $child) {
            if (!$child->isValid()) {
                foreach ($child->getErrors() as $error) {
                    $errors[$key] = $error->getMessage();
                }
            }
        }
    
    
        foreach ($errors as $key => $value) {
            $this->get('session')->getFlashBag()->add('error', $value);
        }
    }
    
    
    return $this->render('front/index.html.twig', array('form' => $form ->createView())); 
    
    }
    

    This way, if your form is not valid, it will return the render form again (with your errors included). You can see an example of a controller that follows that flow here.