Search code examples
slickgrid

Validation on onCellChange with Slickgrid


I have just started to use slickgrid (++ to the author btw) - running into a few small issues - I want to dynamically update some fields using the in-context editing. Once editing is done I wish to send this to the server which also should validate what was sent. If there is an error I would like to handle the error in a similar way to how the validatr event works? e.g. highlight the cell and not let the user to move away until it is valid, however I do not see how I can do so? any advice on this would be much appreciated!

Code so far...

grid.onCellChange.subscribe(function(e, args) {
    var item = args.item;
    var column = args.cell;       
    var row = args.row;
    var value = data[args.row][grid.getColumns()[args.cell].field];
    var id = args.item.id;
    var field = grid.getColumns()[args.cell].field;
    var dataString = "id="+id+"&field="+field+"&value="+value;
    var status = false;
    $.ajax({
        type: "POST",
        url: "/en/<?php echo $this->controller; ?>/updateattribute/&callback=?'",
        data: dataString,
        dataType: "json",
        success: function(a) {  
            console.log(data);              
            if(a.status == true) {                  
                status = true;
            } else {
                status = false;             
            }       
            return false; 
        }
    });    
    if(!status) {
        return false;
    }             
    grid.invalidateRow(data.length);
    data.push(item);
    grid.updateRowCount();
    grid.render();
});

Many thanks


Solution

  • Ajax requests are, by default, asynchronous, which means that

    if(!status) {
        return false;
    }             
    grid.invalidateRow(data.length);
    data.push(item);
    grid.updateRowCount();
    grid.render();
    

    will probably be executed before the success callback. A couple different solutions:

    • Make the ajax request synchronous (not recommended):

      $.ajax({ ... async: false, ...})
      
    • Put all of the code that follows the ajax request in the success or complete callback. Something like this (not tested):

      grid.onCellChange.subscribe(function(e, args) {
          // snip...
      
          $.ajax({
              type: "POST",
              url: "/en/<?php echo $this->controller; ?>/updateattribute/&callback=?'",
              data: dataString,
              dataType: "json",
              success: function(a) {  
                  console.log(data);              
                  if(a.status) {                  
                      grid.invalidateRow(data.length);
                      data.push(item);
                      grid.updateRowCount();
                      grid.render();
                  }
              }
          });
      });
      

    jQuery's deferred object can also provide a clean way to write this.