1

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

我的 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

如何翻译错误消息?

4

1 回答 1

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')
);
于 2013-02-03T00:03:11.403 回答