选择的集合类型无法通过验证
Collection type of choices can't pass validation
我创建了一个带有选择集合类型的表单。
$builder->add('roles', CollectionType::class, [
'entry_type' => ChoiceType::class,
'entry_options' => [
'choices' => ['Admin' => 'ROLE_ADMIN', 'User' => 'ROLE_USER'],
'label' => false,
],
])
roles字段在用户实体中定义如下:
/**
* @ORM\Column(type="json")
*/
private $roles = [];
然后在用户的实体中 class 我添加了以下方法:
public static function loadValidatorMetadata(ClassMetadata $metadata) {
$metadata->addPropertyConstraint('roles', new Assert\Choice(['ROLE_ADMIN', 'ROLE_USER']));
}
每次我尝试提交表单时都会收到验证错误:"The value you selected is not a valid choice."
screenshot of my form
奇怪的是,错误消息显示在所有字段上方,这意味着错误与任何可用字段无关。
具有角色的 select 的名称是自动创建的 user[roles][0]
。
如果我关闭验证,所有数据都会正确保存到数据库中。
Assert\Choice 期望字段 "role" 的值是标量类型,但角色是集合。要使用 Assert\Choice 验证集合,您需要这样做
$metadata->addPropertyConstraint('roles', new Assert\All([
'constraints' => [
new Assert\Choice(['ROLE_ADMIN', 'ROLE_USER'])
],
]));
我创建了一个带有选择集合类型的表单。
$builder->add('roles', CollectionType::class, [
'entry_type' => ChoiceType::class,
'entry_options' => [
'choices' => ['Admin' => 'ROLE_ADMIN', 'User' => 'ROLE_USER'],
'label' => false,
],
])
roles字段在用户实体中定义如下:
/**
* @ORM\Column(type="json")
*/
private $roles = [];
然后在用户的实体中 class 我添加了以下方法:
public static function loadValidatorMetadata(ClassMetadata $metadata) {
$metadata->addPropertyConstraint('roles', new Assert\Choice(['ROLE_ADMIN', 'ROLE_USER']));
}
每次我尝试提交表单时都会收到验证错误:"The value you selected is not a valid choice."
screenshot of my form
奇怪的是,错误消息显示在所有字段上方,这意味着错误与任何可用字段无关。
具有角色的 select 的名称是自动创建的 user[roles][0]
。
如果我关闭验证,所有数据都会正确保存到数据库中。
Assert\Choice 期望字段 "role" 的值是标量类型,但角色是集合。要使用 Assert\Choice 验证集合,您需要这样做
$metadata->addPropertyConstraint('roles', new Assert\All([
'constraints' => [
new Assert\Choice(['ROLE_ADMIN', 'ROLE_USER'])
],
]));