Best way to conditionally expand a row from ajax into multiple rows

Best way to conditionally expand a row from ajax into multiple rows

joed67joed67 Posts: 14Questions: 6Answers: 1

I am rendering a DataTable from an ajax source There are certain conditions, depending on the data, where I need to display a row of data from the source as multiple rows in the table.

Simple example:

[ 
  { Title: "ABC",  Multiple: 0 },
  { Title: "DEF",  Multiple: 3 },
  { Title: "GHI",  Multiple: 0 }
]

This should render as:

 ABC
 DEF - 1
 DEF - 2
 DEF - 3
 GHI

I've been looking through the docs and examples, and have not seen one that shows this.

One way I tried was to call row.add from within the render() for a cell, but this isn't working - it's giving me an "undefined" when I try to get a reference to the DataTable, either using "this.row.add" or "$('mytable').row.add". I'm suspecting this isn't going to work anyway... should it?

Another way would be to use the jquery $.ajax() call to get the data, then manipulate it to add rows to it, then use that as the source for the DataTable.

I don't see any way in the DataTable to have a callback after the ajax call has been made, to modify the data prior to DataTable using it to render the table (is there and I missed it?).

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954
    Answer ✓

    Using columns.render to add rows is probably not a good option.

    One option might be to use Child detail rows.

    Another option is to arrange the rows as needed in your server script. Or you can use ajax.dataSrc to loop through all the rows to create each row.

    One more option would be to use initComplete to loop all the rows using rows().every(). In the loop build the rows you want to add into a variable. After the loop use rows.add(), note the rows with an s, to add all the rows to the table.

    Kevin

  • joed67joed67 Posts: 14Questions: 6Answers: 1

    Thanks - I ended up going with the dataSrc option and looped through the array of objects, and when I encounter one that needs to be "expanded", I use objArray.push to add a new row to the array.

    They all go at the end, so I'm either going to have to sort the DataTable or sort the array in dataSrc.

Sign In or Register to comment.