I created a new page in my module by creating a new front controller. I want to add js and css files to this page but I am unable to do so. I have tried a couple of things, but none are working for me.
I tried adding the setMedia() function in the front controller:
public function setMedia()
{
parent::setMedia();
$this->registerJavascript(
'module-easypaymentoption-front',
'modules/' . $this->module->name . '/views/js/front.js',
[
'priority' => 200,
'attribute' => 'async',
]
);
}
I have also tried to load it by using the actionFrontControllerSetMedia hook in the main module php file:
public function hookActionFrontControllerSetMedia()
{
Media ::addJsDef([
'easypaymentoption' => $this->context->link->getModuleLink($this->name, 'validation', [], true),
]);
$this->context->controller->registerJavascript('modules-easypaymentoption',
'modules/' . $this->name . '/views/js/front.js');
$this->context->controller->registerStylesheet(
'module-easypaymentoption-style',
'modules/' . $this->name . '/views/css/front.css'
);
}
I also tried to add by using the hookHeader in the main module php file:
public function hookHeader()
{
$this->context->controller->addCSS($this->_path . '/views/css/front.css');
}
None of these I tried are working, can anyone help me out please?
Any help is very much appreciated.
You can use the hooks in the module main files, and not in the frontControllers.
Try this in your controllers/front/yourcontrollername.php file:
public function setMedia()
{
parent::setMedia();
$this->context->controller->registerJavascript(
'mymodulename',
'modules/'.$this->module->name.'/views/js/mymodulejs.js',
array(
'position' => 'bottom',
'priority' => 150
)
);
}
And don't forget to clear the cache, or try to reset your module if it's not working, because this is the official way to add JS and CSS to PrestaShop frontControllers.
I have replied to this on the PrestaShop forum where it was also posted, forum post
Try adding them in the hookDisplayHeader Or, if your version is > 1.7.6.0 you can try:
$this->context->controller->registerStylesheet(sha1($css_path), $cssUrl, ['media' => 'all', 'priority' => xx]);
$this->context->controller->registerJavascript(sha1($js_path), $jsUrl, ['position' => 'bottom', 'priority' => xx]);
where css_path, js_path and xx are your variables. Also in hookDisplayHeader.