Symfony2登录ajax翻译错误信息

时间:2013-02-02 23:47:15

标签: symfony symfony-2.1 fosuserbundle

我想翻译我的ajax登录错误消息。 我正在使用FOSUserBundle,我会利用翻译文件正确覆盖文件夹资源/翻译。

我的AthenticationHandler.php:

class AuthenticationHandler
implements AuthenticationSuccessHandlerInterface,
       AuthenticationFailureHandlerInterface
{

protected $router;
protected $security;
protected $userManager;
protected $service_container;

public function __construct(RouterInterface $router,SecurityContext $security, $userManager, $service_container)
{
    $this->router = $router;
    $this->security = $security;
    $this->userManager = $userManager;
    $this->service_container = $service_container;

}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
    if ($request->isXmlHttpRequest()) {
        //...
    }
    return new RedirectResponse($this->router->generate('anag_new'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {

    if ($request->isXmlHttpRequest()) {
        $error = $exception->getMessage();
        $result = array('success' => false, 'message' => $request->get('translator')->trans($error, array(), 'FOSUserBundle'));
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    } else {
        //...
    }
}

}

但是返回此错误:

Fatal error: Call to a member function trans() on a non-object in /var/www/MyBusiness/src/My/UserBundle/Handler/AuthenticationHandler.php

如何翻译错误消息?

1 个答案:

答案 0 :(得分:2)

$request->get(string $key, mixed $default = null, type $deep = false)用于从GET,PATH,POST,COOKIE获取参数。您正在尝试获取“转换器”参数,该参数可能不存在。因此返回null,并在非对象上调用trans()

只需在AuthenticationHandler中注入“翻译”服务(可能在构造函数中)。或者从服务容器中获取它,因为它在您的类中可用:

$translator = $this->service_container->get('translator');

// ...
$result = array(
    'success' => false,
    'message' => $translator->trans($error, array(), 'FOSUserBundle')
);