Select Page

PrestaShop Global JavaScript component

Raghvendra Pratap
Published: May 2, 2022

In this blog, we are about to learn the use of PrestaShop Global JavaScript components in modern forms.

A PrestaShop JavaScript component is a reusable code and these are created in core PrestaShop. For example:

  • tinymce-editor.js
  • router.js:
  • text-to-link-rewrite-copier.js
  • generatable-input.js

These global javascript components are defined in the admin directory.
admin-dev\themes\new-theme\js\components.

Why Global JavaScript component introduced:

In order for modules to use JavaScript components from the Core in lower versions ( < 1.7.8), we needed to import them using the below statements
To use translatable type, we write below code :
import TranslatableInput from ‘../../../../../admin-dev/themes/new-theme/js/components/translatable-input’;

This path is not compatible so we cannot use them like this.

How to use

We are going to learn about components by creating a module.

So lets start.

Firstly we will create a module and an admin controller inside it

modules/demojscomponent/src/Controller/DemoFormController.php
<?php
declare(strict_types=1);
namespace DemoJsComponent\Controller;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use DemoJsComponent\Form\DemoForm;

class DemoFormController extends FrameworkBundleAdminController
{
    public function indexAction(Request $request): Response
    {
        $form = $this->createForm(DemoForm::class);
        return $this->render('@Modules/demojscomponent/views/templates/admin/demo_form.html.twig',[
            'demoForm' => $form->createView(),
        ]);
    }
}

Now, to create the form, we will create a form class

modules/your-module/src/Form/DemoForm.php
<?php
declare(strict_types=1);
namespace DemoJsComponent\Form;
use PrestaShopBundle\Form\Admin\Type\FormattedTextareaType;
use PrestaShopBundle\Form\Admin\Type\GeneratableTextType;
use PrestaShopBundle\Form\Admin\Type\TextWithLengthCounterType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class DemoForm extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('formatted_text_area_type', FormattedTextareaType::class, [
                'label' => 'Formatted text area type',
            ])
            ->add('generatable_text_type', GeneratableTextType::class, [
                'label' => 'Generatable text type',
                'generated_value_length' => 5,
            ])
            ->add('text_with_length_counter_type', TextWithLengthCounterType::class, [
                'max_length' => 50,
                'label' => 'Text with length counter type',
            ]);
    }
}

To to render the form, we will create a twig file

modules/your-module/views/templates/admin/demo_form.html.twig
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
 
<div class="card">
  <h3 class="card-header">
    <i class="material-icons">settings</i>Text form types
</h3>
<div class="card-block row">
    <div class="card-text">
      {{form_start(demoForm)}}
      {{form_end(demoForm)}}
  </div>
</div>
</div>
<div class="card">
  <h3 class="card-header">
    <i class="material-icons">settings</i>Search Customer
</h3>
<div class="card-block">
    <div class="card-text">
       <div class="form-group row type-text ">
        <label class="form-control-label col-md-4" for="demo_search_customer">Search for customer</label>
        <input type="text" id="demo_search_customer" class="col-md-4 form-control">
        <button type="button" class="col-md-4 btn btn-primary" id="demo_search_customer_btn">Search</button>
    </div>
    <div id="info-block" class="d-none"></div>
    <div id="customers-results" class="d-none">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>First name</th>
              <th>Last name</th>
              <th>Email</th>
          </tr>
      </thead>
      <tbody>
      </tbody>
  </table>
</div>
</div>
</div>
</div>

{% endblock %}
{% block javascripts %}
  {{ parent() }}
  <script src="https://webkul.com/blog/how-to-use-global-javascript-components-in-prestashop-modern-pages/{{ asset("../modules/demojscomponent/views/js/demo-form.js') }}"></script>
{% endblock %}

Now we need to create and include a JS file in template file because PrestaShop global javascript components are defined in JS files.

/modules/your-module/views/js/demo-form.js
$(document).ready(function () {
    window.prestashop.component.initComponents(
        [
            'TinyMCEEditor',
            'TranslatableInput',
            'GeneratableInput',
            'TextWithLengthCounter',
            'Router'
        ],
    );
window.prestashop.instance.generatableInput.attachOn('.js-generator-btn');
    $(document).on('click', '#demo_search_customer_btn', () => search($('#demo_search_customer').val()));
function search(searchPhrase) {
    var route = window.prestashop.instance.router.generate('admin_customers_search');
    $.get(route, {
      'customer_search': searchPhrase,
    }).then((data) => renderResults(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.id_customer}</td>
      <td>${customer.firstname}</td>
      <td>${customer.lastname}</td>
      <td>${customer.email}</td>
      </tr>`);
    }
  }
});

Below output is the result of using:

TinyMCEEditor , GeneratableInput and TextWithLengthCounter component.

Forms generated by PrestaShop Global JavaScript Components
Search list generated by PrestaShop Global JavaScript Components

That’s all about this blog.

If any issue or doubt in the above step, please feel free to let us know in the comment section.

We would be happy to help.

You can also explore our PrestaShop Development Services and a large range of quality PrestaShop Modules.

For any doubt contact us at [email protected].

Source: webkul.com