Home > Software engineering >  PHP - Select2 dinamically set multiple selected values when loading data from ajax
PHP - Select2 dinamically set multiple selected values when loading data from ajax

Time:03-17

Hi I'm trying to bring data and show it as selected in a multiple select2. The below code works just fine to bring all the data, but I don't know how can I add the selected info.

The table in my DB where the selected options are is "ejecutivo_agencia" and have two columns, id_agencia and id_comercial.

The select2 brings all the agencias, and I need to mark those that are saved in ejecutivo_agencia as selected.

This is my html: <select name="agencia[]" id="listadoAgencias"></select>

This is my ajax:

$('#listadoAgencias').select2({
        width: '100%',
        placeholder: 'Buscar agencia por Nombre o Código',
        language: 'es',
        multiple: true,
        ajax: {
            url: '<?php echo base_url("ajax/ajax_agencias/") ?>',
            type: "post",
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    searchTerm: params.term // search term
                };
            },
            processResults: function(response) {
                return {
                    results: response
                };
            },
            cache: true
        },
        escapeMarkup: function(markup) {
            return markup;
        }

    });

And this is my php code:

public function ajax_agencias()
    {
        $searchTerm = $_POST['searchTerm'];

        $this->db->select('*');
        $this->db->where("CodigoZARO like '%" . $searchTerm . "%' ");
        $this->db->or_where("Nombre_AGENCIA like '%" . $searchTerm . "%' ");
        // $this->db->order_by("Nombre_AGENCIA", 'ASC');
        $this->db->order_by("CodigoZARO", 'ASC');
        $fetched_records = $this->db->get('agencias', 60);
        $agencias = $fetched_records->result_array();

        // Initialize Array with fetched data
        $data = array();

        foreach ($agencias as $a) {

            $data[] = array("id" => $a['CodigoZARO'], "text" => $a['CodigoZARO'] . ' - ' . $a['Nombre_AGENCIA']);
        }

        echo json_encode($data);
    }

CodePudding user response:

I solved it following this article: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

this is my ajax:

$('#listadoAgenciasEdit').select2({
        width: '100%',
        placeholder: 'Buscar agencia por Nombre o Código',
        language: 'es',
        multiple: true,
        ajax: {
            url: '<?php echo base_url("ajax/ajax_agencias/") ?>',
            type: "post",
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    searchTerm: params.term // search term
                };
            },
            processResults: function(response) {
                return {
                    results: response
                };
            },
            cache: true
        },
        escapeMarkup: function(markup) {
            return markup;
        }

    });

    var listadoAgencias = $('#listadoAgenciasEdit');
    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
            id_comercial: listadoAgencias.data('id')
        },
        url: '<?php echo base_url("ajax/ajax_agencias_selected/") ?>'
    }).then(function(data) {
        console.log(data);
        // create the option and append to Select2
        var option = new Option(data[0].text, data[0].id, true, true);
        listadoAgencias.append(option).trigger('change');

        // manually trigger the `select2:select` event
        listadoAgencias.trigger({
            type: 'select2:select',
            params: {
                data: data
            }
        });
    });

and this my php code:

public function ajax_agencias()
    {
        $searchTerm = $_POST['searchTerm'];

        $this->db->select('*');
        $this->db->where("CodigoZARO like '%" . $searchTerm . "%' ");
        $this->db->or_where("Nombre_AGENCIA like '%" . $searchTerm . "%' ");
        // $this->db->order_by("Nombre_AGENCIA", 'ASC');
        $this->db->order_by("CodigoZARO", 'ASC');
        $fetched_records = $this->db->get('agencias', 60);
        $agencias = $fetched_records->result_array();

        // Initialize Array with fetched data
        $data = array();

        foreach ($agencias as $a) {

            $data[] = array("id" => $a['CodigoZARO'], "text" => $a['CodigoZARO'] . ' - ' . $a['Nombre_AGENCIA']);
        }

        echo json_encode($data);
    }

    public function ajax_agencias_selected()
    {        

        $id_comercial = '';

        if(isset($_POST['id_comercial'])){
            $id_comercial = $_POST['id_comercial'];
        }
        
        $this->db->select('*');
        $this->db->from('ejecutivo_agencia');
        $this->db->where('ejecutivo_agencia.id_comercial', $id_comercial);
        $this->db->join('agencias', 'ejecutivo_agencia.id_agencia = agencias.CodigoZARO');        
        $fetched_records = $this->db->get();        
        $selected = $fetched_records->result_array();
        // var_dump($selected); exit;
        // Initialize Array with fetched data
        $data = array();

        foreach ($selected as $a) {

            $data[] = array("id" => $a['CodigoZARO'], "text" => $a['CodigoZARO'] . ' - ' . $a['Nombre_AGENCIA']);
        }

        echo json_encode($data);
    }
  • Related