Show my module JS at footer in prestashop

ぐ巨炮叔叔 提交于 2019-11-28 01:44:17

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):

  1. The hook hookDisplayBackOfficeHeader()
  2. The controller's method AdminControllerCore::setMedia()
  3. The hook actionAdminControllerSetMedia()
  4. A module's method Module::getContent()
  5. 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>
    ';
}

Note: In PrestaShop 1.7 if someone want to add JavaScript from an external resource, for example, from the https://ajax.googleapis.com, the new method $this->context->controller->registerJavascript() with the option 'server' => 'remote' should be used. For example:

$this->context->controller->registerJavascript(
    'three.js',
    'https://ajax.googleapis.com/ajax/libs/threejs/r84/three.min.js',
    ['position' => 'bottom', 'priority' => 100, 'server' => 'remote']
);

Asset management in PrestaShop 1.7.

If you go to "Modules" > "Hook positions" in BO, you can order the load of the modules.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!