Adding a new row using POJO or JSON not working

Adding a new row using POJO or JSON not working

wxkevinwxkevin Posts: 11Questions: 0Answers: 0
edited February 2012 in DataTables 1.8
I am trying to add a single row (later a bunch of rows) to my DataTable using either a POJO or a JSON representation of the POJO. I've read every example (i think!) on the internet and still don't understand why it's not working.

User is a POJO with say 8 fields. I only display 3 of the fields from the POJO in my DataTable. Here is the table definition:

[code]
var userTable = ${'#userTable').dataTable({
"bAutoWidth": false,
"iLength": "10",
"aoColumns": [
{ "sWidth": "200px:, "sClass": "uid", "mDataProp": "uid" },
{ "sWidth": "200px:, "sClass": "firstName", "mDataProp": "firstName" },
{ "sWidth": "200px:, "sClass": "lastName", "mDataProp": "lastName" }
],
"sDom": 'T<"clear">lfrtip',

// more config

});
[/code]

This is the code I use to call the add data function:

[code]
userTable.fnAddData(userInstance);
[/code]

userInstance is an instance of the User POJO and has members uid, firstName, lastName, and 5 other fields. There are also gets and sets for all fields.
This doesn't work. I get the "DataTables warning (table id = 'userTable'): Requested unknown parameter 'uid' from the data source for row 7" alert.

I tried the same thing but instead I used a json representation of the User POJO:

[code]
var json = '{ "uid": "user123", "firstName": "User", "lastName": "Theuser" }';
userTable.fnAddData(json);
[/code]

I receive the same error with the JSON object.

I can get it to work if I create an array of just the 3 shown values (uid, firstName, lastName) and send that into fnAddData but I don't want to do this because when I get to the point of adding multiple rows, they may be in the thousands so I would like to send in an array of POJOs or its JSON representation.

Does the number of fields in the object have to exactly match the number of columns? I would hope not but if that is the case then I can adjust.

Replies

  • allanallan Posts: 61,824Questions: 1Answers: 10,131 Site admin
    edited February 2012
    [code]
    var json = '{ "uid": "user123", "firstName": "User", "lastName": "Theuser" }';
    userTable.fnAddData(json);
    [/code]

    but json isn't a JSON object here, its a string. To be a JSON object yo would need to use:

    [code]
    var json = { "uid": "user123", "firstName": "User", "lastName": "Theuser" };
    userTable.fnAddData(json);
    [/code]

    So it looks like you might just need to evaluate your string to a JSON object.

    > Does the number of fields in the object have to exactly match the number of columns? I would hope not but if that is the case then I can adjust.

    No it doesn't - that's the whole reason for using objects as data sources :-)

    Allan
  • wxkevinwxkevin Posts: 11Questions: 0Answers: 0
    edited February 2012
    Holy stupid-ness Batman!

    Thanks Allan! It worked.
This discussion has been closed.