The user performs some actions on the site and receives messages about the successful or unsuccessful result, as well as just informational messages. In php code, we are used to using the enqueueMessage()
method for this.
<?php
use Joomla\CMS\Factory;
$html = 'Message';
Factory::getApplication()->enqueueMessage($html, 'warning');
Most often, language constants are used as messages so that users can receive messages in their own language:
<?php
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
Factory::getApplication()->enqueueMessage(Text::_('SOME_LANG_CONSTANT'), 'info');
Rendering of Joomla messages in the frontend
Here we will need the connected core files core.js
and messages.js
. A little excerpt from the code:
/**
* Render messages send via JSON
* Used by some javascripts such as validate.js
*
* @param {object} messages JavaScript object containing the messages to render.
* Example:
* const messages = {
* "message": ["This will be a green message", "So will this"],
* "error": ["This will be a red message", "So will this"],
* "info": ["This will be a blue message", "So will this"],
* "notice": ["This will be same as info message", "So will this"],
* "warning": ["This will be a orange message", "So will this"],
* "my_custom_type": ["This will be same as info message", "So will this"]
* };
* @param {string} selector The selector of the container where the message will be rendered
* @param {bool} keepOld If we shall discard old messages
* @param {int} timeout The milliseconds before the message self destruct
* @return void
*/
This is what it looks like in practice:
Joomla.renderMessages({
message: [Joomla.Text._('COM_SWJPROJECTS_USER_KEYS_KEY_SUCCESSFULLY_COPYED')]
});
Now we see that we can use language constants as a message in Javascript. And that's cool! To do this, we use the Joomla.Text._()
method (similar to Text::_()
in PHP). But Javascript has to get the values of these language constants from somewhere. And to do this, in the php code of our page, we need to take care of it and add the language constants necessary for js using the Text::script()
method.
<?php
use Joomla\CMS\Language\Text;
Text::script('SOME_LANG_CONSTANT_SUCCESS');
Text::script('SOME_LANG_CONSTANT_FAIL');
This way I can access the values of the language constants SOME_LANG_CONSTANT_SUCCESS
and SOME_LANG_CONSTANT_FAIL
in javascript.
Top comments (0)