How to clear field value with Symfony2 forms

后端 未结 3 2130
日久生厌
日久生厌 2021-02-14 00:56

I\'m writing my own CAPTCHA class and when the form doesn\'t validate, I don\'t want to pre-populate the captcha input with the previous answer, for obvious reasons. I just want

3条回答
  •  失恋的感觉
    2021-02-14 01:10

    There is a funny way to modify the Request before handling it. However I'd look into Stephan's answer as it seems more clean.

    Something like so:

    public function indexAction(Request $request)
    {
    
        $form = $this->createForm(Form::class);
    
        $subData=$request->request->get('form');
    
        $subData['task']=null;
    
        $request->request->set('form',$subData);
    
        $form->handleRequest($request);
    
    
        if ($form->isValid()) {
    
          //do stuff
        }
    
    
        return $this->render('default/index.html.twig', array(
            'form' => $form->createView()
        ));
    }
    

    Get submitted data with the name 'form' as an array of values, change the said value to null, then set the request's value with the new one and have the form handle it.

    And a simple form

    class Form extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('task')
                ->add('save', SubmitType::class);    
    
        }
    
    }
    

    No matter what you type, the data will always be null after submitting the form. Of course, you need to verify the captcha before setting the value to null.

提交回复
热议问题