Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 "TypeError: a is undefined" error

I've this code for create a Select2 element from an input field:

var codigo_arancelario = $codigo_arancelario.val();

$codigo_arancelario.select2({
    placeholder: "Seleccione un estado",
    ajax: {
        dataType: 'json',
        url: function () {
            return Routing.generate('obtenerCodigoArancelario');
        },
        data: function (codigo_arancelario) {
            return {
                filtro: codigo_arancelario
            }
        },
        results: function (data) {
            var myResults = [];
            $.each(data.entities, function (index, item) {
                myResults.push({
                    'id': item.id,
                    'nombre': item.nombre
                });
            });
            return {
                results: myResults
            };
        }
    },
    formatNoResults: function () {
        return "No se encontró el código";
    },
    formatAjaxError: function () {
        return "No hay conexión con el servidor";
    }
});

But any time I try to use it I get this error on Firebug console:

TypeError: a is undefined

I checked the Response headers and I got a Content-Type application/json and also I check the Request headers since I'm using Symfony2 in the server side and it send the X-Requested-With XMLHttpRequest. The Symfony2 function return a JSON like this one:

{
   "valid":false,
   "entities":[
      {
         "id":101,
         "codigo":"4545",
         "descripcion":null
      },
      {
         "id":102,
         "codigo":"45455",
         "descripcion":"gfhgfhfghfgh"
      },
      {
         "id":103,
         "codigo":"45457",
         "descripcion":"etert"
      }
   ]
}

Where is the error on my code?

like image 568
ReynierPM Avatar asked Oct 22 '14 04:10

ReynierPM


1 Answers

Select2 expects [{text="john doe",id="1"},{text="jane doe",id="2"}]

so you need to change 'nombre': item.nombre to 'text': item.nombre it should look like followed:

 myResults.push({
       'id': item.id,
       'text': item.nombre
 });
like image 134
Mohit Kumar Avatar answered Oct 18 '22 09:10

Mohit Kumar