gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:11:48 25 4
gpt4 key购买 nike

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

这些没有帮助:

  • How to clear field value with Symfony2 forms
  • Clear form values after successful submit

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

    最佳答案

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

        if ($form->isSubmitted() && $form->isValid()) {
    // ... perform some action, such as saving the task to the database
    return $this->redirect($request->getUri());
    }
    我已将示例源添加到 GitHub

    关于symfony - 表单提交成功后如何清除表单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24229839/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com