I have setup my Entity to have life cycle callback for validation simulating ENUM fields from mySQL.
It works fine, except that when an error is thrown it does not provide the property name and consequently it does not match the format for errors coming from Assert.
In the example below the first error is coming from the callback and does not have the information on the property, while the remainder are generated by Assert and include the property in question:
UsedBundle\AdController
$errors = $this->form_errors->getErrorMessages($form);
\Doctrine\Common\Util\Debug::dump($errors);
array(3) { [0]=> string(14) "Invalid doors!" ["powerHp"]=> array(1) { [0]=> string(32) "This value should be 50 or more." } ["price"]=> array(1) { [0]=> string(34) "This value should be 1000 or more." } }
I can know where the error is coming from because of the message, but this also throws off the function that generate the errors variable for output to the user.
The set up is as follows:
UsedBundle\Entity\Ad
namespace UsedBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* @ORM\Entity(repositoryClass="UsedBundle\Repository\AdRepository")
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="ads")
*/
class Ad
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(type="smallint",length=4,unique=true,options={"unsigned":true})
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
......
public static $valid_doors = array(
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
);
/**
* @Assert\Callback
*/
public function validate(ExecutionContextInterface $context, $payload)
{
if (!in_array($this->getdoors(), self::$valid_doors)) {
$context->buildViolation('Invalid doors!')
->atPath('doors')
->addViolation();
}
}
}
In your case (of course if your Symfony version isn't older then 2.4), I can suggest to use static validate function. When you use static function - you have to pass the $object!
/**
* @static validate
*
* @param $object
* @param ExecutionContextInterface $context
*/
public static function validate($object, ExecutionContextInterface $context)
{
if (!in_array($object->getdoors(), self::$valid_doors)) {
$context->buildViolation('Invalid doors!')
->atPath('doors')
->addViolation();
}
}
As you can see - there is no annotation /** @Assert\Callback */
! Besides don't have to write class annotation @ORM\HasLifecycleCallbacks
. Hope it helps!