I'm working with this Datatables Demo to display child rows. And i'm using php to return an array or data. I have it functioning pretty well, but have a few issues.
Here is an image of what I have currently.
As you see in the picture, there are two parent rows with the same question, and the child rows with different answers.
1. I need a way to limit one parent row for each distinct question.
2. I also need a way to loop through and display multiple child rows in the same child table.
3. Another option is how to assign data to the parent rows and another set of data to the child rows.
I know I should do that in my query, but the question column is single to many results, in two separate tables. The only way to do it with queries would be to return one result for the questions and then make another ajax call to fill the child rows. I was assuming this would be easier.
CODE:
Table:
<table id="car" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="details-control" style="max-width: 80px;">Expand</th>
<th>Question</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th></th>
<th>Question</th>
</tr>
</tfoot>
</table>
Script:
function format(d) {
//d is the original data object for the row
var tbl = '<table cellpadding="5" cellspacing="0" border="0" style="margin-left:110px; width:100%; font-size:12px;">' +
'<tr>' +
'<th style="width:60%; color:3383bb;">Answer Choices</th>' +
'<th style="width:15%; color:3383bb;"># of Answers</th>' +
'<th style="width:15%; color:3383bb;">Percentage</th>' +
'</tr>' + '<tr>' +
'<td>' + d.Answer + '</td>' +
'<td>' + d.NumberOfAnswers + '</td>' +
'<td>' + d.Percent + '</td>' +
'</tr>' + '</table>';
return tbl;
}
var table2 = $('#car').DataTable({
"ajax": "/rmsicorp/clientsite/reset/survey/surveyajax.php",
"scrollY": "400px",
"paging": false,
"bAutoWidth": true,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "Question" },
],
}).columns.adjust().draw();
Query result:
The question column is just repeating for each answer. The rest of the columns are distinct.
It's a common problem, you can solve it on query side or language side. With this scenario i prefer the language side. What you can try to do:
You will have to edit you format function to do that, i can suggest you to split it in two parts, one with Question header and one with the data of answers, and then you control: render or not the header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With