让我说我的形式像跟在我的控制器
$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
添加值,但该值未填充在电子邮件字段中。那我在这里弄错了什么?
我通过将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);
})