Child pages
  • Creating a PrestaShop module

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of content

Table of Contents
maxLevel3

...

Creating a PrestaShop module

...

The main mymodule.php file must start with the following test:

Code Block

if (!defined('_PS_VERSION_'))
  exit;

...

Code Block
titlemymodule.php
borderStylesolid

<?php
if (!defined('_PS_VERSION_'))
  exit;

class MyModule extends Module
{
  public function __construct()
  {
    $this->name = 'mymodule';
    $this->tab = 'Test';
    $this->version = 1.0;
    $this->author = 'Firstname Lastname';
    $this->need_instance = 0;

    parent::__construct();

    $this->displayName = $this->l('My module');
    $this->description = $this->l('Description of my module.');
  }

  public function install()
  {
    return parent::install();
  }
}
?>

Let's examine each line from our MyModule object...

Code Block

public function __construct()

This section defines the class' constructor.

Code Block

$this->name = 'mymodule';
$this->tab = 'Test';
$this->version = 1.0;
$this->author = 'PrestaShop';

...

  • 'name' attribute. Serves as an internal identifier, so make it unique, without special characters or spaces, and keep it lower-case.
  • 'tab' attribute. The title for the table that shall contain this module in PrestaShop's back-office modules list. You may use an existing name, such as Products, Blocks or Stats, or a custom, as we did here. In this last case, a new table will be created with your title.
  • 'version' attribute. The version number for the module, displayed in the modules list.
  • 'author' attribute. This is displayed in the PrestaShop modules list.
Code Block

$this->need_instance = 0;

The need_instance flag indicates whether to load the module's class when displaying the "Modules" page in the back-office. If set at 0, the module will not be loaded, and therefore will spend less resources to generate the page module. If your modules needs to display a warning message in the "Modules" page, then you must set this attribute to 1.

Code Block

parent::__construct();

Calling the parent's constructor. This must be done after the creation of $this->name and before any use of the $this->l() method.

Code Block

$this->displayName = $this->l('My module');

This assigns a public name for the module, which will be displayed in the back-office's modules list.
The l() method is part of PrestaShop translation's tools, and is further explained below.

Code Block

$this->description = $this->l('Description of my module.');

This assigns a public description for the module, which will be displayed in the back-office's modules list.

Code Block

public function install()
{
  return (parent::install());
}

// this also works, and is more future-proof
public function install()
{
  if (parent::install() == false)
    return false;
  return true;
}

...

Info

If your module does create SQL data, whether in its own MySQL tables or in the XXXX table, then it should also feature an uninstall() method, so as to have a custom uninstallation process. This method could look like so:

Code Block

public function uninstall()
{
  if (!parent::uninstall())
    Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'mymodule`');
  parent::uninstall();
}

...

Code Block
titlemymodule.php (partial)
borderStylesolid

public function install()
{
  if (parent::install() == false OR !$this->registerHook('leftColumn'))
    return false;
  return true;
}

// then...

public function hookLeftColumn( $params )
{
  global $smarty;
  return $this->display(__FILE__, 'mymodule.tpl');
}

public function hookRightColumn($params)
{
  return $this->hookLeftColumn($params);
}

Let's explore these new or changed lines.

Code Block

if (parent::install() == false OR !$this->registerHook('leftColumn'))
  return false;
return true;

...

Therefore, this line now reads this way: if installation or hooking fail, we inform PrestaShop.

Code Block

public function hookLeftColumn($params)
{
  global $smarty;
  return $this->display(__FILE__, 'mymodule.tpl');
}

The hookLeftColumn() method makes it possible for the module to hook into the theme's left column.
$smarty is the global variable for the Smarty template system, which PrestaShop uses, and which you need to access.
The display() method returns the content of the mymodule.tpl template file, if it exists.

Code Block

public function hookRightColumn($params)
{
  return $this->hookLeftColumn($params);
}

...

Code Block
titlemymodule.tpl
borderStylesolid

<!-- Block mymodule -->
<div id="mymodule_block_left" class="block">
  <h4>Welcome!</h4>
  <div class="block_content">
    <ul>
      <li><a href="{$base_dir}modules/mymodule/mymodule_page.php" title="Click this link">Click me!</a></li>
    </ul>
  </div>
</div>
<!-- /Block mymodule -->

...

Code Block
titlemymodule_page.tpl
borderStylesolid

Welcome to my shop!
Code Block
titlemymodule_page.php
borderStylesolid

<?php
global $smarty;
include('../../config/config.inc.php');
include('../../header.php');

$smarty->display(dirname(__FILE__).'/mymodule_page.tpl');

include('../../footer.php');
?>

...

Code Block
titlemymodule_page.php
borderStylesolid

<?php
global $smarty;

include('../../config/config.inc.php');
include('../../header.php');

$mymodule = new MyModule();
$message = $mymodule->l('Welcome to my shop!');
$smarty->assign('messageSmarty', $message); // creation of our variable
$smarty->display(dirname(__FILE__).'/mymodule_page.tpl');

include( '../../footer.php' );
?>

