Symfony 2.1 FOSUser翻译错误消息

Symfony 2.1 FOSUser翻译错误消息,symfony,symfony-2.1,fosuserbundle,Symfony,Symfony 2.1,Fosuserbundle,我使用以下代码获取表单中的所有错误: // 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) {

我使用以下代码获取表单中的所有错误:

  // 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();

这并不能解释错误。有人能帮我解决这个问题吗?

你应该使用翻译服务来翻译信息 试试这个:

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;
}