Reader small image

You're reading from  PrestaShop Module Development

Product typeBook
Published inNov 2014
Reading LevelBeginner
Publisher
ISBN-139781783280254
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
Fabien Serny
Fabien Serny
author image
Fabien Serny

Fabien Serny is a former core developer at PrestaShop. He has 10 years of experience in web development and e-commerce. He has worked for several big e-commerce companies in France, and then created his own company named 23Prod in late 2010. In 2014, along with two other former core developers from PrestaShop, he launched Froggy Commerce, a platform that sells simple and powerful modules for PrestaShop based on the needs of e-tailers. You can visit his websites http://www.23prod.com and http://www.froggy-commerce.com.
Read more about Fabien Serny

Right arrow

Chapter 7. The Carrier Module

As we saw earlier, there are three types of modules in PrestaShop: regular modules (which we developed in the first six chapters), carrier modules, and payment modules (which we will see in the next chapter).

In this chapter, we will see how carrier modules work. We will create a module that will retrieve shipping costs from web services and display them in the carrier list. We will also see one way to handle relay points, and how to:

  • Create a very simple carrier module

  • Use the Carrier object

  • Add options, such as relay points

First step to create a carrier module


Just like previous chapters, we will first create the directory and the main class of the module. We will name our new module mymodcarrier. So, create a mymodcarrier directory in the modules directory of PrestaShop, and then create a PHP file with the same name in your new directory.

In this file (mymodcarrier.php), create the class and code a constructor based on the same model as the mymodcomment module with one difference. This time the module's main class won't extend Module, but it will extend CarrierModule:

<?php

class MyModCarrier extends CarrierModule
{
  public function __construct()
  {
    $this->name = 'mymodcarrier';
    $this->tab = 'shipping_logistics';
    $this->version = '0.1';
    $this->author = 'Fabien Serny';
    $this->bootstrap = true;
    parent::__construct();
    $this->displayName = $this->l('MyMod carrier');
    $this->description = $this->l('A simple carrier module');
  }
}

Note

CarrierModule...

Using web services


Since we decided to create a module that connects to web services, I created a small API sample so we can run some tests. It is available in a directory named api, which I have attached to the code of this chapter. Please take this directory and copy and paste it into your localhost root directory.

API description

Here's a quick summary of how this API works:

  • The testConnection method:

    • URL query string:

      http://localhost/api/index.php?mca_email=fabien@mymodcomments.com&mca_token=23c4380e50caf91f81793ac91d9bfde9&method=testConnection.

    • Description:

      Each API call will ask for credentials. This method will be used to test whether the credentials are correct. In our case, I make available only the following credentials:

      • e-mail: fabien@mymodcomments.com

      • token: 23c4380e50caf91f81793ac91d9bfde9

    • Response:

      A reply in the JSON format containing the Success string if the credentials are correct and {"Error":"User or token is incorrect."} if the credentials are incorrect.

  • The getShippingCost...

Creating new carriers


Now that we have a working configuration form, we will have to create carriers. In our case, we will create two carriers, one with a classic delivery option and one with relay points.

If you don't know how a carrier works in PrestaShop, I first invite you to create some carriers manually in your administration panel. This will help you understand the method described in the upcoming code.

We will first add the install method in our module's main class, in which we will call a method named installCarriers:

public function install()
{
  if (!parent::install())
    return false;
  if (!$this->installCarriers())
    return false;
  return true;
}

Unfortunately, there is no native method to create carriers, even in the CarrierModule class. So, we will have to create the method ourselves. We will build it step by step:

  1. First, create the installCarriers method:

    public function installCarriers()
    {
    }
  2. Next, in this new function, retrieve the ID of the default language:

    $id_lang_default...

Using web services on shipping cost calculation


In order to keep the code clear in the module's main class, we will create a controller for shipping cost calculation:

public function getOrderShippingCost($params, $shipping_cost)
{
  $controller = $this->getHookController('getOrderShippingCost');
  return $controller->run($params, $shipping_cost);
}

As you can see, we've passed the two parameters available in the method to the controller. The two parameters are:

  • $params: In this case (the getOrderShippingCost function), $params is in fact the Cart object

  • $shipping_cost: This parameter corresponds to the shipping cost calculated by PrestaShop, which is the addition of the shipping handling fee (if the shipping_handling parameter of the carrier has been set to true, which is the case) and the price range / weight range cost (if the need_range parameter has been set to true, which is the case too)

    Note

    At this state, except if you set the shipping handling fee in the administration panel,...

