trejder
trejder

Reputation: 17505

How to translate exception titles in Yii 2?

My Yii 2 application (based on app-basic scheme) still display English titles for exceptions like for example NotFoundHttpException, when user switches site language to non-English. Any other page element is correctly translated. Where titles of exceptions are stored? How can I fix this problem?

I tried searching through exception classes (NotFoundHttpException > HttpException > UserException > Exception) and found nothing. I browsed based translation files and found that /vendor/yiisoft/yii2/messages/ files have only The requested view "{name}" was not found. and Page not found. string for translations. There is no Not Found or Not Found ( strings to make correct translation of NotFoundHttpException (and others) exception's title in non-English languages.

Related readings:

Upvotes: 4

Views: 1322

Answers (1)

tarleb
tarleb

Reputation: 22619

There is no build-in translation of error or status code messages. One could implement a custom ErrorAction to translate the HTTP response codes. The documentation of yii\web\ErrorAction has the details of how to proceed.

An alternative solution would be to use custom HttpExceptions and overwrite the getName function, but this would require you replicate all error classes you want to use.

Example:

Translation trait:

namespace app\errors;

use Yii;

trait TranslateHttpCodes {
    public function getName()
    {
        return Yii::t('app', parent::getName());
    }
}

Custom error:

namespace app\error;

class NotFoundHttpException extends \yii\web\NotFoundHttpException
{
   use TranslateHttpCodes;
}

As for error messages, the Yii error constructors take a message as an optional argument, so the message can be chosen freely.

What this means is that one would have to put something like the following in the findModel controller method.

throw new NotFoundHttpException(\Yii::t('app', 'The requested page does not exist.');

The gii code generator doesn't do this automatically, even though it offers an --enableI18N command line flag. This might be considered a bug.

Upvotes: 5

Related Questions