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 class="form-control" 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);
}