2012-10-21 81 views
0

我用下面的代碼獲取表單中的所有錯誤:Symfony的2.1 FOSUser翻譯錯誤消息

// get all the errors in the form in an array 
    public static function getErrorMessages(\Symfony\Component\Form\Form $form) { 
    $errors = array(); 

    // actual errors 
    foreach ($form->getErrors() as $key => $error) { 
     $errors[] = $error->getMessage(); 
    } 

    // find children that are not valid 
    if ($form->count()>0) { 
     foreach ($form->all() as $child) { 
      if (!$child->isValid()) { 
       $errors[$child->getName()] = formHelper::getErrorMessages($child); 
      } 
     } 
    } 

工程。唯一的問題是FOSUser:我已經定義了我的驗證組,並且錯誤沒有被翻譯。而不是得到「密碼太短」我得到「fos_user.password.short」。問題是與行:

$errors[] = $error->getMessage(); 

這不會轉換錯誤。任何人都可以幫我解決這個問題?

回答

0

您應該使用翻譯服務來翻譯的消息 試試這個:

public function getFormErrorsAssoc(FormInterface $form) { 
    $errors = array();                                 
    /* @var \Symfony\Component\Form\FormError $error*/                         
    foreach ($form->getErrors() as $key => $error) {                          
     $message = $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), 'validators'); 
     if ($message) { 
      $errors[$key] = $message; 
     } 
    } 
    if ($form->hasChildren()) { 
     /* @var FormInterface $child*/ 
     foreach ($form->getChildren() as $child) { 
      $label = $child->getAttribute('label') ? : $child->getName(); 
      if (!$child->isValid()) { 
       $errors[$label] = $this->getFormErrorsAssoc($child); 
      } 
     } 
    } 

    return $errors; 
}