【问题标题】:Validate a related entity, at least one验证相关实体,至少一个
【发布时间】:2015-03-26 11:38:05
【问题描述】:

我有两个实体,“页面”和“部分”。实体“Page”与实体“Section”具有 oneToMany 关系。

我创建了一个包含页面和部分集合的表单。我想验证一个页面是否至少有一个部分。

我在我的验证 yml 文件中尝试这个。

App\MyBundle\Entity\Page:
    properties:
        sections:
            - Valid: ~

存在我可以用来处理此问题的任何约束吗?还是我必须为此问题编写自己的验证器?

【问题讨论】:

    标签: symfony


    【解决方案1】:

    如果您想查看您的页面至少有一个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 Like:

    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,
            ));
        }
    

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 2011-08-21
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      相关资源
      最近更新 更多