Back to Top

How to use JS routing component in PrestaShop Backoffice

Updated 30 June 2023

In this blog, we will learn how to use the Javascript routing component in the PrestaShop back office. Since the 1.7.8.0 version, you can use components without importing them. window.prestashop.component the object is used for this purpose.
These are some rules to understand the JS component

i) Reusable components in BO will be available globally through window.prestashop object.

ii) PrestaShop components will be grouped together and made available on all pages. So you have to decide on the controller page which components need to initialize.

iii) Reusable components will be available as a namespace window.prestashop.component.

iv) The namespace will contain classes like this prestashop.component.SomeComponent. If you want to get a new instance of SomeComponent, you call the new prestashop.component.SomeComponent(…params)

Searching for an experienced
Prestashop Company ?
Find out More

v) Reusable components will be available as initialized instances through window.prestashop.instance. These instances are initialized with default parameters by the initComponents function.

vi) A function initComponents available through prestashop.component is responsible for building window.prestashop.instance.

Here, we are showing the process step by step with an example module ‘wkjsrouting

Step 1: Create the module class

Here, we have created the module class file “wkjsrouting/wkjsrouting.php

In this class, we are initializing the module and redirecting the configuration page to modern page routes.

<?php
declare(strict_types=1);

use PrestaShop\Module\WkJsRouting\Install\Installer;

if (!defined('_PS_VERSION_')) {
    exit;
}

require_once __DIR__ . '/vendor/autoload.php';

class WkJsRouting extends Module
{
    public $tabs = [
        [
            'class_name' => 'DemoPageController',
            'visible' => true,
            'name' => 'Demo page',
            'parent_class_name' => 'CONFIGURE',
        ],
    ];

    public function __construct()
    {
        $this->name = 'wkjsrouting';
        $this->author = 'Webkul';
        $this->version = '1.0.0';
        $this->ps_versions_compliancy = ['min' => '1.7.7.0', 'max' => '8.99.99'];

        parent::__construct();

        $this->displayName = $this->l('Demo Module');
        $this->description = $this->l('Javascript component Router usage in BO');
    }

    /**
     * @return bool
     */
    public function install()
    {
        if (!parent::install()) {
            return false;
        }

        $installer = new Installer();

        return $installer->install($this);
    }

    public function getContent()
    {
        $moduleAdminLink = Context::getContext()->link->getAdminLink('DemoPageController', true);
        Tools::redirectAdmin($moduleAdminLink);
    }
}

Step 2: Define routes
Create routes.yml file inside the wkjsrouting/config folder

demo_page_index:
    path: demo-page/
    methods: [GET]
    defaults:
        _controller: PrestaShop\Module\WkJsRouting\Controller\DemoPageController::indexAction
        _legacy_controller: 'DemoPageController'
        _legacy_link: 'DemoPageController'

Step 3: Create a controller to handle the JS request

Path: wkjsrouting/src/Controller/DemoPageController.php

<?php

declare(strict_types=1);

namespace PrestaShop\Module\WkJsRouting\Controller;

use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\HttpFoundation\Response;

class DemoPageController extends FrameworkBundleAdminController
{
    public function indexAction(): Response
    {
        return $this->render('@Modules/wkjsrouting/views/templates/admin/demo_page.html.twig');
    }
}

Step 4: Create an installer class

Path: wkjsrouting/src/Install/Installer.php

<?php

declare(strict_types=1);

namespace PrestaShop\Module\WkJsRouting\Install;

use Module;

class Installer
{
    /**
     * Module's installation entry point.
     *
     * @param Module $module
     *
     * @return bool
     */
    public function install(Module $module): bool
    {
        if (!$this->registerHooks($module)) {
            return false;
        }

        return true;
    }

    /**
     * Register hooks for the module.
     *
     * @param Module $module
     *
     * @return bool
     */
    private function registerHooks(Module $module): bool
    {
        $hooks = [];

        return (bool) $module->registerHook($hooks);
    }
}

Step 5: Create a view

Twig file demo_page.html.twig, path: wkjsrouting/views/templates/admin/demo_page.html.twig

{% extends '@PrestaShop/Admin/layout.html.twig' %}

