2013-03-20 49 views
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'])) ?> 
+0

將'validators.XX.yml'放入'app/Resources/{your_bundle}/transalations /'或'src/your/bundle/Resources/transalition /'中。 – 2013-03-20 16:52:26

+0

我做到了。但它沒有幫助。有什麼建議麼? – craphunter 2013-03-20 17:20:51

+0

嘿,如果你有興趣,我發佈了一個解決方案。無論如何感謝您的建議。 – craphunter 2013-03-20 17:56:47

回答

0

我有一個解決方案,但我想它是不是很好:

在我經過每一個可能的錯誤變量的作用。

'constraints' => array(new CheckChoicesDateId(array('date_ids' => $date_ids, 'error_date_0 => $this->get('translator')...., 'error_date_1 => $this->get('translator').... ))), 

,並在自定義驗證我呼籲每一個錯誤的正確變量,$constraint->error_date_X

不好,但它工作。如果有人有更好的解決方案,隨時發佈!