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

时间:2014-06-15 13:01:33

标签: symfony

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

这些没有帮助:

控制器:

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

4 个答案:

答案 0 :(得分:22)

您只需要取消设置表单和实体对象。然后,创建新的,干净的实例,以便它们在您的模板中可用。 我个人认为只有在表格得到适当验证后才会这样做。

if($form->isValid()){

  // persisting and flushing the entity

  unset($entity);
  unset($form);
  $entity = new Entity();
  $form = $this->createForm(new EntityType(), $entity);
}

适合我。 欢呼声。

答案 1 :(得分:17)

在同一页面处理提交时重置symfony表单

在Bazyl的方法中,在取消设置当前表单后创建另一个表单可能是不必要的任务。我建议重定向到同一页面,因为symfony文档(handling-form-submissions)也显示了一个重定向到另一个控制器的示例。

    if ($form->isSubmitted() && $form->isValid()) {
        // ... perform some action, such as saving the task to the database
        return $this->redirect($request->getUri());
    }

我已将示例来源添加到GitHub

答案 2 :(得分:1)

不确定它是否相关,但是当您的表单有效时,您会$this->redirect($this->generateUrl('brand'));。问题是$this->redirect()只是创建一个重定向响应,您的控制器必须返回才能将其考虑在内。换句话说,只是在控制器中间执行$this->redirect()什么也不做(除了对由PHP进行垃圾收集的RedirectResponse进行实例化)。

答案 3 :(得分:0)

如果使用树枝模板,您可以在那里清除它。 例如:

{{ form_start(form) }}
    {{ form_widget(form.yourFieldNameHere, { 'value': '' }) }}
{{ form_end(form) }}