LogoLogo
Homepage
  • Documentations for PrestaShop 1.5
  • English documentation 1.5
    • About PrestaShop 1.5
    • New features in PrestaShop 1.5
    • Getting Started
      • What you need to get started
      • Installing PrestaShop
      • Installing PrestaShop using the command line
      • Updating & Uninstalling
      • Misc. information
    • Updating PrestaShop
      • Automatic update
      • Manual update
      • Making and restoring your own backup
      • In case of issues
    • User Guide
      • Training
      • Customizing your shop
      • Browsing the front-office
      • Connecting to the PrestaShop back-office
      • First steps with PrestaShop 1.5
      • Adding Products and Product Categories
      • A Look Inside the Catalog
      • Managing Orders
      • Managing Customers
      • Creating Price Rules and Vouchers
      • Managing Shipping
      • Understanding Local Settings
      • Managing Modules and Themes
      • Making the Native Modules Work
      • Understanding the Preferences
      • Understanding the Advanced Parameters
      • Administering the Back-Office
      • Understanding Statistics
      • Advanced Stock Management
      • Managing Multiple Shops
    • Developer Guide
      • Developer tutorials
        • Using the PrestaShop Web Service
          • Webservice one-page documentation
          • Chapter 1 - Creating Access to Back Office
          • Chapter 2 - Discovery - Testing access to the web service with the browser
          • Chapter 3 - First steps - Access the Web service and list client
          • Chapter 4 - Retrieve Data - Retrieving a Client
          • Chapter 5 - Modification - Update client
          • Chapter 6 - Creation - Remote Online Form
          • Chapter 7 - Removal - Remove customer accounts from the database
          • Chapter 8 - Advanced Use
          • Chapter 9 - Image management
          • Chapter 10 - Price management
          • Cheat-sheet - Concepts outlined in this tutorial
          • Web service reference
        • Helpers
          • HelperForm
          • HelperOptions
          • HelperList
          • Using helpers to overload a back-office template
        • New Developers Features In PrestaShop 1.5
        • Using the Context Object
        • DB class best practices
        • Public and overloadable methods
        • Overriding default behaviors
        • Using addJquery(), addJqueryPlugin() and addJqueryUI()
        • Handling special characters in links
        • Auto-updating modules
        • Front-Office Controllers
        • Controllers correspondence table
        • Specifics of multistore module development
        • Developer tips and tricks
        • PrestaShop's developer tools
        • Using the backward compatibility toolkit
      • Fundamentals
      • Coding Standards
      • Setting up your local development environment
      • Diving into PrestaShop Core development
      • Creating a PrestaShop module
      • Creating a front-office module
      • Creating a module with both front-end and back-end controllers
      • Hooks in PrestaShop 1.5
      • Translations in PrestaShop 1.5
      • How to use the Forge to contribute to PrestaShop
      • How to write a commit message
      • Contributing code to PrestaShop
    • Designer Guide
      • Theme development fundamentals
      • Integrating content in a page using hooks
      • Characteristics of a front-office theme
      • Characteristics of a back-office theme
      • Creating your own theme
      • Theme templates and Smarty
      • Using jQuery and Ajax
      • Best practices
      • Designer tutorials
        • Changes in version 1.5 which impact theme development
        • Changing a 1.4 theme to support gift products
        • Implementing layered navigation in a theme
    • System Administrator Guide
    • Merchant's Guide
      • Our advices
      • Sample price rules
    • FAQ
      • Using PrestaShop with WordPress
    • Troubleshooting
  • Documentation française 1.5
    • À propos de PrestaShop 1.5
    • Nouveautés de PrestaShop 1.5
    • Guide de démarrage
      • Ce dont vous avez besoin
      • Installer PrestaShop
      • Installer PrestaShop en ligne de commande
      • Mettre PrestaShop à jour
      • Informations diverses
    • Guide de mise à jour
      • Mise à jour automatique
      • Mise à jour manuelle
      • Faire une sauvegarde et la restaurer
      • En cas de problème
    • Guide de l'utilisateur
      • Formations
      • Personnaliser votre boutique
      • Parcourir le front-office
      • Se connecter au back-office de Prestashop
      • Premiers pas avec PrestaShop 1.5
      • Ajouter des produits et des catégories de produits
      • Un aperçu du catalogue
      • Gérer les commandes
      • Gérer les clients
      • Mettre en place des promotions
      • Gérer les transporteurs
      • Comprendre les réglages locaux
      • Gérer les modules et les thèmes
      • Configurer les modules natifs
      • Comprendre les préférences
      • Comprendre les paramètres avancés
      • Administrer le back-office
      • Comprendre les statistiques
      • Gestion avancée des stocks
      • Gérer plusieurs boutiques
    • Guide du développeur
      • Fondamentaux
      • Norme de développement
      • Mettre en place votre environnement de développement
      • Plonger dans le développement PrestaShop
      • Créer un module PrestaShop
      • Les hooks de PrestaShop 1.5
      • Les traductions dans PrestaShop 1.5
      • Comment utiliser la Forge pour contribuer à PrestaShop
      • Comment écrire un descriptif de modification
    • Guide de l'intégrateur
      • Fondamentaux de la création de thème
      • Intégrer du contenu dans une page à l'aide de hooks
      • Caractéristiques d'un thème front-office
      • Caractéristiques d'un thème back-office
      • Template de thème et Smarty
      • Utiliser jQuery et Ajax
      • Bonnes pratiques
    • Guide de l'administrateur système
    • Guide du vendeur
      • Exemples de promotions
      • Nos bons conseils
    • Questions fréquentes
    • Dépannage
  • Documentación española 1.5
    • Acerca de PrestaShop 1.5
    • Introducción
      • Lo que necesita para empezar
    • Guía del usuario
      • Formación
      • Personalización de su tienda
      • Exploración del front-office
      • Conexión al back-office de PrestaShop
      • Primeros pasos con PrestaShop 1.5
      • Añadir productos y categorías de productos
      • Una mirada interna al catálogo
      • Gestionar pedidos
      • Gestionar clientes
      • Crear reglas de precios y cupones
      • Gestionar el transporte
      • Comprender la Configuración Local
      • Gestionar módulos y temas
      • Configurar los Módulos Nativos
      • Comprender las Preferencias
      • Comprender los Parámetros avanzados
      • Administrar el Back-Office
      • Comprender las estadísticas
      • Gestión avanzada de stock
      • Gestionar varias tiendas
    • Guía del Desarrollador
      • Tutoriales para Desarrolladores
        • Uso del Web Service de Prestashop
          • Capítulo 1 - Creación de acceso al Back Office
  • Документация на русском языке 1.5
    • Информация о PrestaShop 1.5
    • Новые функции в PrestaShop 1.5
    • Приступая к работе
      • Что нужно чтобы приступить к работе
      • Установка PrestaShop
      • Установка PrestaShop при помощи командной строки
      • Обновление и удаление PrestaShop
      • Прочая информация
    • Руководство пользователя
      • Обучение
      • Настройка вашего магазина
      • Изучение публичной части сайта
      • Бэк-офис PrestaShop
      • Первые шаги в PrestaShop 1.5
      • Добавление товаров и товарных категорий
      • Внутри каталога
      • Управление заказами
      • Работа с клиентами
      • Создание правил ценообразования корзины и ваучеров
      • Управление доставкой
      • Ориентация в локальных настройках
      • Управление модулями и темами
      • Настойка встроенных модулей
      • Ориентация в настройках
      • Ориентация в расширенных параметрах
      • Администрирование Back-Office
      • Ориентация в статистике
      • Расширенное управление запасами
      • Управление мультимагазином
