Zoners
Zoners

Reputation: 123

DataTables.net how use multiple data source?

I use the composant "http://datatables.net/". With my datatables, I use ajax request to get the data from the serverSide. But I have an other datasource for one cell ("List Role") which use another ajax source.

How to use this sources for the cell("List Role") and how display a "<selec...><option..>" for the cell which is "ListRole"?

My code example:

<table id="gridrole" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Nom</th>
            <th>Login</th>
            <th>Email</th>
            <th>Role Current</th>
            <th>List Role</th>

        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Nom</th>
            <th>Login</th>
            <th>Email</th>
            <th>Role Current</th>
            <th>List Role</th>

        </tr>
    </tfoot>
</table>
$('#gridrole').dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "/Role/ReadRole/",
            "dataType": "json"
        },

        columns: [
            { "data": "UserName" },
            { "data": "Login" },
            { "data": "Email" },
            { "data": "RoleName" },
            {
                "data": "ListRole"
            }

        ],

    });

Update

Example list role:

[{"Id":"1","Name":"Admin"},{"Id":"2","Name":"Test"}]

Upvotes: 3

Views: 4320

Answers (1)

davidkonrad
davidkonrad

Reputation: 85558

I assume other aspects of your dataTables initialisation are working well and the items of the first datasource looks something like

{
  "UserName": "test",
  "Login": "qwerty",
  "Email": "[email protected]",
  "RoleName": "Test",
  "ListRole": 2
 }

etc, and the listrole data source looks like

[{"Id":"1","Name":"Admin"},{"Id":"2","Name":"Test"}]

etc. Then, I will suggest you read the listrole datasource only once, and create a jQuery object holding a <select><option ..</select> instance with the listrole Id's and Name's :

var $select = $('<select></select>');

$.getJSON('listrole.json', function(json) {
  for (var i=0;i<json.length;i++) {
     $select.append('<option value="'+json[i].Id+'">'+json[i].Name+'</option>')
  }
});

and then in columns return a cloned $select (or actually its HTML) where the <option> that corresponds to the value of ListRole in the first datasource are selected :

columns: [
   ...
   { data: "ListRole",
     render: function(data, type, row, meta) {
        var $clone = $select.clone();
        $clone.find('option[value="'+data+'"]').attr('selected', 'selected');
        return $clone.wrap('<div></div>').parent().html();
      }
   }
]

have made a demo of the above -> http://plnkr.co/edit/JW15Iblkz6rVSod3YWXw?p=preview

Upvotes: 2

Related Questions