我确实为我构建了一个自定义约束验证器。验证器正在工作。但是如何在 php 模板中翻译 CUSTOM 验证器的错误消息?其他验证器消息正在工作,所以我确实有app/config/validators.XX.yml
.
在我的行动中:
$form = $this->createFormBuilder()
->add('date_id', 'choice', array(
....
'constraints' => array(new CheckChoicesDateId(array('date_ids' => $date_ids))),
....
))
在捆绑/验证器/约束中
class CheckChoicesDateId extends Constraint
{
public $invalidMessage = '{{ value }}';
public $date_ids;
public function __construct($options = null)
{
parent::__construct($options);
if (null === $this->date_ids ) {
throw new MissingOptionsException('Option date_ids must be given for constraint ' . __CLASS__, array('date_ids'));
}
}
}
在捆绑/验证器/约束中
class CheckChoicesDateIdValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint) {
if ($value == NULL || !isset($value)) {
$this->context->addViolation($constraint->invalidMessage, array(
'{{ value }}' => 'error.date.0',
//I also tried $this->get('translator')->trans('error.date.0');
// with the error message: Call to undefined method GET
));
}
if (is_numeric($value)) {
$t = array_key_exists($value, $constraint->date_ids);
if ($t == NULL) {
$this->context->addViolation($constraint->invalidMessage, array(
'{{ value }}' => 'error.date.1',
));
}
}
return;
}
}
在我的模板中:
<?php echo $view['form']->errors($form['date_id']) ?>
//I also tried
<?php echo $this->get('translator')->trans($view['form']->errors($form['date_id'])) ?>