约束不能放在属性或getter上

Neo*_*tex 6 php validation constraints symfony

我尝试在symfony 3中创建自定义约束

我有错误

约束App\Bundle\MyBundle\Validator\Constraints\Code不能放在属性或getter上

<?php
// vendor/app/mybundle/Validator/Constraints/Code.php

namespace App\Bundle\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;


class Code extends Constraint
{
    public $message = 'Error validate message!!!';
    public function validatedBy()
    {
        return 'alias_name';
    }

    public function getTargets()
    {
      //return self::CLASS_CONSTRAINT; // error "The constraint cannot be put on properties or getters"
      return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT); // working, but $value is a STRING!!!
    }
 }
Run Code Online (Sandbox Code Playgroud)

我的vendor/app/mybundle/Validator/Constraints/CodeValidator.php

<?php
// vendor/app/mybundle/Validator/Constraints/CodeValidator.php

namespace App\Bundle\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class CodeValidator extends ConstraintValidator
{
     public function validate($value, Constraint $constraint)
     {
         $value->getId(); // this code not working, because $value is STRING!!
         $this->context->buildViolation($constraint->message)
             ->atPath('code')
             ->addViolation();
     }
Run Code Online (Sandbox Code Playgroud)

}

哪里弄错了?

cha*_*asr 7

尝试将此添加到您的约束中:

/**
 * @Annotation
 * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
 */
Run Code Online (Sandbox Code Playgroud)

编辑

今天早上,我花时间尝试在新的symfony 3安装上实现.

此外,如果您添加如下所示@AcmeAssert\Code的属性:

use AppBundle\Validator\Constraints as AcmeAssert;

// ...

/**
 * @var string
 * @AcmeAssert\Code
 * @ORM\Column(name="code", type="string")
 */
private $code;
Run Code Online (Sandbox Code Playgroud)

仅验证字段,因此$value表示属性的字段值.
例如,如果您指定@AcmeAssert\Code$code在你的实体属性,当表单提交时,$value你的校验器将代表您的字段值$code属性).

如果您添加@AcmeAssert\Code实体顶部,如下所示:

use AppBundle\Validator\Constraints as AcmeAssert;

/**
 * Foo
 *
 * @ORM\Table(name="foo")
 * @AcmeAssert\Code
 * @ORM\Entity(repositoryClass="AppBundle\Repository\FooRepository")
 */
class Foo
Run Code Online (Sandbox Code Playgroud)

然后,$ value将代表您的完整实体,您可以使用getter进行所需的所有验证.

我已将我的测试项目添加到存储库中,您可以使用它来查看如何使用两个替代方案:sf3-constraint-test

在我的示例中,实体AppBundle::Bar具有属性约束,并且AppBundle::Foo对整个实体具有约束.

希望这是你需要的!

EDIT2

如果您处于yaml映射中,请使用以下命令对整个实体应用约束,并在约束中访问完整对象$value:

AppBundle\Entity\AcmeEntity:
    constraints:
        - App\Bundle\MyBundle\Validator\Constraints\Code: ~
Run Code Online (Sandbox Code Playgroud)

在您的映射之上.

如果你想只在一个属性上应用约束,并使用,访问字段的值$value,保持你的方式,你的逻辑$value是一个字符串(对应于映射中约束的实体属性的字段的值),它是就像是 :

AppBundle\Entity\AcmeEntity:
    properties:
            # ...
            code:
                - App\Bundle\MyBundle\Validator\Constraints\Code: ~
Run Code Online (Sandbox Code Playgroud)