I have a minimum age custom validator which is straight forward enough:
The constraint(Minage.php)
namespace MyCompany\VisitBundle\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Minage extends Constraint
{
public $message = 'The user must be {{ age }} or over';
public $age = 18;
public function validatedBy()
{
return get_class($this).'Validator';
}
}
The validator (MinageValidator.php)
namespace MyCompany\VisitBundle\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class MinageValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
$minAge = strtotime(sprintf("-%s YEAR", $constraint->age));
if(strtotime($value->format("Y-m-d")) > $minAge)
{
$this->setMessage($constraint->message,
array('{{ age }}' => $constraint->age));
return false;
}
return true;
}
}
In my entity (stripping parts which aren’t important)
use MyCompany\VisitBundle\Component\Validator\Constraints as MyCompanyAssert;
/**
* @ORM\Column(name="birth_date", type="datetime")
* @MyCompanyAssert\Minage(age="18")
*/
private $birth_date;
And in twig:
{{ form_errors(form.birth_date) }}
{{ form_widget(form.birth_date) }}
I know for sure the validator is returning false but my form refuses to show the error message All other validators (out-of-the-box not custom) work fine and show their respective errors. Any idea?
Translations are disabled, so it won’t be looking for a translation in a file.
Thanks in advance.
UPDATE: form_errors(form.birth_date) does not work but form_errors(form) does? why is it assigned as a global form error?
The reason of this behavior is error bubbling. Set the field’s
error_bubblingoption tofalse.