实际上,当我尝试通过发送空字段来编辑表单时,会出现上述错误,
我的 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,
]);
}
}
这个问题可以通过在builder添加函数中添加'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,
]);
}
}
您可以将字段设置为接受
null
值,而不是@Mustapha GHLISSI答案:
<?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;
}
如果您不喜欢数据库中出现的 NULL,那么您有 2 个选择
class User
{
public string $firstName;
public function setFirstName(?string $firstName): self
{
if ($firstName === null) {
$firstName = '';
}
$this->firstName = $firstName;
return $this;
}
}
empty_data
选项。我不知道为什么 Mustapha 在他的答案中使用 empty_data
选项前后的星星。class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('firstName', TextType::class, [
'label' => 'Prénom',
'required' => false,
'empty_data' => '',
])
->add('lastName', null, [
'label' => 'Nom',
'required' => false,
'empty_data' => ''
])
;
}
}