How to translate exception headers in Yii 2?

My Yii 2 app (based on the basic app schema) still displays English headers for exceptions, such NotFoundHttpException

as when the user switches the site language to a non-English language. Any other element on the page is translated correctly. Where are the exception headers stored? How can I fix this problem?

I tried to search for an exception class ( NotFoundHttpException

> HttpException

> UserException

> Exception

) and found nothing. I was looking through the based translation files and found that /vendor/yiisoft/yii2/messages/

there are only strings for files The requested view "{name}" was not found.

and Page not found.

for translations. There are no lines Not Found

or Not Found (

to do the correct translation of the exception header NotFoundHttpException

(and others) in non-english languages.

Related readings:

+3


source to share


1 answer


There is no built-in translation of error messages or status codes. You can implement a custom one ErrorAction

to translate HTTP response codes. The documentation yii\web\ErrorAction

contains information on how to proceed.

An alternative solution would be to use a custom HttpException

and overwrite function getName

, but this would require replicating all the error classes you want to use.

Example:

Translation characteristics:

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 far as error messages are concerned, Yii's error constructors accept a message as an optional argument, so the message can be chosen freely.

This means that findModel

something like the following would have to be added in the controller method .

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

      

The code generator gii

does not do this automatically, even if it offers a command line flag --enableI18N

. This may be considered a bug.

+4


source







All Articles