我目前正在与ExpressionLanguage验证有关形式验证所需的约束:
我的表格:
我的意愿:
Entity1.id == XX
和Entity2.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.
答案 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();
}
}