{% block content %}
  <div>
    <div class="form-group">
			<div class="row">
				<label class="col-lg-3 control-label text-right" for="demo_search_customer">
          {{ 'Search customer'|trans({}, 'Modules.Wkjsrouting.Admin') }}
				</label>
				<div class="col-lg-6">
          <div class="input-group">
            <input type="text" class="form-control" id="demo_search_customer">
            <div class="input-group-addon"><button type="button" class="btn btn-primary" id="demo_search_customer_btn"> {{ 'Search'|trans({}, 'Modules.Wkjsrouting.Admin') }}</button></div>
          </div>
				</div>
			</div>
		</div>
  </div>
  <div id="info-block" class="d-none"></div>
  <div id="customers-results" class="d-none">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>{{ 'Email'|trans({}, 'Modules.Wkjsrouting.Admin') }}</th>
          <th>{{ 'Full Name'|trans({}, 'Modules.Wkjsrouting.Admin') }}</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
{% endblock %}

{% block javascripts %}
  {{ parent() }}
  <script src="{{ asset('../modules/wkjsrouting/views/js/admin.js') }}"></script>
{% endblock %}

Step 6: JS file for routing

This file is responsible to use the PrestaShop JS component

Path: wkjsrouting/views/js/admin.js

$(() => {
    // initialize the Router component in PS 1.7.8+ 
    if (typeof window.prestashop.component !== 'undefined') { window.prestashop.component.initComponents(['Router']); }

    // initiate the search on button click
    $(document).on('click', '#demo_search_customer_btn', () => search($('#demo_search_customer').val()));

    /**
     * Performs ajax request to search for customers by search phrase
     *
     * @param searchPhrase
     */
    function search(searchPhrase) {
        var route;
        var getParams = { 'customer_search': searchPhrase };

        if (typeof window.prestashop.component !== 'undefined') {
            // use the router component to generate the existing route in PS 1.7.8+
            route = window.prestashop.instance.router.generate('admin_customers_search');
        } else {
            // use pure JS functions if PS search route component is unavailable
            const locationSearch = new URLSearchParams(window.location.search);
            const locationPathname = window.location.pathname.split('/');

            for (const param of locationSearch) {
                if (param[0] === '_token') getParams[param[0]] = param[1];
            }
            route = `${locationPathname[0]}/${locationPathname[1]}/sell/customers/search`;
        }

        // use the ajax request to get customers
        $.get(route, getParams
            // render the customers
        ).then((data) => renderResults(data));
    }

    /**
     * Renders the results block
     *
     * @param {Object} data
     */
    function renderResults(data) {
        var $infoBlock = $('#info-block')
        $infoBlock.addClass('d-none').empty();
        var $resultsBlock = $('#customers-results');
        var $resultsBody = $('#customers-results tbody');

        if (data.found === false) {
            $infoBlock.text('No customers found').removeClass('d-none');
            $resultsBlock.addClass('d-none');
            $resultsBody.empty();

            return;
        }

        $resultsBlock.removeClass('d-none');
        $resultsBody.empty();

        for (const id in data.customers) {
            const customer = data.customers[id];
            $resultsBody.append(`<tr><td>${customer.email}</td><td>${customer.firstname} ${customer.lastname}</td></tr>`);
        }
    }
});

Step 7: Create a composer.json file to install the dependency

{
    "name": "prestashop/wkjsrouting",
    "description": "Demo Module",
    "license": "AFL-3.0",
    "authors": [{
            "name": "Webkul"
        },
        {
            "name": "dev"
        }
    ],
    "autoload": {
        "psr-4": {
            "PrestaShop\\Module\\WkJsRouting\\": "src/"
        },
        "config": {
            "prepend-autoloader": false
        },
        "type": "prestashop-module"
    }
}

Step 8: Installation

Copy created a module on the modules directory of PrestaShop and run the composer command composer install to install all dependencies. The complete module folder structure is attached in the screenshot.

folder_structure

After installing the module, click on configure button, and you will able to see the search page and search customers by name.

output
routing_results

That’s all about this blog.

If any issues or doubts please feel free to mention them in the comment section.

I would be happy to help.

Also, you can explore our PrestaShop Development Services & a large range of quality PrestaShop Modules.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home