Search code examples
javascriptcssprestashop-1.7backoffice

Can't add js and css files to back office


I want to add JS and CSS files to back office in my module. But I get error: Attempted to call an undefined method named "registerStylesheet" of class "AdminModulesController".

I've seen other posts (like this Show my module JS at footer in prestashop) or here https://devdocs.prestashop.com/1.7/themes/getting-started/asset-management/

So I want to avoid addJS() function as this is depreciated. But when I try to use $this->context->controller->registerStylesheet() and $this->context->controller->registerJavascript() I get the above error.

This is my whole hook code:

public function hookActionAdminControllerSetMedia($params)
{ 
    $this->context->controller->registerStylesheet(
        'mb_pages_content',
        'modules/'.$this->name.'/styles/admin.min.css'
    ); 

    $this->context->controller->registerJavascript(
        'mb_pages_content',
        'modules/'.$this->name.'/js/admin.js'
    );
}

I've checked what kind of thing is my: $this->context->controller but it doesn't indeed have registerStylesheet() and registerJavascript() methods. What am I missing? i do everything exactly as described everywhere in the internet, why do I get the error?


Solution

  • The explanation of which methods to use:

    These are FrontController methods in PrestaShop 1.7: registerJavascript and registerStylesheet.

    These are legacy (deprecated) FrontController methods in PrestaShop 1.7: addJS and addCSS.

    These are AdminController methods in PrestaShop 1.7, 1.6, 1.5: addJS and addCSS.

    So, the correct example to add a JS and a CSS files for a back-office (i.e. for AdminController) via a module class is:

    public function hookActionAdminControllerSetMedia($params)
    { 
        // Adds your's CSS file from a module's directory
        $this->context->controller->addCSS($this->_path . 'views/css/example.css'); 
    
        // Adds your's JavaScript file from a module's directory
        $this->context->controller->addJS($this->_path . 'views/js/example.js');
    }
    

    For an additional information see my yet another answer how to register JavaScript in a back-office (in admin pages). I have updated it after this question.