symfony 应为“string”类型的参数,但在属性路径中给定了“null”

mmvthczy  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(128)

实际上,当我试图通过发送空字段来编辑表单时,出现了上述错误,
我的UserType类如下所示:

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,
        ]);
    }
}
3zwtqj6y

3zwtqj6y1#

此问题可通过在***构建器添加函数***中添加'empty_data'参数来解决:
因此,新的UserType类变为:

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,
        ]);
    }
}
jk9hmnmh

jk9hmnmh2#

除了@Mustapha GHLISSI的答案,你可以设置你的字段接受null值:

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

       // your other fields
}

public ?string $firstName将接受字段firstName的字符串和空值。
在PHP 8.0之前,它可能是:

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

相关问题