ccc

Mostrando entradas con la etiqueta JQueryui: Datatables. Mostrar todas las entradas
Mostrando entradas con la etiqueta JQueryui: Datatables. Mostrar todas las entradas

Datatablas con Ajax

Poner un id al table:
<table id="datatable_lsg"...> Rellenar todos los thead pero en el tbody solo poner:
<tbody>
</tbody>

Cuando generas el datatable ya especificar el ajax de donde se saquen los datos, los parámetros que les pasarás, así como las características de cada columna: $('#datatable_lsg').dataTable( {
...
},
"processing": true,
"serverSide": true,
"ajax": {
"url": "{{ route('ajaxGetTodo') }}",
"data": {
"busq_by_texto": function() { return $('#busq_by_texto').val() },
}
},
'columns': [
{
data: 'idContent',
class: "",
createdCell: function (td, cellData, rowData, row, col) {
//Your js here.
$(td).css('text-align', 'center');
$(td).css('font-size', '1.2rem');
$(td).css('font-weight', 'bold');
}
},
{
data: 'title',
class: "",
createdCell: function (td, cellData, rowData, row, col) {
//Your js here.
$(td).css('text-align', 'center');
},
},
{
data: 'entradilla',
class: "",
createdCell: function (td, cellData, rowData, row, col) {
//Your js here.
$(td).css('text-align', 'center');
},
},
{
data: 'visibility',
class: "",
createdCell: function (td, cellData, rowData, row, col) {
//Your js here.
$(td).attr("hidden","");
},
},
],
createdRow: function (row, data, dataIndex) {
if (data["visibility"] == 0) {
}
else {
$('td', row).eq(3).html('visible');
$('#visibility_'+data["idContent"], row).attr('checked','checked');
}
}
});

En ajaxGetTodo:
...
foreach ($contents_list as $clave=>$valor) {
$data[] = array(
"idContent"=>$valor->idContent,
"visibility"=>$valor->visibility,
"title" => strip_tags($valor->content_title),
"entradilla" => strip_tags($valor->short_description),
);
}

$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalReg,
"iTotalDisplayRecords" => $totalRegFiltro,
"aaData" => $data,
);

echo json_encode($response);

Datatables: ordenar el campo fecha por fecha en español

Datatables: ordenar el campo fecha por fecha en español (por defecto lo trata siempre como un string y lo ordena alfabéticamente).

La solución es a la hora de rellenar ese campo:
<?php
$arr = explode("/",$motivo['fecha']);
$fechaEN = $arr[2].$arr[1].$arr[0];
?>
<td><a   href="xxx"><span style='display: none;'><?=$fechaEN;?></span><?=$motivo['fecha']?></a></td>

JQueryui Datatables: Que el buscador filtre solo por una columna concreta y no por las demás

$('#tablaLSG').dataTable( {
            "columnDefs": [
                { "targets": [1,2,3,4,5], "searchable": false } // Filtra solo por la columna 0
            ]
        });

JQueryui Datatables: Especificar el número de filas que quieres que se muestren

$('#tablaLSG').dataTable({
   aLengthMenu: [
     [25, 50, 100, 200, -1],
     [25, 50, 100, 200, "TODOS"]
   ],
   iDisplayLength: 100, // Que muestre 100
});

JQueryui Datatables: Que no ordene por ningún campo por defecto

$(function() {
            $('#tablaLSG').dataTable( {
                "aaSorting": []
            });
       });

JQueryui Datatables: filtrar genérico (sin acentos, mayúsculas, etc)

Por una parte en tu web:
function accents_supr(data){
        return ! data ?
            '' :
            typeof data === 'string' ?
                data
                    .replace( /\n/g, ' ' )
                    .replace( /[áàäâ]/g, 'a' )
                    .replace( /[éèëê]/g, 'e' )
                    .replace( /[íìïî]/g, 'i' )
                    .replace( /[óòöô]/g, 'o' )
                    .replace( /[úùüû]/g, 'u' ):
                data;
    
            jQuery.extend( jQuery.fn.dataTableExt.oSort,
            {
                "spanish-string-asc"  : function (s1, s2) { return s1.localeCompare(s2); },
                "spanish-string-desc" : function (s1, s2) { return s2.localeCompare(s1); }
            });
    
            jQuery.fn.DataTable.ext.type.search['spanish-string'] = function ( data ) {
                return accents_supr(data);      
            }
    }

Y luego en el datatables.js hay que modificar:
function nb(a) {
   var b = !this.value ? "" : this.value;
   b=accents_supr(b);
   ....
  g(a.nTable).on("search.dt.DT", function (b, c) {
                // LSG
                totalReg = a.aoData.length;
                for (k=0; k < totalReg; k++) {
                    a.aoData[k]._sFilterRow = a.aoData[k]._sFilterRow.replace("á", "a");
                    a.aoData[k]._sFilterRow = a.aoData[k]._sFilterRow.replace("é", "e");
                    a.aoData[k]._sFilterRow = a.aoData[k]._sFilterRow.replace("í", "i");
                    a.aoData[k]._sFilterRow = a.aoData[k]._sFilterRow.replace("ó", "o");
                    a.aoData[k]._sFilterRow = a.aoData[k]._sFilterRow.replace("ú", "u");
                    // console.log(show_props(a.aoData[k], "o"));
                }
                // FIN LSG
            ....
}

JQueryui: Datatables

<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<script type="text/javascript" language="javascript" src="http://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>

<?php
$sql_aux = "select nomColab from tcolab order by nomColab";
 $reg_aux = $bd->getRegistro($sql_aux);
 ?>
 <hr>
  <div class="container" style="width:700px;">
<section>
<table id="tablaLSG" class="display cabDatatable" cellspacing="0" width="100%" >
<thead>
<tr>
<th>Colaborador</th>
</tr>
</thead>

<tfoot>
<tr>
<th>Colaborador</th>
</tr>
</tfoot>

<tbody>
<?php
$total = count($reg_aux);
for ($i = 0; $i < $total; $i++) { ?>
<tr>
<td><a class=letraAzul12 href="buscar-<?php echo urlencode($reg_aux[$i]["nomColab"]);?>.html"><?php echo utf8_encode($reg_aux[$i]["nomColab"]);?></td>

</tr>
<?php
}
unset($reg_aux);
?>
</tbody>
</table>
</section>
</div>
<hr>

 <script>
$(document).ready(function() {
$('#tablaLSG').DataTable({
"language": {
"sProcessing":    "Procesando...",
"sLengthMenu":    "Mostrar _MENU_ registros",
"sZeroRecords":   "No se encontraron resultados",
"sEmptyTable":    "Ningún dato disponible en esta tabla",
"sInfo":          "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty":     "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered":  "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix":   "",
"sSearch":        "Buscar:",
"sUrl":           "",
"sInfoThousands":  ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst":    "Primero",
"sLast":    "Último",
"sNext":    "Siguiente",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
}
});
});
</script>