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

Practical case on Symfony2 validation constraint expression

我目前正在与 ExpressionLanguage 验证有关表单验证所需的约束进行斗争:

我的表格:

我的愿望:

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

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

看来我需要输入 相反的条件 才能让它工作。到目前为止,我没有在 documentation, nor in expression language syntax help.

上找到任何高级线索

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

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

我终于找到了解决办法。正如我在 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 : 
 */
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();
    }
}