10

In my custom component I do a lot of JavaScript validation for each view. The validation throws various error messages and those messages are configured inside the language file en-GB.com_mycomp.ini and I write the JavaScript inclusion as below inside a PHP file.

in the view.html.php

require_once JPATH_COMPONENT.'/views/send/tmpl/validation.php';

validation.php

function doValidation(){
  // do some checking
  alert("<?php echo JText::_( 'VALIDATION_ERROR'); ?>");
}

Doing by this way the JavaScript code is rendered along with the PHP file.

What I was thinking is to use the standard $document->addScript(...) function so that the .js files are loaded as part of header. Since I got the inline PHP statements I'm not able to do it like that.

Note: I do not want to hard code the error messages inside the .js file because the component is language independent.

I need some direction regarding the best way of including JavaScript code that has language specific values.

1 Answer 1

17

Joomla has a certain method for this. First, in view.html.php add all strings, what needs to be translated with this:

JText::script('VALIDATION_ERROR');

This will add your string to javascript object, what you can use later.

And in javascript, use:

Joomla.JText._('VALIDATION_ERROR')

Which will give you matching translation in current language. This way you can keep JS and PHP in separate files.

3
  • where to add this, JText::script('VALIDATION_ERROR'); in view.html.php file? Jan 4, 2019 at 5:29
  • @ankitsuthar Yes, view.html.php is fine.
    – Rene Korss
    Jan 4, 2019 at 7:41
  • @ankitsuthar If you meant location in file, then inside of display method.
    – Rene Korss
    Jan 15, 2019 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.