从帮助程序转换Symfony表单错误

时间:2015-05-28 09:50:31

标签: php forms symfony translation

我有一个FormErrors帮助器:

class FormErrors implements \JsonSerializable
{

    public function __construct(FormInterface $form)
    {
        $this->form = $form;
    }

    public function all()
    {
        return $this->getErrors($this->form);
    }

    private function getErrors(FormInterface $form)
    {
        $result = array();
        $result[$form->getName()] = array();
        foreach ($form->getErrors() as $error) {
            $result[$form->getName()][] = $error->getMessage();
        }


        foreach ($form->all() as $child)
        {
            $errors = $this->getErrors($child);

            if (count($errors[$child->getName()]))
                $result[$form->getName()][$child->getName()] = $errors[$child->getName()];
        }
        return $result;
    }

    public function jsonSerialize()
    {
        return $this->all();
    }

}

使用如下: return (new \Bundle\Util\FormErrors($form))->all();

但此代码不会返回已翻译的邮件。 文档清楚地说$ error-> getMessage()应该返回翻译的消息。

我通过各地的语言环境设置进行了调试,并且没有设置为英语,但我仍然收到英文消息。

我宁愿不将容器注入帮助器,因为我需要更改帮助器的构造函数,因为我在我的应用程序的许多地方使用此函数,它可能会破坏代码。

1 个答案:

答案 0 :(得分:0)

在" validators.en.yml"中添加错误或指定表单的翻译域可能会有所帮助:

$resolver->setDefaults(array(
    'translation_domain' => 'errors'
));