1
我做了一個自定義約束驗證器。驗證器正在工作。但是,如何在php模板中翻譯CUSTOM驗證器的錯誤消息?其他驗證器消息正在工作,所以我確實在app/config/validators.XX.yml
中有翻譯。在php模板中自定義驗證器的翻譯
在我的行動:
$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'])) ?>
將'validators.XX.yml'放入'app/Resources/{your_bundle}/transalations /'或'src/your/bundle/Resources/transalition /'中。 – 2013-03-20 16:52:26
我做到了。但它沒有幫助。有什麼建議麼? – craphunter 2013-03-20 17:20:51
嘿,如果你有興趣,我發佈了一個解決方案。無論如何感謝您的建議。 – craphunter 2013-03-20 17:56:47