Child pages
  • Creación de un módulo de PrestaShop

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Esa clase debe tener el mismo nombre que el módulo y su carpeta, en CamelCase: MyModule.
Por otra parte, la clase debe extender la clase Module y por lo tanto hereda todos los métodos y atributos. Esta puede igualmente extender cualquier clase derivada del Module: PaymentModule, ModuleGridEngine, ModuleGraph...

Code Block
borderStylesolid
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()
    {
    if ( parent::install() == false )
      return false;
    return true;
    }
  }
?>

...

En ese caso, cambiaremos el código del módulo, y agregaremos estas líneas:

Code Block
borderStylesolid
titlemymodule.php (partial)
borderStylesolid
public function install()
  {
  if ( parent::install() == false OR !$this->registerHook( 'leftColumn' ) )
    return false;
  return true;
  }

...

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

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

...

Por consiguiente, crearemos el archivo mymodule.tpl y le agregaremos algunas líneas de código.

Code Block
borderStylesolid
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 -->

...

Tip

Debe esforzarse por utilizar nombres explícitos y reconocibles para sus archivos TPL, para que pueda encontrarlos rápidamente en el back-office – los que son una necesidad cuando se utiliza la herramienta de traducción.

Code Block
borderStylesolid
titlemymodule_page.tpl
borderStylesolid
Welcome to my shop!
Code Block
borderStylesolid
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' );
?>

...

Por ejemplo, en nuestro mymodule_page.php, podemos crear una variable:

Code Block
borderStylesolid
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' );
?>

A partir de ahí, podemos pedir a Smarty que muestre el contenido de esta variable en nuestro archivo TPL.

Code Block
borderStylesolid
titlemymodule_page.tpl
borderStylesolid
{$messageSmarty}

PrestaShop incluye una serie de variables. Por ejemplo, {$HOOK_LEFT_COLUMN} será remplazado por el contenido de la columna izquierda, es decir, el contenido de todos los módulos que han sido unidos al hook de la columna izquierda.

...

Las cadenas en los archivos PHP necesitarán ser mostradas a través del método l(), de la clase abstracta Module.php.

Code Block
borderStylesolid
titlemymodule.php (partial)
borderStylesolid
...
$this->displayName = $this->l( 'My module' );
$this->description = $this->l( 'Description of my module.' );
...

Las cadenas en los archivos TPL tendrán que ser convertidas en contenido dinámico, que Smarty remplazará por la traducción del idioma elegido. En nuestro módulo de muestra, este archivo:

Code Block
xml
xml
borderStylesolid
titlemymodule.tpl (partial)
borderStylesolid
xml
<li>
  <a href="{$base_dir}modules/mymodule/mymodule_page.php" title="Click this link">Click me!</a>
</li>

...se convierte en:

Code Block
xml
xml
borderStylesolid
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>

...y este otro:

Code Block
xml
xml
titlemymodule_page.tplxml
<h4>Welcome!</h4>
...
Click me!

...se convierte en:

Code Block
xml
xml
borderStylesolid
titlemymodule.tpl
borderStylesolid
xml
<h4>{l s='Welcome!' mod='mymodule'}</h4>
...
{l s='Click me!' mod='mymodule'}

...

Las traducciones se guardan en un archivo nuevo, es.php (o languageCode.php, el cual es generado por PrestaShop y luce así:

Code Block
borderStylesolid
titlemymodule.tpl
borderStylesolid
<?php

global $_MODULE;
$_MODULE = array();
$_MODULE['<{mymodule}prestashop>mymodule_2ddddc2a736e4128ce1cdfd22b041e7f'] = 'Mon module';
$_MODULE['<{mymodule}prestashop>mymodule_d6968577f69f08c93c209bd8b6b3d4d5'] = 'Description de mon module';
$_MODULE['<{mymodule}prestashop>mymodule_c66b10fbf9cb6526d0f7d7a602a09b75'] = 'Cliquez sur ce lien';
$_MODULE['<{mymodule}prestashop>mymodule_f42c5e677c97b2167e7e6b1e0028ec6d'] = 'Cliquez-moi \!';
$_MODULE['<{mymodule}prestashop>mymodule_page_c0d7cffa0105851272f83d5c1fe63a1c'] = 'Bienvenue dans ma boutique \!';

...

  1. Agregar un nuevo cuadro a su base de datos de PrestaShop, llamado ps_test. Ofrézcale dos campos:
    • id_test (INT 11)
    • test (VARCHAR 32)
  2. Crear un archivo en blanco llamado Test.php en la carpeta /classes de PrestaShop.
  3. Agregar las siguientes líneas a este archivo:
Code Block
borderStylesolid
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;
    }
  }
?>
  1. Crear un archivo en blanco llamado AdminTest.php en /admin/tabs de PrestaShop.
  2. Agregar las siguientes líneas a este archivo:
Code Block
borderStylesolid
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> ';
    }
  }
?>

...