Powered by GitBook
On this page
  • Usage of configuration variables
  • Handling images and other types of files
  • Creating database tables
  • Object in some stores only
  • Object in all stores
  • Different language in every store

Was this helpful?

  1. English documentation 1.5
  2. Developer Guide
  3. Developer tutorials

Specifics of multistore module development

PreviousControllers correspondence tableNextDeveloper tips and tricks

Last updated 4 years ago

Was this helpful?

Usage of configuration variables

As indicated in the "Configuration object" section of the "" chapter of this developer guide, some of the methods from the Configuration object have three optional parameters, which make it possible to target any other existing store on the current PrestaShop installation: id_shop, id_shop_group and id_lang.

While these parameters can prove useful when having to handle multiple specific and known stores from one of the presented Configuration method, they are not recommended for general usage. Your configuration code should only target the current store using the current Context, which every Configuration method does automatically.

In the few occasions where you need to apply a new value to the same Configuration variable for all existing stores, using the Configuration::updateGlobalValue('myVariable', 'myValue') method. You can then retrieve that value for the current store by using the Configuration::get('myVariable') method.

Handling images and other types of files

Images can be defined on a per-store or a per-store-group basis: an item can have a default image on most stores on the PrestaShop installation, and another image for a specific store.

In order to achieve that, the name of the image must be stored in a configuration variable. The default image is then replaced on the fly with the store-specific image.

Let's explore how the Blockadvertising module does it. Using this module, you can upload an image to be displayed on the front-office of the store, serving as an advertisement to any link you might want. The module was built to make use of the multistore feature: depending on the selected store or store group in the multistore menu, the user can assign the uploaded image to a given store context or store group context.

Here is how it saves a submitted file:Saving the file on a per-store basis

