I cannot get editor populated with row data

I cannot get editor populated with row data

zipperzipper Posts: 35Questions: 9Answers: 0
edited March 2017 in Free community support

Server side I'm using Node.js + Express + EJS.

  • In the router file:
router.get('/product_tst3', function(req, res, next){
  var sql = 'SELECT product.id, product.name, product_catalog.name AS "catalogue",\
    product.description, product.create_time, product_status.name AS "status"\
    FROM product\
    INNER JOIN product_catalog ON product.catalog_id = product_catalog.id\
    INNER JOIN product_status ON product.status_id = product_status.id\
    WHERE 1=1';
  var tb_titles = [
    "ID",
    "Product Name",
    "Catalogue",
    "Description",
    "Create Time",
    "Status"    
  ];
  
  //db operations
  conn.query(sql, function(err, r, f){
    if (!err){
      var ff = JSON.parse(JSON.stringify(f));
      var rr = JSON.parse(JSON.stringify(r));
      var tb_field_names = [];
      //get field names to JS array
      for (var i =0; i<ff.length; i++){
        tb_field_names.push(ff[i].name);          
      }
      //get data to JS array
      var tb_data = [];
      for (var i = 0; i< rr.length; i++){
          var row = [];
          Object.keys(rr[i]).map(function(_){
            row.push(rr[i][_]);
          });
          tb_data.push(row);
      }
      res.jsonp(new Object({tb_titles, tb_field_names, tb_data}));
    }else{
      console.log('Error while performing Query.');
    }
  });
});
  • The json response:
{ tb_titles:
   [ 'ID',
     'Product Name',
     'Catalogue',
     'Description',
     'Create Time',
     'Status' ],
  tb_field_names:
   [ 'id',
     'name',
     'catalogue',
     'description',
     'create_time',
     'status' ],
  tb_data:
   [ [ 1,
       'as_o_agent',
       'nibiru',
       'Act as oritionation agent',
       '2017-03-02T12:20:45.000Z',
       'active' ],
     [ 2,
       'as_t_agent',
       'nibiru',
       'Act as termination agent',
       '2017-03-05T03:51:49.000Z',
       'active' ] ] }
  • mgmt2.ejs is attached, but I have to renamed as .html because otherwise the server rejects it.

Please check what's wrong? By printing out I can see that the target_row already populated, but the data does not go to the editor by the edit method.

This question has an accepted answers - jump to answer

