Symfony 5 在表单提交后向表单添加字段

Symfony 5 add field to form after form submit

假设我有以下形式:

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,这很公平。

另一件我可以做但我非常不想做的事情是在控制器中创建一个新实体,设置我从表单中获取的数据并保存它。

if ($form->isSubmitted() && $form->isValid()) {
    $formData = $form->getData();
    $entity = new Paste();
    $entity->setCreatedAt($formData->get('createdAt')->getData());
    ...

我还可以为表单创建一些通用的父级并对其进行修改,但这似乎更加 hacky。


我不反对这里的另一种方法。也许我一开始就看错了。

如果你想修改数据,你不应该调用 $form->setData() 因为这是内部处理的。

->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
    $class= $event->getData();
    $class['new_field'] = 'some_data';
    $event->setData($class);
});

但您可以改用 $event->setData()。