Add date-attribute in Columns using Datatable and Ajax

Asked

Viewed 138 times

0

Good afternoon,

I have a code that returns me a table via ajax and I would like to add in all columns of this ajax a data-attribute with a specific value:

Example:

var atributo = json[i]['codigo_usuario'];

and column rows should look as follows:

In other words, the tag "tr" should have the date-attribute

tr

date-attribute="49"

/tr

tr

date-attribute="94"

/tr

Follow my Datatable code which is in the latest version:

$('.table.aprovado').dataTable({
               "language" : {
                    "decimal": ",",
                    "thousands": ",",
                    "sEmptyTable": "Nenhum registro encontrado",
                    "sInfo": "Mostrando  _START_ até _END_ de _TOTAL_ Resultados",
                    "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                    "sInfoFiltered": "(Filtrados de MAX registros)",
                    "sInfoPostFix": "",
                    "sInfoThousands": ".",
                    "sLengthMenu": "_MENU_ resultados por página",
                    "sLoadingRecords": "Carregando...",
                    "sProcessing": "Processando...",
                    "sZeroRecords": "Nenhum registro encontrado",
                    "sSearch": "Pesquisar",
                    "oPaginate": {
                        "sNext": "Próximo",
                        "sPrevious": "Anterior",
                        "sFirst": "Primeiro",
                        "sLast": "Último"
                    },
                    "oAria": {
                        "sSortAscending": ": Ordenar colunas de forma ascendente",
                        "sSortDescending": ": Ordenar colunas de forma descendente"
                    }
                },
                dom: 'Bfrtip',  
                buttons: [
                    'copyHtml5',
                    'excelHtml5',
                    'csvHtml5'
                ],
               "order": [[ 6, 'desc' ]],
               "ajax": {
                    "jQueryUI": true,
                    "processing": true,
                    "serverSide": true,
                    "async": true,
                    "url": base_url+'painel/Inscritos/buscaInscritosAprovado',
                    "type": "POST",
                    "dataSrc": function( json ){
                        var return_data = new Array();

                        for(var i=0; i<json.length; i++) { 

                            if(json[i]['limite_usu'] == null) {
                                var limite_usu = "A definir";
                            } else {
                                var limite_usu = 'R$ ' + parseFloat(json[i]['limite_usu']).toLocaleString('pt-br', {minimumFractionDigits: 2});
                            }

                            if(json[i]['aberto'] == null) {
                                var aberto = "A definir";
                            } else {
                                var aberto = 'R$ ' + parseFloat(json[i]['aberto']).toLocaleString('pt-br', {minimumFractionDigits: 2});
                            }

                            if(json[i]['operado'] == null) {
                                var operado = "A definir";
                            } else {
                                var operado = 'R$ ' + parseFloat(json[i]['operado']).toLocaleString('pt-br', {minimumFractionDigits: 2});
                            }

                            var data_1 = json[i]['created_usu'].substring(0,10);

                            var hora = json[i]['created_usu'].substring(10,19);

                            var data_2 = data_1.split('-').reverse().join('/') + hora;

                            var teste = '<a data-toggle="tooltip"  data-placement="top" data-nome="' + json[i]['fantasia_usu'] + '" data-cod="' + json[i]['codigo_usu'] + '" href="Javascript: void(0)" data-url="painel/sistema/resetarInscrito" onclick="aguardandoAprovacao('+ json[i]['codigo_usu'] + ')"><svg class="icone-acao-tabela"><use xlink:href="#icone_retorno"></use></svg></a>'
                            + '<a data-toggle="tooltip" data-placement="top" href="Javascript: void(0)" onclick="logarComo('+ json[i]['codigo_usu'] + ')"><svg class="icone-acao-tabela"><use xlink:href="#user"></use></svg></a>'
                            + '<a data-toggle="tooltip" title="Não recebe email" data-placement="top" href="Javascript: void(0)" onclick="toogleEmail('+ json[i]['codigo_usu'] + "," + json[i]['recebe_email'] + ')"><svg class="icone-acao-tabela"><use xlink:href="#email_2"></use></svg></a>'
                            + '<a data-toggle="tooltip" class="inscrito-reseta" data-placement="top" data-original-title="Remover" data-nome="' + json[i]['fantasia_usu'] + '" data-cod="' + json[i]['codigo_usu'] + '" data-email="' + json[i]['email_usu'] + '" href="Javascript: void(0)" data-url="painel/sistema/resetarInscrito"><svg class="icone-acao-tabela"><use xlink:href="#icone-x"></use></svg></a>'
                            + '<a data-toggle="tooltip" class="editar-inscrito" data-placement="top" data-original-title="Alterar"  data-cod="' + json[i]['codigo_usu'] + '" href="Javascript: void(0)" data-url="painel/sistema/dadosModalInscrito"><svg class="icone-acao-tabela"><use xlink:href="#icone_editar"></use></svg></a>'
                            + '<a data-toggle="tooltip" class="detalhar-inscrito" data-placement="top" data-original-title="Detalhar" data-nome="' + json[i]['fantasia_usu'] + '" data-cod="' + json[i]['codigo_usu'] + '" href="Javascript: void(0)" data-url="painel/sistema/buscaDadosPessoais"><svg class="icone-acao-tabela"><use xlink:href="#icone_detalhar"></use></svg></a>';


                            return_data.push({
                              'razao_usu': json[i]['razao_usu'],
                              'cnpj_usu' :  json[i]['cnpj_usu'],
                              'limite_usu' : limite_usu,
                              'aberto' : aberto,
                              'operado' : operado,
                              'email_usu' : json[i]['email_usu'],
                              'created_usu' : data_2,
                              'acoes' : teste
                            })
                        }
                        return return_data;
                    }
                  },
                "aoColumns": [
                    { "data": 'razao_usu' },
                    { "data": 'cnpj_usu' },
                    { "data": 'limite_usu' },
                    { "data": 'aberto' },
                    { "data": 'operado' },
                    { "data": 'email_usu' },
                    { "data": 'created_usu' },
                    { "data": 'acoes' }
                ]   
            });

1 answer

0

Add one more entry to the array return_data[] with the value cod_usuario:

return_data.push({
   'razao_usu': json[i]['razao_usu'],
   'cnpj_usu' :  json[i]['cnpj_usu'],
   'limite_usu' : limite_usu,
   'aberto' : aberto,
   'operado' : operado,
   'email_usu' : json[i]['email_usu'],
   'created_usu' : data_2,
   'acoes' : teste,
   'cod_usuario' : json[i]['codigo_usu']
})

And add the function createdRow in the Datatables:

'createdRow': function(row, data, dataIndex){
   $(row).attr('data-attribute', data.cod_usuario);
},

Thus each line tr (and not columns, as you say) will have the attribute data-attribute with the value of json[i]['codigo_usu'].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.