Version 1
Version 1

CRUD

DataViewsJS supports CRUD (create, read, update, destroy) data operations to sync data dynamically with the server. CRUD can be enabled by implementing the callback methods to trigger the dataView about the operations.

This callback methods only has one parameter as a transport protocol which can be used for actual server interaction in the callback. If callback succeeds, call params.success(); , else call params.failed().

List of transports and their respective usages are as follows:

Transport Usage
create Used to create items in the data.
This callback is called after adding new items in the grid. Implement by including autoAddRow and by calling dataView.data.insertDataItems.
loadRange Used to update data.
This callback is called in case:
1. New data is required in paging mode.
2. Not in paging mode, scrolled near the bottom and control option loadOnDemand is true.
update Used to update item in the data.
This callback is called after updating items in the grid. It includes edit and calls dataView.data.updateDataItem.
delete Used to delete item in the data.
This callback is called after adding delete item in the grid. It includes delete row in action column and calls dataView.data.removeDataItems.

Steps to implement CRUD feature are as follows:

Sample Code

  1. Add a reference to the following files:
<script src="[Your Script Path]/gc.dataviews.common.min.js" type="text/javascript"></script>
<script src="[Your Script Path]/gc.dataviews.core.min.js" type="text/javascript"></script>
<script src="[Your Script Path]/pageui.js" type="text/javascript"></script>
  1. Add the column definition along with action column presenter definition.
  2. Add functions for CRUD definition.
var dataView;
var currentPageDataSource;
var itemsTotalCount;
var baseUrl = ''.concat(process.env.SITE_ROOT, '/remotedata/api/records');
var dataSource = {
  loadRange: function(params) {
    $.ajax({
      //pageSize and startPageIndex only works when paging component is     referenced, if control
      //do find the paging component, pageSize and pageIndex will be     undefined.
      url: getRecords(params.pageIndex == undefined ? undefined : params.pageSize * params.pageIndex, params.pageSize),
      crossDomain: true,
      success: function(result) {
        currentPageDataSource = result.m_Item2;
        itemsTotalCount = result.m_Item1;
        params.success(currentPageDataSource, itemsTotalCount);
      },
      error: function(xhr, status) {
        params.failed();
        if (status !== 'abort') {
          alert('Failed to load data from remote web site.');
        }
      },
    });
  },
  create: function(params) {
    var dataItem = _.clone(params.dataItem);
    $.ajax({
      url: baseUrl,
      type: 'POST',
      data: JSON.stringify(dataItem),
      success: function(data) {
        dataItem['Transaction_Id'] = data['Transaction_Id'];
        params.success(dataItem);
      },
      error: function(xhr, status) {
        params.failed();
        alert('add item on server side failed');
      },
    });
  },
  delete: function(params) {
    $.ajax({
      url: baseUrl + '/' + params.dataItem['Transaction_Id'],
      type: 'DELETE',
      success: function(data) {
        params.success();
      },
      error: function(xhr, status) {
        params.failed();
        alert('delete item on server side failed');
      },
    });
  },
  update: function(params) {
    $.ajax({
      url: baseUrl + '/' + params.dataItem['Transaction_Id'],
      type: 'PUT',
      data: JSON.stringify(params.dataItem),
      success: function(data) {
        params.success();
      },
      error: function(xhr, status) {
        params.failed();
        alert('update item on server side failed.');
      },
    });
  },
};
  1. Initialize the code by calling the grid ID from the DIV tag.
$(document).ready(function() {
  dataView = new GC.DataViews.DataView(
    document.getElementById('grid1'),
    dataSource,
    columns,
    new GC.DataViews.GridLayout({
      colWidth: 80,
      showColHeader: false,
      showRowHeader: false,
      rowHeight: 36,
      pageSize: 10,
      allowEditing: true,
      editMode: 'popup',
      autoAddRowPosition: 'top',
      headerRow: {
        visible: true,
        height: 40,
        separateColumn: false,
        renderer: '<button id="btnAddNew"><span class="add-icon"></    span><span> Add new record</span></button>',
      },
    })
  );

  dataView.editing.addHandler(function(sender, args) {
    if ((args.status === 'endEditing' && args.isNewRow) || args.status === 'cancelEditing') {
      if (dataView.options.allowAutoAddRow) {
        dataView.options.allowAutoAddRow = false;
        dataView.invalidate();
      }
    }
  });

  $('#btnAddNew').on('click', function() {
    var addNewRecordID = dataView.uid + '-autorow';
    dataView.startEditing(addNewRecordID);
  });

  var pageController = dataView.data.pageController;
  var pager = new PageUI('#page-nav', pageController.getStatus());

  pager.goToFirstEvent.addHandler(function() {
    pageController.first();
  });

  pager.goToPreviousEvent.addHandler(function() {
    pageController.previous();
  });

  pager.goToNextEvent.addHandler(function() {
    pageController.next();
  });

  pager.goToLastEvent.addHandler(function() {
    pageController.last();
  });

  pager.goToPageEvent.addHandler(function(e) {
    pageController.goToPage(e.newPage);
  });

  pageController.statusChanged.addHandler(function(sender, newStatus) {
    pager.updateStatus(newStatus);
  });
});

//action column handler
function deleteItem(args) {
  var rowId = dataView.getRowId(args.hitInfo);
  var dataItem = dataView.getItem(rowId);
  if (dataItem && dataItem.item) {
    var sourceIndex = dataItem.item.sourceIndex;
    if (sourceIndex >= 0) {
      dataView.data.removeDataItems(sourceIndex);
    }
  }
}

function getRecords(start, count) {
  var result = [];
  if (start != undefined) {
    result.push('start=' + start);
  }
  if (count != undefined) {
    result.push('count=' + count);
  }

  if (result.length > 0) {
    return baseUrl + '?' + result.join('&');
  }
  return baseUrl;
}

See also