How can I clear form values after successful form submission?
These didn't help:
CONTROLLER:
namespace Car\BrandBundle\Controller;
use Car\BrandBundle\Entity\BrandEntity;
use Car\BrandBundle\Form\Type\BrandType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class BrandController extends Controller
{
public function indexAction()
{
$form = $this->getFrom();
return $this->render('CarBrandBundle:Default:brand.html.twig',
array('page' => 'Brand', 'form' => $form->createView(), 'brands' => $this->getBrands()));
}
public function createAction(Request $request)
{
if ($request->getMethod() != 'POST')
{
return new Response('Only POST method is allowed');
}
$form = $this->getFrom();
$form->handleRequest($request);
if ($form->isValid())
{
$submission = $form->getData();
$em = $this->getDoctrine()->getManager();
$brand = new BrandEntity();
$brand->setName($submission->getName());
$em->persist($brand);
$em->flush();
$this->redirect($this->generateUrl('brand'));
}
return $this->render('CarBrandBundle:Default:brand.html.twig',
array('page' => 'Brand', 'form' => $form->createView(), 'brands' => $this->getBrands()));
}
private function getFrom()
{
return $this->createForm(new BrandType(), new BrandEntity(),
array('action' => $this->generateUrl('brandCreate')));
}
private function getBrands()
{
$repo = $this->getDoctrine()->getRepository('CarBrandBundle:BrandEntity');
$brands = $repo->findAll();
return $brands;
}
}
The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.
To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.
You may use JavaScript form reset() method or loop throw all textboxes and set Text property to empty string.
You simply need to unset both form and entity objects. Then, create new, clean instances so they are available in your template. Personally I prefer to do it only when the form is properly validated.
if($form->isValid()){
// persisting and flushing the entity
unset($entity);
unset($form);
$entity = new Entity();
$form = $this->createForm(new EntityType(), $entity);
}
Works for me. Cheers.
Resetting symfony form when same page handles the submission
In Bazyl's method creating another form after unsetting current form may be unnecessary task. I suggest to redirect to same page because symfony documentation (handling-form-submissions) also shows an example which redirects to another controller.
if ($form->isSubmitted() && $form->isValid()) {
// ... perform some action, such as saving the task to the database
return $this->redirect($request->getUri());
}
I have added sample sources to GitHub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With