【问题标题】:Validate doctrine entity based on another entity's data根据另一个实体的数据验证学说实体
【发布时间】:2013-07-29 19:37:25
【问题描述】:

我想用 symfony2 构建一个文章配置器。 在我的第一个实体中存储了所有可能的文章配置。

实体可能的ArticleConfiguration
名称:第一条
最小长度:250 最大长度:500
最小宽度:250
最大宽度:500

我的第二个实体中的一个对象如下所示:

实体

配置文章

名称:第一篇

长度:300

宽度:400

是否有任何最佳实践可以根据 PossibleArticleConfiguration 中的最小和最大范围来验证 ConfiguredArticle 对象?

提前致谢

【问题讨论】:

  • 是否有类似 ConfiguredArticle -> PossibleArticleConfiguration ( one-to-many / one-to-tone ) 的关系?
  • 是的,有一个关系 ConfiguredArticle/Material OneToMany ManyToOne PossibleArticleConfiguration/Material

标签: php symfony orm doctrine


【解决方案1】:

我会创建一个自定义约束。如果这两个实体没有与映射关联,您可以注入对象管理器。如果您已映射实体的关联,回调也可能会起作用。

http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

【讨论】:

    【解决方案2】:

    在 ConfiguredArticle 实体中,您可以使用以下方法:

    public function isLengthValid(ExecutionContextInterface $context)   {
        if ($this->getLength < $this->getArticleConfiguration()->getMinLength()) {
            $context->addViolationAt('length', 'The length does not satisfy the minimum length', array(), null);
        }
        if ($this->getLength > $this->getArticleConfiguration()->getMaxLength()) {
            $context->addViolationAt('length', 'The length does not satisfy the maximum length', array(), null);
        }
    }
    
    public function isWidthValid(ExecutionContextInterface $context)    {
        if ($this->getWidth < $this->getArticleConfiguration()->getMinWidth()) {
            $context->addViolationAt('width', 'The width does not satisfy the minimum width', array(), null);
        }
        if ($this->getWidth > $this->getArticleConfiguration()->getMaxWidth()) {
            $context->addViolationAt('width', 'The width does not satisfy the maximum width', array(), null);
        }
    }
    

    在此页面上阅读有关如何使用回调方法进行验证的更多信息:http://symfony.com/doc/current/reference/constraints/Callback.html

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多