假设我有以下形式:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('paste', TextareaType::class, [
'attr' => array('rows' => '15'),
])
->add('language', ChoiceType::class, ['choices' => $this->languagesService->getSupportedLanguages()])
->add('visibility', ChoiceType::class, ['choices' => $this->visibilityService->getVisibilities()])
->add('expiresAt', ChoiceType::class, ['choices' => $this->expiryService->getExpiryTimes(), 'mapped' => false])
->add('name', TextType::class, ['required' => false])
->add('save', SubmitType::class, ['label' => 'Submit'])
;
}
提交表单后,我想向其中添加用户无法完成的另一个字段。让我们打电话给有问题的领域new_field
。
到目前为止,我已经尝试使用表单事件:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('paste', TextareaType::class, [
'attr' => array('rows' => '15'),
])
->add('language', ChoiceType::class, ['choices' => $this->languagesService->getSupportedLanguages()])
->add('visibility', ChoiceType::class, ['choices' => $this->visibilityService->getVisibilities()])
->add('expiresAt', ChoiceType::class, ['choices' => $this->expiryService->getExpiryTimes(), 'mapped' => false])
->add('name', TextType::class, ['required' => false])
->add('save', SubmitType::class, ['label' => 'Submit'])
->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
$form->add('new_field')->setData('some_data');
})
;
}
而且我显然遇到了一个异常:You cannot add children to a submitted form
,这很公平。
我可以做的另一件事,我非常不想做,因为它看起来很hacky是在控制器中创建一个新实体,设置我从表单获得的数据并保存它。
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
$entity = new Paste();
$entity->setCreatedAt($formData->get('createdAt')->getData());
...
我还可以为表单创建一些通用父级并对其进行修改,但这似乎更加hacky。
我不反对这里的另一种方法。也许我一开始就看错了。