我有一个产品表,它与产品到部门表之间存在一对多关系,其中产品可以与一个或多个部门相关联。
我在添加新产品以验证我的部门时遇到问题。
如果我不选择部门,表格仍会验证并提交。
这是我构建表单的地方。
class NewProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('departments', 'collection', array(
'type' => new ProductDepartmentType(),
'required' => true,
));
...
该集合是通过 ProductDepartmentType 类设置的:
class ProductDepartmentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('department', 'entity', array(
'property' => 'indentedName',
'class' => 'WebIllumination\SiteBundle\Entity\Department',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('d')
->addSelect('dd')
->leftJoin('d.descriptions', 'dd')
->orderBy('d.displayOrder', 'ASC');
},
'required' => true,
'empty_value' => '- Select a Department -',
), array());
$builder->add('displayOrder', 'hidden');
}
public function getDefaultOptions(array $options)
{
$collectionConstraint = new Collection(array(
'department' => array(
new NotBlank(array('message' => 'Select a department.')),
),
));
return array(
'validation_constraint' => $collectionConstraint,
);
}
public function getName()
{
return 'site_product_department';
}
}
然后我尝试将以下内容添加到 ProductDepartmentType 中:
class ProductDepartmentType extends AbstractType
{
...
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'WebIllumination\SiteBundle\Entity\ProductToDepartment'
));
}
...
这没有任何影响,并且表单仍然可以在未经验证的情况下提交。
谁能帮我弄清楚如何验证这个字段?