Lets assume I have the following form:
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'])
;
}
Once the form is submitted I want to add another field to it that the user cannot complete. Lets call the field in question new_field.
So far I've tried using a form event:
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');
})
;
}
And I obviously get an exception thrown my way: You cannot add children to a submitted form, which is fair enough.
Another thing I could do, which I very much don't want to do because it seems hacky is create a new entity in the controller, set the data I get from the form there and save it.
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
$entity = new Paste();
$entity->setCreatedAt($formData->get('createdAt')->getData());
...
I could also create some generic parent to the form and modify that, but that seems even more hacky.
I'm not opposed to another approach here. Perhaps I'm looking at this wrong to begin with.