addJS function not working for admin in prestashop

2019-02-18 21:53发布

问题:

I am trying to add javascript file in prestashop admin using backOfficeHeader hook using a module but nothing happened. My code is given below.

public function install()
{
    if (!parent::install()
        || !$this->registerHook('backOfficeHeader'))
        return false;

    return parent::install() && 
     $this->registerHook('backOfficeHeader');
}

 public function hookBackOfficeHeader() {
   $this->context->controller->addJS(_MODULE_DIR_.$this->module->name.'js/hs_custom.js');
 }

回答1:

If you are using PS 1.5 or 1.6 you should use hook "actionAdminControllerSetMedia".

Your module installer should check which prestashop version is used and then register the needed hook.

 if (version_compare(substr(_PS_VERSION_, 0, 3), '1.5', '<'))
      $this->registerHook('BackOfficeHeader');
 else
      $this->registerHook('actionAdminControllerSetMedia');

Then you need to addJS on each hook in its version format: PS>=1.5

 public function hookActionAdminControllerSetMedia($params) { 
     $this->context->controller->addJS($this->_path.'views/js/hs_custom.js');
 }

PS<=1.4

public function hookBackOfficeHeader($params) { 
    Tools::addJS($this->_path.'views/js/hs_custom.js');
}


回答2:

did u try to check addJS path? I think nothing more can be possible if other JS files working. Try to use $this->_path.

$this->context->controller->addJS($this->_path.'views/js/hs_custom.js');

1) Output path and check if it is valid. 2) Reload page and check network. Page load your script or not? 3) Remember to reset module if u change something with hooks. 4) Check module hooks.



回答3:

You did several mistakes. This is the invalid access to the property: $this->module->name. Must be $this->name. I.e., the correct code to generate the JavaScript path is:

_MODULE_DIR_ . $this->name . '/js/hs_custom.js'

Or as advised:

$this->_path . 'js/hs_custom.js'

You are also did the double installation of the module and of the hook. You can use the hook BackOfficeHeader, but the hook ActionAdminControllerSetMedia is preferred.

Here is the detailed information, how to register JavaScript in a back-office (in admin pages).



回答4:

For me "this->_path" dosn't work. My solution is to use $_SERVER['DOCUMENT_ROOT']

public function hookActionAdminControllerSetMedia($params)
{
    // add necessary javascript to products back office
    if($this->context->controller->controller_name == 'AdminProducts' && Tools::getValue('id_product'))
    {
        $this->context->controller->addJS($_SERVER['DOCUMENT_ROOT']."/modules/apl/views/js/jquery.ui.touch-punch.min.js");
    }
}


标签: prestashop