I’m trying to create dynamic columns
in my Datatables.
Suppose I want to create 4 columns + default column (2 buttons). Well, we would do the following (this works):
$('#tablaUsuarios').DataTable({
"columns": [
{"data": "usuario"},
{"data": "apellido1"},
{"data": "apellido2"},
{"data": "email"},
{"defaultContent": "<div class='text-center'><div class='btn-group'><button class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>"}
],
});
Now suppose I want to do the SAME thing, but with a single value, something like this:
var dataHeader = <?=$fields?>;
$('#tablaUsuarios').DataTable({
"columns": [
dataHeader,
"defaultContent": "<div class='text-center'><div class='btn-group'><button class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>"
],
});
dataHeader
contains the following:
0: {data: "id", mData: "id"}
1: {data: "usuario", mData: "usuario"}
2: {data: "apellido1", mData: "apellido1"}
3: {data: "apellido2", mData: "apellido2"}
4: {data: "email", mData: "email"}
length: 5
__proto__: Array(0)
(Is a copy paste from console.log from my browser because I need reputation to upload images).
As all of you can see, it has the same format but it doesn’t show the defaultColumns and I don’t know why. I don’t get any type of error.
Does anyone know if it is possible to do something like this?
This is my full code:
<?php
include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');
$test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
switch($_POST['action']){
case 'datosTabla':
$res = json_decode($_POST['datos']);
echo json_encode($res, JSON_UNESCAPED_UNICODE);
break;
case 'showtable':
$res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
foreach ($res as $data){
$resultados['data'][] = $data;
}
$resultados = json_encode($resultados);
foreach(json_decode($_POST['tableFields']) as $columnsDB){
$fields[] = array('data'=>$columnsDB);;
}
$fields = json_encode($fields);
?>
<div class="container caja">
<div class="row">
<div class="col-lg-12 col-sm-12">
<div>
<table id="tablaUsuarios" class="table table-striped table-bordered table-condensed" style="width:100%" >
<thead class="text-center">
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function() {
var datos = '<?=$resultados?>';
var dataHeader = <?=$fields?>;
console.log(dataHeader);
$('#tablaUsuarios').DataTable({
"language": {"url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Spanish.json"},
"paging": true,
"lengthChange": true,
"searching": true,
"info": true,
"autoWidth": true,
"scrollX": true,
"ajax":{
"url": '<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/',
"method": 'POST',
"data":{action: "datosTabla", datos: datos}
},
"columns":
dataHeader,
"defaultContent": "<div class='text-center'><div class='btn-group'><button class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>",
success: function() {
alert("Hello, successful!");
}
});
})
</script>
<?php
break;
}
?>
Also, as an additional question, how can I add values in my TH? I mean, add like a title for each column.
Also, as an additional question, how can I add values in my TH? I mean, add like a title for each column.
I tryied to add <tr><td>Test 1</td></tr>
in my <thead></thead>
, but nothing …
Thank you in advance, guys.
Advertisement
Answer
The problem is happening because the dataHeader
variable is an array, so what it actually looks like is this:
var dataHeader = [
{ "data": "id" },
{ "data": "usuario" },
{ "data": "apellido1" },
{ "data": "apellido2" },
{ "data": "email" }
];
Side Note: I simplified your variable because it appears to contain both data
and mData
options:
{ data: "id", mData: "id" },
Whereas it only needs to contain data
options:
{ data: "id" },
mData
is the old name for data
– so these options are equivalent.
If you take this array and add it into your DataTable, you end up with the following structure for the columns
option:
"columns": [
[
{ "data": "id" },
{ "data": "usuario" },
{ "data": "apellido1" },
{ "data": "apellido2" },
{ "data": "email" }
],
"defaultContent": "<div class='text-center'>...</div>"
],
And this is not what you want – you have that extra array inside the columns
array. This is not valid for DataTables.
Solution:
You can work around this by taking that HTML string and adding it to the array provided by PHP:
var defaultContent = { defaultContent: "<div class='text-center'>...</div>" }
var dynamicColumns= <?=$fields?>;
dynamicColumns.push(defaultContent);
The push()
function adds the defaultContent
object to the end of the dynamicColumns
array.
Now you can use this new variable dynamicColumns
in your DataTable:
$('#tablaUsuarios').DataTable({
"columns": dynamicColumns
});