I am attempting to apply this symfony callback constraint reference, but I am getting the following error:
[] targeted by Callback constraint is not a valid callable
I've also seen this question, which did not help much.
So, what I am trying to do is to limit input to a entity field to a defined array of items ( self::$valid_years in the code below ).
I also did a dump on the variable $method on class below, which generates the error, and in fact the $method variable is an empty array.
Symfony\Component\Validator\Constraints\CallbackValidaor.php
This is the entity:
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