{ 
  // Saving only the main portion of the uploaded file's name, without the file extension.
  Configuration::updateValue(
    'BLOCKADVERT_IMG_EXT', 
    substr($_FILES['adv_img']['name'], strrpos($_FILES['adv_img']['name'], '.') + 1)
    );
					
  // Setting the image's name with a name contextual to the shop context.
  $this->adv_imgname = 'advertising';

  // Creating two versions of the image name, depending on the store context:
  // If the context is the current group, use the image named 'advertising-g'
  // If the context is the current store, use the image named 'advertising-s'
  if (Shop::getContext() == Shop::CONTEXT_GROUP)
    $this->adv_imgname = 'advertising'.'-g'.(int)$this->context->shop->getContextShopGroupID();
  elseif (Shop::getContext() == Shop::CONTEXT_SHOP)
    $this->adv_imgname = 'advertising'.'-s'.(int)$this->context->shop->getContextShopID();

  // Copying the image in the module directory with its new contextual name.
  if (!move_uploaded_file($_FILES['adv_img']['tmp_name'], 
    _PS_MODULE_DIR_.$this->name.'/'.$this->adv_imgname.'.'.Configuration::get('BLOCKADVERT_IMG_EXT')))
    $errors .= $this->l('File upload error.');
}

And here is how it decides which image to display, depending on the context:Loading the file on a per-store basis

protected function initialize()
{
  // Setting the main name of the image.
  $this->adv_imgname = 'advertising';

  // Setting the contextual name of the file, depending on the context.
  if ((Shop::getContext() == Shop::CONTEXT_GROUP  || Shop::getContext() == Shop::CONTEXT_SHOP)
    && file_exists(_PS_MODULE_DIR_.$this->name.'/'.$this->adv_imgname.'-g'
    .$this->context->shop->getContextShopGroupID().'.'.Configuration::get('BLOCKADVERT_IMG_EXT')))
    $this->adv_imgname .= '-g'.$this->context->shop->getContextShopGroupID();
  if (Shop::getContext() == Shop::CONTEXT_SHOP
    && file_exists(_PS_MODULE_DIR_.$this->name.'/'.$this->adv_imgname.'-s'
    .$this->context->shop->getContextShopID().'.'.Configuration::get('BLOCKADVERT_IMG_EXT')))
    $this->adv_imgname .= '-s'.$this->context->shop->getContextShopID();
  $this->adv_img = Tools::getMediaServer($this->name)._MODULE_DIR_.$this->name.'/'
    .$this->adv_imgname.'.'.Configuration::get('BLOCKADVERT_IMG_EXT');
}

Creating database tables

There can be several scenarios:

  • The object/entity exists in some stores, but not in all of them: you should use an associative table, and handle it using id_group_shop.

  • The object/entity exists in all stores: use the regular tables, with a custom field. Handle it using id_entity, id_group_shop and the attributes.

  • The language must be different for every store: handle it using id_shop in the _lang table.

Object in some stores only

The method to use is Shop::addSqlRestriction($share = false, $alias = null).It makes it possible to add restrictions to a SQL query, in order to retrieve information on a shop or a shop group.The parameters are optional:

  • $share: is used to add a "WHERE" clause indicating that we are in the same group as the current store.

  • $alias: is used to set the table alias to which the WHERE clause should be applied.

For instance, this query retrieves visitor connections from a given shop:

'SELECT date_add, COUNT(`date_add`) as total
 FROM `'._DB_PREFIX_.'connections`
 WHERE 1 '.Shop::addSqlRestriction();

Object in all stores

The method to use is Shop::addSqlAssociation($table, $alias, $inner_join = true, $on = null, $force_not_default = false).

It makes it possible to add a JOIN clause to the SQL query, joining a table and its associated table in multistore mode.

For instance, this query automatically associates the _DB_PREFIX_.'product_shop' table to the _DB_PREFIX_.'product' table using the 'p' alias:

'SELECT wp.`id_product`
 FROM `'._DB_PREFIX_.'wishlist_product` wp
 LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = wp.`id_product`
 '.Shop::addSqlAssociation('product', 'p');

This way, the joint between the information from the product and the current store's context is applied.

Different language in every store

The method to use is Shop::addSqlRestrictionOnLang($alias = null, $id_shop = null).

It makes it possible to add a restriction on id_shop for a multishop language table.

For instance, this query automatically associates the _DB_PREFIX_.'product_lang' table to the _DB_PREFIX_.'wishlist_product' table using the 'pl' alias:

'SELECT wp.`id_product`
 FROM `'._DB_PREFIX_.'wishlist_product` wp
 LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = wp.`id_product`
 '.Shop::addSqlAssociation('product', 'p').'
 LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON pl.`id_product` = wp.`id_product`'.Shop::addSqlRestrictionOnLang('pl').'
 WHERE pl.`id_lang` = '.(int)($id_lang);

This way, the joint between the language information of the product and the current store language is applied.

Creating a PrestaShop module