I implemented a structure of API Rest with the models in Yii2. Everything works great for actions (index, create, update etc ...) and methods (GET, POST, PUT etc ..) but I have a problem with the ContentNegotiator
class.
Specifically, if I pass as a parameter of GET the language in which the response is to be translated, this is ignored.
According to the documentation for setting the language of response we need to set allowed languages of ContentNegotiator
(look at my behaviors()
) and make a request like this:
http://localhost/api/v1/users?_lang=it-IT
But the response continues to be in English. Why??? Nothing against the English =)
This is my ActiveController
child class that extend from yii\rest\Controller
.
use yii\rest\ActiveController;
use yii\filters\VerbFilter;
class AActiveController extends ActiveController
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['verbFilter'] = [
'class' => VerbFilter::className(),
'actions' => $this->verbs(),
];
$behaviors['contentNegotiator']['languages'] = [
'en-EN',
'it-IT',
'de-DE',
'ru-RU',
];
return $behaviors;
}
...
N.B.: I debug through yii\filters\ContentNegotiator
class of the framework and at this point the app language is set correctly but the response is always in English.
public function negotiate()
{
$request = $this->request ?: Yii::$app->getRequest();
$response = $this->response ?: Yii::$app->getResponse();
if (!empty($this->formats)) {
$this->negotiateContentType($request, $response);
}
if (!empty($this->languages)) {
Yii::$app->language = $this->negotiateLanguage($request);
}
debug(Yii::$app->language); // result OK!: it-IT
}
Looks like some build-in errors not translated, for example yii\rest\Action:103
throws throw new NotFoundHttpException("Object not found: $id")
its not translated. You have different ways to solve this problem:
For more information about i18n see documentation.