Create new hook in PrestaShop Tutorial
28
May
2013

How to create a new hook in PrestaShop

The first step of creating a new hook in PrestaShop is choosing a unique name for it. You can check the existing hooks in your database and running an SQL query you can verify if the new hook’s name is used already or not:

 

SELECT * FROM [YOUR_DB_PREFIX]hook WHERE name=’[NEW_HOOK_NAME]’

 

If the query returns an empty result, you can use the hook name and insert it in the database:

  • id_hook: is generated automatically, you do not need to set it
  • name: is the hook name
  • title: title of the hook
  • description: you can leave it blank
  • position: set to 1 if you want to have the hook listed in the Module Positions, otherwise 0
  • live_edit: set to 1 if you want to enable live edit, otherwise 0

 

In this tutorial we will call the new hook: myHook.

After the hook is added to the database, you need to creates the hook’s executing function in the module file:

 

public function hookMyHook($params)
{
//CODE TO EXECUTE
}

 

The next step is to transplant the module to the new hook in Back Office -> Modules -> Positions -> Transplant a module. By this you will make sure the hookMyHook function is executed for the new hook.

The new hook can be added to various places: CMS page, product list etc. To make things simple we will use the hook in CMS pages.

Create a new file named CMSController.php, this file will contain the class that overrides the CmsControllerCore class. To preserve the main functionalities and avoid any future conflicts in case of an upgrade, the CmsController class will extend the CmsControllerCore class:

 

class CmsController extends CmsControllerCore
{
//CLASS FUNCTIONS(METHODS), CLASS PROPERTIES
}

 

If we want our module to be called in the body part of the CMS pages, we will create a function called process :

 

public function process()
{
parent::process();
self::$smarty->assign(‘HOOK_MY_HOOK’, Module::hookExec(myHook, $params));
}

 

$params variable is an associative array and it’s use is optional.

This function will first execute the parent class’ (CmsControllerCore) process function, so we have preserved it’s functionality. After the parent’s process function is executed, the modules hooked to myHook will be executed too and their return values assigned to Smarty. We do not have to worry about the other function of the CmsControllerCore class as they are inherited by CmsController class.

The new CmsController.php has to be uploaded to: override/controllers/

The last step is to display the hook: edit themes/[YOUR_THEME]/cms.tpl and add {$HOOK_MY_HOOK} to the desired location.

  • 1465 View
  • Pin It