Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dataTables add multiple collapsible rows using the fnOpen() API function

I am using the jQuery dataTables plugin to build advanced tables for our application. One of the requirements is to have "collapsible" rows (not groups!): e.g. rows represent campaigns, and they might have child campaigns. The structure of child rows is (in basic case) the same as in the parent table - same cells, same data types.

But, the child rows shouldn't affect the parent table itself: I mean, the number of rows per page should remain the same, child rows shouldn't be sorted separately from the parent row, they should always remain binded. Therefore I can't use fnAddData() API func for that.

And the other tricky requirement is the possibility to have multi-level collapsible rows (e. g. child campaigns for child campaigns, etc.)

I was using the fnOpen() API function for that, it allows to "open" any row, appends a child block to it, and you can generally insert there whatever you want. It was working just fine in dataTables 1.8.2, i used code like this to generate child rows:

$(childRowData).each(function(){
    row = $(oTable.fnOpen(row.get(0), $(this), "child_row"));
    $(row).addClass('child_row');
});

Generally, it "opened" the current row (defined above), inserted data in the child row, then in the cycle "opened" the child row, added a child to it, etc.

But as of dataTables 1.9.0 looks like it is allowed only to "open" the parent rows, and only do it once.

Of course, I can create a sub-table, apply $.dataTable() to it and insert it to the child row, but it seems like a somewhat lame and expensive solution, especially when we might have 3-4 levels of depth.

Is there any other way to implement collapsible rows in dataTables?

like image 455
Alexander Gilmanov Avatar asked Jun 07 '12 10:06

Alexander Gilmanov


1 Answers

Datatables has been updated somehow and it's very straight forward now for adding children rows to parent rows: http://datatables.net/reference/api/row().child()

One of the thing not really obvious, is in case you want to use the same layouts for your children rows like for the parent rows, you need to use the jquery selector, for passing a node instead of a string (written in the documentation but I missed it the first time).

Doint that is correct:

.child(
    $(
        '<tr>'+
            '<td>'+rowIdx+'.1</td>'+
            '<td>'+rowIdx+'.2</td>'+
            '<td>'+rowIdx+'.3</td>'+
            '<td>'+rowIdx+'.4</td>'
        '</tr>'
    )
)

But doing that is wrong: (it will insert your "tr" into a "td" with a colspan of the size of your table and it will obviously break the columns alignment)

.child(
    '<tr>'+
        '<td>'+rowIdx+'.1</td>'+
        '<td>'+rowIdx+'.2</td>'+
        '<td>'+rowIdx+'.3</td>'+
        '<td>'+rowIdx+'.4</td>'
    '</tr>'
)
like image 70
Christophe Vidal Avatar answered Oct 13 '22 01:10

Christophe Vidal