根据另一个实体的数据验证原则实体

时间:2013-07-29 19:37:25

标签: php symfony orm doctrine

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

  

实体PossibleArticleConfiguration
  名称:第一条   MinLength:250   MaxLength:500
  最小宽度:250
  MaxWidth:500

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

  

实体

     

ConfiguredArticle

     

姓名:第一条

     

长度:300

     

宽度:400

是否有最佳做法可根据PossibleArticleConfiguration中的最小和最大范围验证ConfiguredArticle对象?

提前致谢

2 个答案:

答案 0 :(得分:0)

在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

答案 1 :(得分:0)

我会创建一个自定义约束。如果两个实体未与映射关联,则可以注入对象管理器。如果您已为实体映射关联,则回调也可能有效。

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

相关问题