了解表单事件 - Symfony

问题描述 投票:0回答:1

让我说我的形式像跟在我的控制器

$data = [];
    $form = $this->createFormBuilder($data)
            ->add('username', 'text', [ 'mapped' => FALSE, 'required' => FALSE ])
            ->add('show_email', 'checkbox', [ 'mapped' => FALSE, 'required' => FALSE ])
            ->add('submit', 'submit')
            ->addEventListener(\Symfony\Component\Form\FormEvents::PRE_SUBMIT, function($event){
                $user = $event->getData();
                $form = $event->getForm();

                if (true == $user['show_email']) {
                    $form->add('email', 'email', [
                        'required' => FALSE,
                         'data' => '[email protected]'
                    ]); 
                }

                $form->setData($user);
            })
            ->getForm()
            ;
    $form->handleRequest($request);

当用户检查PRE_SUBMIT时,我正在听email事件添加show_email字段。在PRE_SUBMIT期间,email字段成功添加但当我尝试在该字段中分配数据时,它不会显示在表单视图中。在示例中,我使用'data' => '[email protected]'email field添加值,但该值未填充在电子邮件字段中。那我在这里弄错了什么?

symfony symfony-forms symfony-2.8
1个回答
1
投票

我通过将email字段值添加到event data来解决了这个问题,就像$data['email'] = "[email protected]"一样,然后再次reassign事件数据$event->setData($data)

 ->addEventListener(\Symfony\Component\Form\FormEvents::PRE_SUBMIT, function($event){

                $form = $event->getForm();
                $data = $event->getData();

                if(isset($data['showEmail']) && $data['showEmail'] == TRUE){
                    $form->add('email', 'email', [
                       'mapped' => FALSE ,
                    ]);
                    $data['email'] = "[email protected]";
                }
                else
                {
                    unset($data['email']);
                }

                $event->setData($data);
            })
© www.soinside.com 2019 - 2024. All rights reserved.