0

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?

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

beforeRender happens after the controller action has run, and before the view is being rendered. So things are working as intended. http://book.cakephp.org/3.0/en/controllers.html#Cake\Controller\Controller::beforeRender

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.