我正在尝试应用此功能 symfony callback constraint reference,但我收到以下错误:
Callback约束所针对的[]不是有效的可调用
我也见过this question,但没有多大帮助。
所以,我要做的是将实体字段的输入限制为已定义的项目数组(以下代码中的self :: $ valid_years)。
我还在下面的类上对变量$ method进行了转储,这会生成错误,实际上$ method变量是一个空数组。
的Symfony \元器件\验证\约束\ CallbackValidaor.php
这是实体:
Warranty.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\WarrantyRepository")
* @ORM\Table(name="warranties")
*/
class Warranty
{
/**
* @ORM\Id
* @ORM\OneToOne(targetEntity="Brand")
* @Assert\NotBlank(message="La marque est requise.")
*/
private $brand;
/**
* @ORM\Column(type="string",length=5)
* @Assert\Callback
*/
private $wrYear;
.... some code .....
public static $valid_years;
public static $valid_wrpaint;
public static $valid_wrcorr;
public static $valid_wrtransf;
public function __construct()
{
self::$valid_years = array('0','1','2','3','4','5','ilim');
self::$valid_wrpaint = array('0','1','2','3','4','5','ilim','n/c');
self::$valid_wrcorr = array('0','3','7','8','12','13','ilim','n/c');
self::$valid_wrtransf = array('Y','N','n/c');
}
public function validate(ExecutionContextInterface $context, $payload)
{
\Doctrine\Common\Util\Debug::dump(self::$valid_years);
if (!in_array($this->getWrYear(), self::$valid_years)) {
$context->buildViolation('Invalid year!')
->atPath('wrYear')
->addViolation();
}
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addConstraint(new Assert\Callback('validate'));
}
.... some code....
/**
* Get wrYear
*
* @return string
*/
public function getWrYear()
{
return $this->wrYear;
}
}
validation.yml
AppBundle\Entity\Warranty:
constraints:
- Callback: validate
答案 0 :(得分:2)
验证配置似乎混淆了。使用以下注释配置
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\WarrantyRepository")
* @ORM\Table(name="warranties")
*/
class Warranty
{
/**
* @Assert\Callback
*/
public function validate(ExecutionContextInterface $context, $payload)
{
// ...
}
}
然后删除您的validation.yml配置(yml配置)和loadValidatorMetadata(PHP配置)
答案 1 :(得分:0)
Callback Validator可以通过Symfony调用statically
,这可能是你的数组为空的原因。
您是否可以尝试在__construct
方法之外初始化静态属性,如下所示:
public static $valid_years = array(
'0',
'1',
'2',
'3',
'4',
'5',
'ilim'
);
它也会更清晰:如果您的静态属性值始终相同,为什么要等到实例化一个对象来初始化它们?