Affichage des articles dont le libellé est prestashop. Afficher tous les articles
Affichage des articles dont le libellé est prestashop. Afficher tous les articles

lundi 16 janvier 2017

Ajax en front et back office de Prestashop

Aujourd'hui je vais vous montrer comment créer un script client (jquery) ,avec l'utilisation de la méthode ajax, et une partie back (PHP) dans des contrôleurs front office et back office.
Je vais traiter seulement, la démarche spécifique à la création d'un module Prestashop,
Vous pourriez suivre la même démarche pour les contrôleurs natives admin et front de Prestashop

Ajax dans le Back office de Prestashop

Si vous avez un contrôleur admin créé, vous allez passer l'étape suivante sinon vous aurez à créer un contrôleur admin

Créer un appel ajax dans un fichier admin js

  1. Inclure le fichier js, il faut déjà le créer dans nommodule/views/admin/js/script.js, et pour appeler ce fichier dans la page admin de Prestashop ou onglet (tab en anglais),  il faut utiliser la méthode hookDisplayBackOfficeHeader dans le fichier nommodule.php
    exemple :
       public function hookDisplayBackOfficeHeader(){
        if (Tools::getValue('configure') != $this->name)
return;
        $this->context->controller->addJquery(); // si aurait besoin de Jquery
        $this->context->controller->addJS($this->_path.'views/admin/js/script.js');
       }
et enregistrer le hook correspondant dans méthode install du module dans le fichier nommodule.php
$this->registerHook('displayBackOfficeHeader')

