Search code examples
ajaxsymfonyfosuserbundle

Translate messages using ajax form to login


I'm using symfony 3.2 and I'd like to login with ajax form. Everything works fine except messages are not translated.

this is the AjaxAuthenticationFailureHandler class

class AjaxAuthenticationFailureHandler extends DefaultAuthenticationFailureHandler
{
/**
 * @var mixed
 */
private $translator;

/**
 * @param \Symfony\Component\HttpKernel\HttpKernelInterface $httpKernel
 * @param \Symfony\Component\Security\Http\HttpUtils        $httpUtils
 * @param array                                             $options
 * @param \Psr\Log\LoggerInterface                          $logger
 * @param mixed                                             $translator
 */
public function __construct(HttpKernelInterface $httpKernel, HttpUtils $httpUtils, array $options, LoggerInterface $logger = null, $translator = null)
{
    parent::__construct($httpKernel, $httpUtils, $options, $logger);

    $this->translator = $translator;
}

/**
* {@inheritDoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    if ($request->isXmlHttpRequest()) {
        return new Response(json_encode(array(
            'has_error' => true,
            'message'     => $this->translator->trans($exception->getMessage())
        )));
    }

    return parent::onAuthenticationFailure($request, $exception);
}

Solution for symfony 4:

For symfony 4 we can do like this:

'message' => $this->translator->trans($exception->getMessageKey(), array(), 'security'),

Solution

  • Try changing your translation line to this:

    $this->translator->trans($exception->getMessage(), array(), 'messages')
    

    then create translation file in your Resources/translations folder for each language i.e. messages.en.yml, messages.fr.yml, etc...

    your $exception->getMessage() should try and return translation keys to simplify things so for example it should return "error.name.missing" and then in the yml translation file you'd have:

    error.name.missing: 'The name cannot be missing'