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
  • Developer tips and tricks
  • How to check whether a user is logged to PrestaShop or not
  • How to find the speed bottleneck on a site
  • How to retrieve the carrier's id
  • How to retrieve the cart's id
  • How to import products from a XML file

Was this helpful?

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

Developer tips and tricks

PreviousSpecifics of multistore module developmentNextPrestaShop's developer tools

Last updated 4 years ago

Was this helpful?

Table of contents

/*<![CDATA[*/ div.rbtoc1597308498964 {padding: 0px;} div.rbtoc1597308498964 ul {list-style: disc;margin-left: 0px;} div.rbtoc1597308498964 li {margin-left: 0px;padding-left: 0px;} /*]]>*/

Developer tips and tricks

How to check whether a user is logged to PrestaShop or not

You can easily perform this check by using the isLoggedBack() method provided in the Employee class (/classes/Employee.php).

This example assumes your file is located in the administration folder:

<?php

define('_PS_ADMIN_DIR_', getcwd());
include(_PS_ADMIN_DIR_.'/../config/config.inc.php');

if (Context::getContext()->employee->isLoggedBack())
{
   /* Your code here, user is logged */
}

?>

The isLoggedBack() method was located in the Cookie class in PrestaShop 1.4.x, and was moved to Employee class in v1.5.x.

How to find the speed bottleneck on a site

Try to enable the profiling feature, it will highlight which part of the code is slowing down your server.

  1. Put your store in maintenance mode.

  2. In your PrestaShop v1.5.x store, edit the /config/defines.inc.php file.

  3. On line 44, replace define('_PS_DEBUG_PROFILING_', false); by define('_PS_DEBUG_PROFILING_', true);

  4. Go to your store homepage and reload the page.

You should now be able to see how much time is consuming each function and SQL query.

How to retrieve the carrier's id

In PrestaShop 1.4, you could use {id_carrier}:

{if $id_carrier == "1"}
  {* Do some stuff here *}
{/if} 

The same result can be achieved in PrestaShop 1.5 with {$cart->id_carrier}:

{if isset($cart->id_carrier) && $cart->id_carrier == 1}
   {* Do some stuff here *}
{/if}

How to retrieve the cart's id

You have several ways to retrieve the Cart ID from the current visitor, the easiest one is to use the Context.

Step 1

Open the /modules/blockcart/ajax-cart.js file and look for this line:

$(document).ready(function(){

Below this line, add this:

$.ajax({
    type: 'GET',
    url: baseDir + 'modules/blockcart/ajax.php' + '?retrieve_cart_id=1',
    success: function(result_cart_id)
    {
        alert(result_cart_id);
        /* my_id_cart = parseInt(result_cart_id); Uncomment this line to store the value into a JS variable */
    }
});

Step 2

Create a file named ajax.php in /modules/blockcart/ with the following code inside:

<?php

include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../init.php');

$context = Context::getContext();
if (Tools::getValue('retrieve_cart_id') == 1)
    echo isset($context->cookie->id_cart) ? (int)$context->cookie->id_cart : 0;

You might want to consider the fact that by retrieving this value in JavaScript, it will be publicly available to the visitor. Depending on how secure your code and payment modules are, this could be an issue.

How to import products from a XML file

With PrestaShop you can easily import your data using one of these options:

  1. By using the "CSV Import" feature in your Back-office

  2. By using the PrestaShop Web-service (custom development required)

  3. By using the existing classes (custom development required)

Please note that:

  • This code MUST be adapted to your own XML needs!

  • This code will is not designed to work with combinations (color, sizes, etc.)

  • This code does not create categories for you, and is adding all the products to the "Home" category

<?php

include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');

$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Document>
  <Products>
    <Reference>1101TEST</Reference>
    <Valid_internet_product>1</Valid_internet_product>
    <Products_name>Test product</Products_name>
    <Price>49.99</Price>
    <Active_product>1</Active_product>
    <SupplierNo>8</SupplierNo>
    <Weight>5</Weight>
    <Description>My long product description</Description>
    <Short_Description>Product desc.</Short_Description>
    <MinOrderQty>1</MinOrderQty>
    <Categories>
      <Category>
        <CategoryID>3</CategoryID>
          <CategoryName>Home\Prod</CategoryName>
          <Active_category>1</Active_category>
          <Changed>0</Changed>
      </Category>
    </Categories>
    <Tax_Class_ID>1</Tax_Class_ID>
    <Discount>
      <Discount_percentage>percentage</Discount_percentage>
      <discountprice_ex_vat>0</discountprice_ex_vat>
      <Discountprice_include_vat>0</Discountprice_include_vat>
      <Pct_ReductionPercent>0</Pct_ReductionPercent>
    </Discount>
  </Products>
</Document>
XML;

$xml = simplexml_load_string($xml_string);
foreach ($xml->Products as $product_xml)
{
    if ($product_xml->Valid_internet_product == 1)
    {
        /* Update an existing product or Create a new one */
        $id_product = (int)Db::getInstance()->getValue('SELECT id_product FROM '._DB_PREFIX_.'product WHERE reference = \''.pSQL($product_xml->Reference).'\'');
        $product = $id_product ? new Product((int)$id_product, true) : new Product();
        $product->reference = $product_xml->Reference;
        $product->price = (float)$product_xml->Price;
        $product->active = (int)$product_xml->Active_product;
        $product->weight = (float)$product_xml->Weight;
        $product->minimal_quantity = (int)$product_xml->MinOrderQty;
        $product->id_category_default = 2;
        $product->name[1] = utf8_encode($product_xml->Products_name);
        $product->description[1] = utf8_encode($product_xml->Description);
        $product->description_short[1] = utf8_encode($product_xml->Short_Description);
        $product->link_rewrite[1] = Tools::link_rewrite($product_xml->Products_name);
        if (!isset($product->date_add) || empty($product->date_add))
            $product->date_add = date('Y-m-d H:i:s');
        $product->date_upd = date('Y-m-d H:i:s');
        $id_product ? $product->updateCategories(array(2)) : $product->addToCategories(array(2));
        $product->save();

        echo 'Product <b>'.$product->name[1].'</b> '.($id_product ? 'updated' : 'created').'<br />';
    }
}

Below is a quick code snippet that is working with a specific XML document (stored as a ). It will create or update all the products, and take into account their price, availability, name, description, weight, etc.

heredoc string
Developer tips and tricks
How to check whether a user is logged to PrestaShop or not
How to find the speed bottleneck on a site
How to retrieve the carrier's id
How to retrieve the cart's id
How to import products from a XML file