cpliu338
cpliu338

Reputation: 647

Use CakePHP 3 Internationalization in Controller

In a controller, I need to return translated message in an Ajax json response as:

$body['message'] = __("Duplicated");
$this->response->body(json_encode($body));
$this->response->statusCode(202);
$this->response->type('json');
return $this->response; 

But the translation is not looked up. However, in a template, I am able to get this working:

<?= __("Duplicated");?>

I know I can use the Ajax layout and write a template, but in this case the message body is very short, I need to return a Status Code other than 200. How can I do this in a controller in CakePHP 3?

Upvotes: 0

Views: 301

Answers (1)

cpliu338
cpliu338

Reputation: 647

It seems to be a CakePHP bug (Not a bug, see comments below). I have in app.php

'App' => [
...
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
...
]

and in AppController::beforeRender(), According to http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#changing-the-locale-at-runtime I could override with this (but in fact that does not work):

I18n::locale('zh');

When I change config/app.php to

'App' => [
...
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'zh'),
...
]

It works.

Upvotes: 0

Related Questions