我有两个实体,“页面”和“部分”。实体“Page”与实体“Section”具有一对多关系。
我创建了一个包含页面和部分集合的表单。我想验证一个页面是否至少有一个部分。
我在我的验证 yml 文件中尝试了这个。
App\MyBundle\Entity\Page:
properties:
sections:
- Valid: ~
是否存在任何可以用来处理此问题的约束?或者我必须为此问题编写一个自己的验证器?
最佳答案
如果您想查看您的页面至少有一个 Section
,那么您必须查看该 Collection
部分是否大于 0。
App\MyBundle\Entity\Page:
properties:
sections:
- Count: { min: 1, minMessage: "You need to have at least one Section" }
如果您想查看您的Section对象是否也有效,那么您需要为您的Section实体和PageType表单设置验证策略cascade_validation => true
,例如:
App\MyBundle\Entity\Section:
properties:
name:
- NotBlank
和你的FormType
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\MyBundle\Entity\Page',
'cascade_validation' => true,
));
}
关于symfony - 验证相关实体,至少一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29277446/