Octobercms: how to translate flash messages?

1.6k Views Asked by At

I use translate.rainlab plugin for localization, but not sure how to translate flash messages for ajax form.

function onMailSend() {
    Mail::sendTo('[email protected]', 'contact.form', post());
    Flash::success('Message has been sent');
}
2

There are 2 best solutions below

2
On BEST ANSWER

You can stick with using the Translate plugin's features, no need to use another translation mechanism.

use RainLab\Translate\Models\Message;

function onMailSend() {
    Mail::sendTo('[email protected]', 'contact.form', post());
    Flash::success(Message::trans('Message has been sent'));
}

This assumes that "Message has been sent" is the string in the default locale.

3
On

translate plugin is used for translating content front-end side, but for translating messages within code, its good idea to use locale lang messages.

suppose this is your site : http://octdev.local.com/demo/ajax (default lang is set to en)

then you can create plugin and within lang/en/lang.php file you can define translation messages

en lang file will be there and default content will be look like this

// lang/en/lang.php
<?php return [
    'plugin' => [
        'name' => 'TestPlugin',
        'description' => ''
    ]
];

you can access this messages any where

\Flash::success(\Lang::get('hardiksatasiya.testplugin::lang.plugin.name'));

hardiksatasiya.testplugin => plugin auther name . pluginname

lang.plugin.name => worked like array lang stands for file name (language) then get plugin array then its key name so in our case it will out put TestPlugin

now you can use new url : http://octdev.local.com/de/demo/ajax its in de

so you can create new lang file in your plugin directory lang/de/lang.php and put same above php code with translated messages

// lang/de/lang.php
<?php return [
    'plugin' => [
        'name' => 'TestPlugin In de',
        'description' => ''
    ]
];

and it will work. if you need whole document you can use this reference : https://octobercms.com/docs/plugin/localization

update if you think i only needed to do in one place you can do something like this (but not preferred way)

$locale = \Lang::getLocale();
switch($locale) {
  case 'en':
     \Flash::success('Message has been sent - EN');
     break;
  case 'de':
     \Flash::success('Message has been sent - DE');
     break;
  default:
     \Flash::success('Message has been sent - default');
}