php - Symfony validation only on new form
My validation works for creating a new entity, and not allowing a duplicate description.
How do I make this validation work for updating an entity, as it is, when updating the entity the validator is invoked and displays an error.
I'm still learning Symfony so please let me know any further details I need to provide.
descUnique.php
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class descUnique extends Constraint
{
public $message = 'The description "{{ value }}" is allready in use.';
}
descUniqueValidator.php
class descUniqueValidator extends ConstraintValidator {
/**
* @var Security
*/
private $security;
/**
* @var Em
*/
private $em;
public function __construct(EntityManagerInterface $em, Security $security) {
$this->em = $em;
$this->security = $security;
}
public function validate($value, Constraint $constraint) {
/* @var $constraint \App\Validator\descUnique */
if (null === $value || '' === $value) {
return;
}
$repo = $this->em->getRepository(Carrier::class)
->findUniqueName($this->security->getUser(), $value);
if ($repo) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $value)
->addViolation();
}
}
}
edit
My validator declaration in the entity object.
/**
* @ORM\Column(type="string", length=100)
* @Validator\CarrierDescUnique
*/
private $description;
Answer
Solution:
What is the displayed error?
Without the error message the only thing I can see that could go wrong is that you don't check the type of Constraint
inside the validate method. Could it be that another constraint is being tested in this validator by accident?
Also, the type of $value
is not checked. That might cause some problems in case $value
is neither ''
, null
nor a string (i assumed a string is correct in your case).