In most cases to add any asset (JavaScript or CSS) to a back-office (admin pages) you should use the hook actionAdminControllerSetMedia()
.
Full steps to register correctly a JavaScript file are:
Step 1. Register the hook on a module install:
public function install()
{
if (!parent::install()) {
return false;
}
// After a module installation, register the hook
if (!$this->registerHook('actionAdminControllerSetMedia')) {
return false;
}
return true;
}
Step 2. Then, add your JavaScript asset:
public function hookActionAdminControllerSetMedia()
{
// Adds jQuery and some it's dependencies for PrestaShop
$this->context->controller->addJquery();
// Adds your's JavaScript from a module's directory
$this->context->controller->addJS($this->_path . 'views/js/example.js');
}
There are different ways and several methods that can be used to register assets in a back-office (admin pages) (they are listed in the order of the execution):
- The hook
hookDisplayBackOfficeHeader()
- The controller's method
AdminControllerCore::setMedia()
- The hook
actionAdminControllerSetMedia()
- A module's method
Module::getContent()
- The hook
hookDisplayBackOfficeFooter()
To add an inline code, the best way is use the hook hookDisplayBackOfficeFooter()
. For example:
public function hookDisplayBackOfficeFooter()
{
return '
<script type="text/javascript">
var EXAMPLE_VARIABLE = "Hello, Zapalm!";
</script>
';
}
Yet another example for a case when you need to add a JavaScript asset but in a child class of AdminController of your module (for PrestaShop 1.7):
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addCSS(_MODULE_DIR_ . $this->module->name . '/views/css/example.css');
$this->addJS(_MODULE_DIR_ . $this->module->name . '/views/js/example.js');
}
For PrestaShop 1.6 and 1.5 you can do also like in this example but you need to remove $isNewTheme
parameter from the method definition and the parent method call.
References:
Asset management in PrestaShop 1.7.
How to add an external asset to a front-office page in PrestaShop 1.7.
The explanation of which methods to use: addJS or registerJavascript.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…