Answers

  • zipperzipper Posts: 35Questions: 9Answers: 0

    I finally found some possible work around. Since my data came as arrays of values (which each array is a record without field names) instead of an array of key:value pair objects (which each object is a record with field names), they data table was initialized by the arrays of values without a field name for each column.

    So I tried to add the field names to the column.name. But this does NOT work.

    Then I put the editor.idSrc to 0 and put the name of editor.field[i] to i (0 <= i < column_count). Now the data is loaded to the editor. But I will have to work with the index numbers not names now.

    The question is: What is the column property/option used to address the column, since column.name is not used; and can I control it? Naturally the JSON dataset comes with an array of key: value objects, but when the records becomes hundreads, it there is no reason to duplicate the field name for every field.

  • allanallan Posts: 63,350Questions: 1Answers: 10,443 Site admin

    I would need to be able to see your client-side Javascript for how you've configured DataTables and Editor.

    Allan

  • zipperzipper Posts: 35Questions: 9Answers: 0
    edited March 2017

    Here is it:

      $(document).ready(function() {
        $.ajax({
          type: "get",
          async: false,
          url: "/product_tst3",
          dataType: "jsonp",
          jsonp: "callback",
          success: function(json) {
            draw_table(json);
          },
          error: function() {
            alert('failed!');
          }
        });
      });
      
      function draw_table(tb_contents) {
        var t_head_foot = "<tr>";
        for (var i = 0; i < tb_contents.tb_titles.length; i++) {
          t_head_foot += "<th>" + tb_contents.tb_titles[i] + "</th>";
        }
        
        t_head_foot += '<th><b><a class="editor_create fa fa-pencil fa fa-plus-square"> New<a></b></th></tr>';
        $("#thead1").append(t_head_foot);
      
        var table = $('#table1').DataTable({
          data: tb_contents.tb_data,
          autoWidth: false,
          columnDefs: [{
            'targets': -1,
            'width': '6%',
            'orderable': false,
            'defaultContent': '<a class="editor_edit fa fa-pencil"></a> <a class="fa fa-trash editor_delete"></a>'
          }]
        });
        table.draw();
        draw_editor(table, tb_contents);
      }
      
      function draw_editor(table, tb_contents) {
        var editor = new $.fn.dataTable.Editor({
          'table': '#table1',
          'idSrc': 0
        });
        
        var r_count = tb_contents.tb_titles.length;
        for (var i = r_count; i > 0;) {
          var predecessor = (i == r_count) ? null : tb_contents.tb_titles[i];
          var field_type = 'text';
          var field_option = [];
          editor.add({
            label: tb_contents.tb_titles[--i],
            name: i,
            type: field_type,
            options: field_option
          }, predecessor);
        }
      
        $('#tbody1').on('click', 'a.editor_edit', function(e) {
          e.preventDefault();
          editor.edit($(this).closest('tr'), true, {
            title: 'Edit Record',
            buttons: 'Submit'
          });
        });
      }
    
  • allanallan Posts: 63,350Questions: 1Answers: 10,443 Site admin

    I must confess, that does look like it should work!

    Can you give me a link to the page so I can check it out please?

    The one thing I might suggest adding is rowId to your DataTable initialisation and setting it to be 0. But really that shouldn't be required, so I don't believe that will actually fix it.

    Allan

  • zipperzipper Posts: 35Questions: 9Answers: 0

    Hi Allan, to migrate to the public address I need a Node.js server to response the jsonq requests and will try to set up on AWS by tomorrow.

    As I tested a bit more, setting the idSrc and field.name into indexes only works for editor.edit(); does not work for editor.create(). when using indexes the editor.create() shows no fields. I tried another combination of idSrc=index, field.name=field_name; the result is the editor.edit failed to populate the form with data.

    All above are for the situation specified editor.table to '#table1' the jQuery selector. when setting editor.table to datatable, none above works(e.g. editor.edit(datatable.row(0), true, {'title':'edit','buttons':'submit'}) -- this shows no fields in the form).

    It seems you are implicitly enforcing the policy to only accept key:value pairs for each data field; and no easy way to specify the field_names for an array of pure values.

  • allanallan Posts: 63,350Questions: 1Answers: 10,443 Site admin

    Thanks for looking into setting up a test case - I think that would be really useful in this case.

    idSrc should basically be irrelevant for the create action, since the id isn't known until it is submitted to the server.

    Thanks,
    Allan

  • zipperzipper Posts: 35Questions: 9Answers: 0
    edited March 2017

    Hi, pelase see http://54.199.175.35/ where I put the indexes version and the editor.edit() works fine but the editor.create() prompts form with fields missing. I put the field name version at http://54.199.175.35/2/ , and you can see the editor.create() is fine but the editor.edit() got the error of "Unable to find row identifier For more information, please refer to https://datatables.net/tn/14"

  • zipperzipper Posts: 35Questions: 9Answers: 0

    Frustrated after another day of trying. The datatables does not really have a data model, I cannot easily manipulate the data in the table like the name indicated, but still have to work on the views -- the views are re beautiful and consistent, however.

  • allanallan Posts: 63,350Questions: 1Answers: 10,443 Site admin
    Answer ✓

    Thanks for the test case! That lead me straight to the issue. This was indeed a bug in Editor I'm sorry to say, whereby fields with an integer for fields.name would not correctly be added to the form.

    I'm just about to PM you an updated trial file with the fix in it.

    Regards,
    Allan

This discussion has been closed.