Jesus M Jesus M - 1 year ago 222
PHP Question

How to reset form in Symfony

How can I reset the form after submit? It's a simple search form where I show a field on the top and a table in the bottom that shows either the results based on the search or the whole list... but it does not reset, the search key remained...

* @Route("/", name="plazas_index")
public function indexAction(Request $request)
$form = $this->createForm('AppBundle\Form\BuscarType');

$repository = $this->getDoctrine()->getRepository('AppBundle:Plaza');

if ($form->isSubmitted() && $form->isValid()) {

$clave = $form['clave']->getData();

$query = $repository->createQueryBuilder('p')
->where('p.nombre LIKE :nombre')
->orWhere('p.localidad LIKE :localidad')
->setParameter('nombre', '%'.$clave.'%')
->setParameter('localidad', '%'.$clave.'%')
->orderBy('p.nombre', 'ASC')

$plazas = $query->getResult();
$cant = count($plazas);

$this->addFlash($cant ? 'success' : 'warning', 'La búsqueda de '.$clave. ' ha producido '.$cant.' resultados');
//return $this->redirectToRoute('plazas_index');
else {
$plazas = $repository->findAll();

unset ($form);
$form = $this->createForm('AppBundle\Form\BuscarType');
return $this->render('admin/plazas/index.html.twig', array(
'plazas' => $plazas,
'buscar_form' => $form->createView(),

I can't redirect because I do the render at the end of the action...
Any help is welcome, thanks!!

Answer Source

Remove the second $form->handleRequest($request); line and you are good to go!

handleRequest takes the submitted POST or GET data and applies it to the form, so if you want a blank form then you shouldn't call that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download