A PrestaShop module helper to display “boxed” success and error notifications

First, a little bit of theory:

PrestaShop (PS) implements the concepts of modularity and extensibility through two different entities:

  1. modules
  2. hooks

The first ones are actually wrappers for the custom functionality you may need on your store while the latter ones are the connection points offered by the PS core.

Hooks can be used by modules to directly implement both frontend and  backend functionality.

In the context of a module you can specify as many hooks as you want to extend the default behavior of your store. This is accomplished by defining methods with the same name of the hooks you want to use.

Besides hooks, modules also support some nice features that can be directly used to handle their configuration panel in the backoffice.

The appearance of the panel is handled by the getContent() method.

To see what I’am talking about, have a look at the code of one of the PS default modules. Here’s the blockbanner, for example.

The logic related to the validations and saving of the configuration values is usually placed inside the postProcess() method and for the blockbanner module you can see the code right here.

Now…enough with the theory!

In the context of the over mentioned validations and saving you may probably want to display some success or error message according to the result of some operation.

To accomplish this goal you should push the messages you want to deliver to the users of your module right into the errors and success arrays (i.e. errors[], success[]). These are defined inside the Module class that every module should extend to be called a module 😛

To display these messages, all you have to do is to call the respective display method, i.e. displayError() and displayConfirmation().

In case your module has a complex configuration panel you may encounter the need to display the errors and the confirmations by following some logic.

The one I stick with is to always display each single message in a separate box.

Here’s an example of two boxes, one for an error and one for a success:

image

To do this I use a little helper I wrote.

Here it is:

    

  private function displayNotifications($notification_types = array())
  {
    $output = '';
    foreach ($notification_types as $notification_types_key => $notification_type) {
      $notifications = "_{$notification_type}s";
      foreach ($this->$notifications as $notification_key => $notification) {
        $output .= call_user_func_array(
          array($this, 'display'.ucfirst($notification_type)),
          array($notification)
        );
      }
    }
    return $output;
  }

It simply loops through the message arrays you pass as parameter and call the correct display method to render each message inside its box.

All the messages with their respective box are then concatenated into a single string.

That’s all folks.

Cheers! 🙂

Leave a Reply

wpDiscuz