...

Code Block
titlemymodule_page.tpl
borderStylesolid

{$messageSmarty}

PrestaShop includes a number of Smarty variables. For instance, {$hook_left_column} will be replaced with the content for the left column, meaning the content from all the modules that have been attached to the left column's hook.

...

There are many other contextual hooks. If you need to display all of the current page's Smarty variables, add the following call:

Code Block

{debug}

Comments are based on asterisk:

Code Block

{* This string is commented out *}

{*
This string is too!
*}

...

Code Block
titlemymodule.php (partial)
borderStylesolid

...
$this->displayName = $this->l('My module');
$this->description = $this->l('Description of my module.');
...

...

Code Block
xml
titlemymodule.tpl (partial)
borderStylesolid
xml

<li>
  <a href="{$base_dir}modules/mymodule/mymodule_page.php" title="Click this link">Click me!</a>
</li>

...

Code Block
xml
titlemymodule.tpl (partial)
borderStylesolid
xml

<li>
  <a href="{$base_dir}modules/mymodule/mymodule_page.php" title="{l s='Click this link' mod='mymodule'}">{l s='Click me!' mod='mymodule'}</a>
</li>

...

Code Block
xml
titlemymodule_page.tpl
xml

<h4>Welcome!</h4>
...
Click me!

...

Code Block
xml
titlemymodule.tpl
borderStylesolid
xml

<h4>{l s='Welcome!' mod='mymodule'}</h4>
...
{l s='Click me!' mod='mymodule'}

...

Code Block
titlefr.php
borderStylesolid

<?php

global $_MODULE;
$_MODULE = array();
$_MODULE['<{mymodule}prestashop>mymodule_b268021027834ab9a4fe675f0c0a93ef'] = 'Mon module';
$_MODULE['<{mymodule}prestashop>mymodule_8dc6964360034754105d1328b04d7727'] = 'Description de mon module';
$_MODULE['<{mymodule}prestashop>mymodule_19d8055bcd0e60a5f99c807e50094c4e'] = 'Cliquez sur ce lien';
$_MODULE['<{mymodule}prestashop>mymodule_526fdd5deb77218de6497b4f3f5b5c65'] = 'Cliquez-moi \!';
$_MODULE['<{mymodule}prestashop>mymodule_page_9cfb297375a799e0f130804c089bd034'] = 'Bienvenue dans ma boutique \!';

...

Code Block
titleTest.php
borderStylesolid

<?php
class Test extends ObjectModel 
{
  /** @var string Name */
  public $test;

  protected $fieldsRequired = array('test');
  protected $fieldsSize = array('test' => 64);
  protected $fieldsValidate = array('test' => 'isGenericName');
  protected $table = 'test';
  protected $identifier = 'id_test';

  public function getFields() 
  {
    parent::validateFields();
    $fields['test'] = pSQL($this->test);
    return $fields;
  }
}
?>

...

Code Block
titleAdminTest.php
borderStylesolid

<?php
include_once(PS_ADMIN_DIR.'/../classes/AdminTab.php');

class AdminTest extends AdminTab
{
  public function __construct()
  {
    $this->table = 'test';
    $this->className = 'Test';
    $this->lang = false;
    $this->edit = true;
    $this->delete = true;
    $this->fieldsDisplay = array(
      'id_test' => array(
        'title' => $this->l('ID'),
        'align' => 'center',
        'width' => 25),
      'test' => array(
        'title' => $this->l('Name'),
        'width' => 200)
    );

    $this->identifier = 'id_test';

    parent::__construct();
  }

  public function displayForm()
  {
    global $currentIndex;

    $defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT'));
    $languages = Language::getLanguages();
    $obj = $this->loadObject(true);

    echo '
      <script type="text/javascript">
        id_language = Number('.$defaultLanguage.');
      </script>';

    echo '
      <form action="' . $currentIndex . '&submitAdd' . $this->table . '=1&token=' . $this->token . '" method="post" class="width3">
        '.( $obj->id ? '<input type="hidden" name="id_'.$this->table.'" value="'.$obj->id.'" />' : '' ).'
        <fieldset><legend><img src="../img/admin/profiles.png" />'.$this->l('Profiles').'</legend>
          <label>'.$this->l('Name:').'</label>
          <div class="margin-form">';

    foreach ($languages as $language)
      echo '
          <div id="name_'.$language['id_lang'|'id_lang'].'" style="display: '.($language['id_lang'|'id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
            <input size="33" type="text" name="name_'.$language['id_lang'|'id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'name', intval($language['id_lang'|'id_lang'])), ENT_COMPAT, 'UTF-8').'" /><sup>*</sup>
          </div>';

    $this->displayFlags($languages, $defaultLanguage, 'name', 'name' );
    echo '
          <div class="clear"></div>
        </div>
        <div class="margin-form">
          <input type="submit" value="'.$this->l('Save').'" name="submitAdd'.$this->table.'" class="button" />
        </div>
        <div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
      </fieldset>
    </form> ';
  }
}
?>

...