我有两个模型和两种表单类型:
class User
{
private $name;
/**
* @Assert\Valid()
*/
private $address;
}
-
class Address
{
/**
* @Assert\NotBlank(groups={"street"})
*/
private $street;
/**
* @Assert\NotBlank(groups={"number"})
*/
private $number;
}
表单类型:
class AddressType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('street', TextType::class, [
'required' => false
])
->add('number', IntegerType::class, [
'required' => false
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Address::class,
'validation_groups' => ['number']
]);
}
}
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'required' => false
])
->add('address', AddressType::class)
->add('submit', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class
]);
}
}
但是验证不起作用(对于AddressType中的字段编号)。此外,当我在表单类型定义中添加约束时:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'required' => false
])
->add('address', AddressType::class, [
'constraints' => [
new Valid()
]
])
->add('submit', SubmitType::class);
}
验证开始工作。这对我来说很奇怪,我也不知道为什么。也许我的方法不好? UserType中的注释和配置有何区别?