Handling carrier update


If you have played a bit with the carrier system in the PrestaShop administration panel, you might have noticed that when you update a carrier, the carrier ID changes. In fact, when you update a carrier, PrestaShop will create a new carrier by copying the one you want to update and applying your changes. It will then delete (set the flag deleted to 1) the old carrier.

So if we think about it and if a merchant updates a carrier attached to our module, the carrier ID saved in the configuration table won't match anymore. Do not worry, we can handle this very simply.

First, we will hook our module on the actionCarrierUpdate hook, which, as the name indicates, is called when a carrier is updated. So, add the following code in the install method of your module's main class:

if (!$this->registerHook('actionCarrierUpdate'))
  return false;

As usual, we will create the matching hook method in mymodcarrier.php:

public function hookActionCarrierUpdate($params)
{
  $controller...

Displaying relay points


We are almost done! We will now see how to handle the relay points. You will not always need to manage relay points when you create a carrier module, but this is just an example here. With this method, you will be able to manage other things, such as delivery options (and insurance).

We will begin by attaching our module to the displayCarrierList hook. Then, create the hook method and the associated controller. At this point, I don't think I need to explain how it works again, but if you're experiencing some difficulties, do not hesitate to look at the code files attached to the code of this chapter (or to look at my GitHub repository: https://github.com/FabienSerny/mymodcarrier).

Create a displayCarrierList.tpl template in the views/templates/hook/directory and use it in your controller's run method:

public function run()
{
  return $this->module->display($this->file,'displayCarrierList.tpl');
}

As for the shipping costs, we will build one method to retrieve...

Associating the chosen relay point with the cart


To store the customer choice for their relay point, we will first have to create a MySQL table to save the association between the chosen relay point and the customer's cart.

In your module's root directory, create a new directory named install. In this directory, create one file named install.sql; this file will contain the new table creation:

CREATE TABLE IF NOT EXISTS `PREFIX_mymod_carrier_cart` (
  `id_mymod_carrier_cart` int(11) NOT NULL AUTO_INCREMENT,
  `id_cart` int(11) NOT NULL,
  `relay_point` text NOT NULL,
  `date_add` datetime NOT NULL,
  PRIMARY KEY (`id_mymod_carrier_cart`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Note

In the source code of this chapter, I also created an uninstall.sql file as an example. However, it is better not to delete data on module uninstallation to avoid the loss of data on orders.

Then, in our module's main class, we will add the loadSQLFile method that we used in a previous chapter:

public...

Displaying the customer's choice in the back office


You've reached the last part of this chapter (don't worry, it's the easiest part).

In the install method of your module, attach your module to the displayAdminOrder hook (do not forget to uninstall/reinstall your module once done).

Next, as for the other hooks, create a controller named displayAdminOrder. In this controller, first check whether the carrier selected is the one with the relay point. Then, retrieve the choice of the customer with the cart ID by using the method we created in the previous section, getRelayPointByCartId.

Finally, assign the object to Smarty. At the end, you should have something like this:

public function run()
{
  // Check if selected carrier is relay point carrier
  $order = new Order((int)Tools::getValue('id_order'));
  if ($order->id_carrier != Configuration::get('MYMOD_CA_REPO'))
    return '';

  // Retrieve relay point cart association
  $id_cart = (int)$order->id_cart;
  $relaypoint = MyModCarrierRelayPoint...

Summary


In this chapter, we saw how to create a fully functional carrier module. Also, you learned how to add complex features, such as delivery points.

In the next chapter, you will learn how to create payment modules, new order states, and send e-mails.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
PrestaShop Module Development
Published in: Nov 2014Publisher: ISBN-13: 9781783280254
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Fabien Serny

Fabien Serny is a former core developer at PrestaShop. He has 10 years of experience in web development and e-commerce. He has worked for several big e-commerce companies in France, and then created his own company named 23Prod in late 2010. In 2014, along with two other former core developers from PrestaShop, he launched Froggy Commerce, a platform that sells simple and powerful modules for PrestaShop based on the needs of e-tailers. You can visit his websites http://www.23prod.com and http://www.froggy-commerce.com.
Read more about Fabien Serny