7

Actually when I try to edit the form by sending empty fields, the above error comes on ,

My UserType class looks like:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', null, [
                'label' => 'Prénom'
            ])
            ->add('lastName', null, [
                'label' => 'Nom'
            ])
            ->add('email', EmailType::class, [
                'label' => 'Adresse e-mail'
            ])
            ->add('password', PasswordType::class, [
                'label' => 'Mot de passe'
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}
Mustapha GHLISSI
  • 1,485
  • 1
  • 15
  • 16

2 Answers2

21

This problem can be resolved by adding 'empty_data' param in the builder add function:

So the new UserType classe becomes:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', null, [
                'label' => 'Prénom',
                **'empty_data' => ''**
            ])
            ->add('lastName', null, [
                'label' => 'Nom',
                **'empty_data' => ''**
            ])
            ->add('email', EmailType::class, [
                'label' => 'Adresse e-mail',
                **'empty_data' => ''**
            ])
            ->add('password', PasswordType::class, [
                'label' => 'Mot de passe',
                **'empty_data' => ''**
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}
Mustapha GHLISSI
  • 1,485
  • 1
  • 15
  • 16
  • For me, it was ChoiceType, had to add `empty_data` and set entity field to nullable and setter/getter to accept nulls (see next answer here). – JohnSmith Jan 21 '23 at 15:35
4

Instead of @Mustapha GHLISSI answer, you can set your field to accept null values:

<?php
    
class User 
{
       public ?string $firstName;

       // your other fields
}

The public ?string $firstName will accept string and null values for the field firstName.

Before PHP 8.0 its maybe:

public function setFirstName(string $firstName = null): self
{
   $this->firstName = $firstName;
   return $this;
}
scasei
  • 457
  • 4
  • 4