关于Symfony2验证约束表达式的实际案例

时间:2016-01-04 13:59:06

标签: validation symfony expression constraints yaml

我目前正在与ExpressionLanguage验证有关形式验证所需的约束:

我的表格:

  • 文字项目
  • Entity1项目选择器(下拉列表)
  • Entity2项目选择器(下拉列表)
  • Textarea项目

我的意愿:

  • 条件文本项上的一个错误触发器为空且 Entity1 选择器为空
  • 条件为另一个错误触发器:Entity1.id == XXEntity2.id == YY且Textarea为空

到目前为止,我在validation.yml中得到了这个:

Experveo\ShopBundle\Entity\Vehicle:
    constraints:
        - Expression:
            expression: "this.getTextItem() != '' |  this.getEntity1() != ''"
            message: error1.

似乎我需要将相反的条件设为可行。到目前为止,我没有在documentation上找到任何高级线索,也没有找到in expression language syntax help

我怎样才能达到这些条件?以下根本不起作用......

- Expression:    
    expression: >
        this.getTextItem() == ''
        && this.getEntity1() != ''
        && this.getEntity1().getId() === 49
        && this.getEntity2() != ''
        && this.getEntity2() === 914
        && this.getTextAreaItem() == ''"
    message: error2.

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。当我在2.4上运行并根据稍后合并的this fix时,ExpressionValidator错误地跳过了null或空字符串值的验证。

因此,回调选项是正确的解决方法,如this other SO post中所述。就我而言:

 /**
 * @Assert\Callback
 *
 * Using a callback is a better solution insted of make an "Assert\Expression" for the class,
 * because of a Symfony bug where the ExpressionValidator skip validating if the value if empty or null.
 * Exemple for information : https://stackoverflow.com/questions/24649713/assert-expression-validation-not-working-at-attribute-level-in-symfony-2-4
 */
public function validate(ExecutionContextInterface $context)
{
    if( '' === $this->getTextItem() && '' === $this->getMark() ){
        $context->buildViolation("error 1")
            ->addViolation();
    }

    if( '' === $this->getTextItem()
        && '' === $this->getTextAreaItem()
        && (( $this->getEntity1() && $this->getEntity1()->getId() === self::ENTITY1_VALUE)
             || ($this->getEntity2() && $this->getEntity2()->getId() === self::ENTITY2_VALUE))  
    ){
        $context->buildViolation("error2")
            ->addViolation();
    }
}
相关问题