成功提交表单后如何清除表单值 [英] How can I clear form values after successful form submission

查看:58
本文介绍了成功提交表单后如何清除表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表单提交成功后如何清除表单值?

How can I clear form values after successful form submission?

这些都没有帮助:

控制器:

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

推荐答案

您只需要取消设置表单和实体对象.然后,创建新的、干净的实例,以便它们在您的模板中可用.就我个人而言,我更喜欢仅在正确验证表单时才这样做.

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

对我有用.干杯.

这篇关于成功提交表单后如何清除表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