Dans le fichier script.js, mettre :

          var id_product = $('input[name="id_product"]').val();
                  $.ajax({
                     type: "POST",
                     url: currentIndex + "&token=" + token,
                         dataType: 'json',
                           data: {
                                     controller: 'AdminNomModuleNomController',
                                       action: 'GetProductInformations',
                                         ajax: true,
                                          id_product: id_product,
                                       },
                                       success: function(result) {
                                                 if (result.status == 'ok'){
                                                     $('#id_product').html(result.productInformations.id_product); 
                                                                               $('#link').html(result.productInformations.link); 
                                                                       }
                                                                          else
                                                                                alert('error');
                                                                }
                                                });


                            Créer un contrôlleur admin

                            Dans le dossier /nom_module/controllers/admin vous aurez à créer un fichier de nom 
                            AdminNomModuleNomControllerController.php
                            Où NomModule est le nom du module et NomController est le nom du contrôleur admin

                            Et mettre

                            class AdminNomModuleNomControllerController extends ModuleAdminController{
                                public function __construct(){
                                parent::__construct();
                                $this->context = Context::getContext();
                                }

                            public function ajaxProcessGetProductInformations() {
                            
                                    if ((int) Tools::getValue("id_product") > 0) {
                            
                                        $id_product = (int) Tools::getValue("id_product");
                            
                                        $product = new Product((int) Tools::getValue("id_product"), false, $this->context->language->id, $this->context->shop->id);
                            
                                        $row = array();
                            
                                        $row['id_product'] = $id_product;
                            
                                        $product_informations = Product::getProductProperties($this->context->language->id, $row);
                            
                                        if ($product_informations)
                            
                                            $json = array(
                                                        'productInformations' => $product_informations);
                                                        'status' =>'ok'
                                                   );
                            
                            
                                        else
                                            $json = array(
                            
                                                        'status' => 'error',
                            
                                                        'message' => $this->l('Erreur de sauvegarde.')
                            
                                         );
                            
                                         die(Tools::jsonEncode($json));
                            
                            
                                          break;
                            
                                   }

                            }
                            PS: il ne faut oublier de créer le lien de menu correspondant dans le fichier nommodule.php

                            par exemple utiliser ce code:

                            $tab = new Tab();
                            $languages = Language::getLanguages(false);
                            foreach ($languages as $language)
                            $tab->name[$language['id_lang']] = 'Le nom de mon onglet';
                            $tab->class_name = 'AdminMonModuleNomControleur'; //controller a creer correspondant au contenu de l'onglet
                            $tab->module = 'monmodule'; //nom du module
                            $tab->id_parent = Tab::getIdFromClassName('AdminOrders'); //mettre l'id de l'onglet parent de votre onglet
                            
                            
                            if (!$tab->add())
                            return false;
                            


                            Ajax dans le Front office de Prestashop

                            Si vous avez créer un contrôlleur front, alors vous pouvez omettre l'étape suivante

                            Créer un contrôlleur front

                            Dans le dossier /nom_module/controllers/front vous aurez à créer un fichier de nom 
                            default.php


                            class ModuleNameDefaultModuleFrontController extends ModuleFrontController
                            {     public function initContent(){
                                parent::initContent(); 
                                     if (Tools::getValue('ajax')){
                                         $id_product = (int) Tools::getValue("id_product"); 
                            $product_informations = Product::getProductProperties($this->context->language->id, $row);
                              
                            
                                         if ($product_informations)
                                             $json = array('productInformations' => $product_informations);
                            
                                         else
                                             $json = array(
                            
                                                        'status' => 'error',
                            
                                                        'message' => $this->l('Erreur de sauvegarde.')
                            
                                         );
                            
                                         die(Tools::jsonEncode($json));
                            }
                            }
                            Default est le nom du contrôleur.

                            Créer un appel ajax dans un le fichier tpl

                            Dans votre fichier tpl qui doit appeler l'ajax mettre
                            var id_product = $('input[name="id_product"]').val();
                            $.ajax({
                            type: "POST",
                            url: '{$link->$this->context->getModuleLink('nommodule', 'default')}',
                            async: false,
                            cache: false,
                            data: "product_id="+id_product+"&ajax=1",
                            success: function(html){
                                                $("#pricet").html(html.price);
                                                $('#link').html(result.productInformations.link);
                                            },
                            error: function() {alert("ERROR:");}

                            });

                            Comme ça je vous ai montré aujourd'hui comment développer avec ajax en Prestashop, pour les pages admin et les pages front.
                            N'hésitez pas à mettre vos questions en commentaires.
                            Si vous avez n'importe quel travail sur Prestashop, n'hésitez pas à envoyer un mail à tarek.fellah@gmail.com pour un devis gratuit dans les 24h.



                            vendredi 10 juillet 2015

                            Install and Uninstall module prestashop gets errors

                            Install and Uninstall prestashop module errors


                            Install module prestashop errors


                            You created a module and you get an error message when installing it, try to call your hooks register after the parent::install method
                             
                            if (!parent::install())
                            return false;
                            Try to put this code at the beginning of the install function, if it doesn't solve your problem, try to debug your hook functions  and see if thay returns false, in this case, you shouldd correct the errors in those functions, To debug, you can use var_dump function

                            For example:

                            var_dump($this->registerHook('leftColumn'));exit;
                             

                            Uninstall prestashop module problems

                            You have created a prestashop module and when your tried to uninstall it for testing purpose or others, you got prestashop errors: something related to remove override files error, this should be because prestashop failed to remove module override files, this can be the case when you manually removed this files.
                            So after that don't forget to remove cache/class_index.php file, which contains the prestashop classe locations, so after removing it, prestashop recreate it with the new classe paths.

                            If you get

                            The following module(s) could not be uninstalled properly:

                            Try to remove your override module folder, uninstall you module and restore your override folder and try to reinstall your module.
                            After try to remove cache/class_index.php and try to uninstall the module another once.

                            Hope this helping prestashop users to surpass this embarrassing problem


                            dimanche 14 juin 2015

                            Change order total amount in prestashop after payment method choosing

                            If you like to change the order total amount, to add an extra fee or something else after choosing a payment method by the client. You can do it by overriding the validateOrder method, in classes/PaymentModule.php, and change it like this, for prestashop 1.6.0.13, change the instruction in line 13 by
                            
                            if($payment_method == 'Bank wire')     
                            $order->total_paid_tax_incl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier)*1.25, 2);
                            

                            In this example, i added a 25% extra fee to order total amount when the payment method is bankwire. Hope this helps.