Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

symfony - How can I clear form values after successful form submission

How can I clear form values after successful form submission?

These didn't help:

CONTROLLER:

namespace CarBrandBundleController;

use CarBrandBundleEntityBrandEntity;
use CarBrandBundleFormTypeBrandType;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;

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;
    }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...