After hours of debugging the complete vendor/symfony/form/Form
I was only able to find out that the FormEvents::SUBMIT
converts my null
value to Object
.
This is my code.
$form = $this->createForm(PersonType::class, new Person());
$form->submit($request->request->all(), false);
if ($form->isSubmitted() && $form->isValid())
{
$em->persist($entity);
$em->flush();
return $entity;
}
return $form->getErrors(true, true);
Then I send this request.
POST /api/persons/e3d90966-b2e7-4503-959f-da989c73c185
{
"name": {"firstName": "John", "lastName": "Doe"}
}
It sets the name of the person to John Doe
.
Now I want to clear it:
POST /api/persons/e3d90966-b2e7-4503-959f-da989c73c185
{
"name": null
}
And et voilà: The name is still John Doe
.
I'm using a custom type:
class NameType extends AbstractType
{
private EntityManagerInterface $manager;
public function __construct(EntityManagerInterface $manager)
{
$this->manager = $manager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('firstName', TextType::class)
->add('lastName', TextType::class)
;
$builder->addModelTransformer(new NameTransformer($this->manager));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Name::class,
'compound' => true
]);
}
}
And is used via:
$builder
->add('name', NameType::class)
;
Some more informations:
My Answer:
1. The issue you are facing is related to how Symfony handles form submission and data transformation. When you submit a form with null values, Symfony converts them into objects based on the data class defined in your form type.
2. In your case, the NameType form type is responsible for transforming the form data into a Name object. When you submit null values for the name field, Symfony still converts it into a Name object because of the data_class option set in the configureOptions method.
3. To solve this issue and clear the name field, you can handle the null values in your form type's data transformer. You can check if the submitted value is null and set the corresponding properties of the Name object to null as well.
4. Alternatively, you can create a custom form event listener or subscriber to intercept the form submission process and handle null values before they are converted into objects.
5. It's important to understand how Symfony's form component works and how data transformation is handled to effectively troubleshoot and resolve issues like this. You may need to dive deeper into Symfony's form documentation and source code to fully understand the behavior of form submission and data transformation.
Rate this post
3 of 5 based on 6156 votesComments