Search code examples
prestashopprestashop-1.7

Prestashop - Adding a select box for produts in custom module with search


I'm making a custom module and I want to select 4 products as featured products, but I have 1200 products so I wanted to add a search so it's easier to select the products that the user wants.

Since it uses Bootstrap I thought about using their "data-live-search='true'" but I didn't find a way to insert this.

This is the code I have so far:

$fields_form = [
            'form' => [
                'legend' => [
                    'title' => $this->trans('Settings', [], 'Admin.Global'),
                    'icon' => 'icon-cogs',
                ],

                'description' => $this->trans('Add products to your homepage', [], 'Modules.Featuredproducts.Admin'),
                'input' => [

                    array(
                        'type' => 'select',
                        'label' => $this->l('Select a Product'),
                        'name' => 'id_product',
                        'required' => false,
                        'col' => '8',
                        'class' => 'selectpicker',
                        'bootstrap' => true,
                        'options' => array(
                            'query' => Product::getProducts($this->context->language->id, 0, 0, "id_product", "desc"), // true only the ones active
                            'id' => 'id_product',
                            'name' => 'name',
                            'default' => array(
                                'value' => '',
                                'label' => $this->l('--')
                            )
                        )
                    )
                ],
                'submit' => [
                    'title' => $this->trans('Save', [], 'Admin.Actions'),
                ],
            ],
        ];

Solution

  • Try to change class to select2, it should work automaticly If not add some js to your module, and use select2 jquery plugin

    $(()=>{
      $("select.select2").select2();
    });

    Do not forget to add

    $this->addjQueryPlugin(array(
        'select2',
    ));
    

    To your controller.

    And please... if you want to work this nice and without any latency do not load all products data in select source. Think what will happen if someone may have many products (10k 100k)?

    Use select2 ajax to load data which can be paginated. https://select2.org/data-sources/ajax