display.grid.insert()
Description
display.grid.insert() inserts one or more new records into a grid at a given zero-based index. The records that were at that index and after it are moved down; no records are removed.
To add records to the end of the grid use display.grid.push() or display.grid.addRecords(); to add them at the beginning use display.grid.unshift().
Syntax
display.gridName.insert(start, record1, record2, ...)Parameters
Start (Number) - The zero-based index at which to insert. If greater than the number of records in the grid, the records are added at the end. If negative, the insertion point is counted from the end of the grid, so
-1inserts before the last record.Record (Object) - A JavaScript object with properties representing the fields in the grid.
Additional records (Object, optional) - One or more additional record objects to insert after the first one.
Return Value
Nothing is returned.
Examples
Example 1: Insert a Record in the Middle of a Grid
Inserts a record at index 2, so it becomes the third record. Records 3 and 4 move down to indexes 3 and 4.
Prerequisite: a Rich Display File named display.json with a record format named screen that contains a grid whose record format name is mygrid, with the fields product and description bound to its columns.
pjs.defineDisplay("display.json"); // Object name defaults to "display"; display.json defines mygrid
display.mygrid.addRecords([
{ product: 1, description: "ITEM ONE" },
{ product: 2, description: "ITEM TWO" },
{ product: 3, description: "ITEM THREE" },
{ product: 4, description: "ITEM FOUR" }
]);
display.mygrid.insert(2, { product: 2.5, description: "TWO AND A HALF" });
console.log(display.mygrid.getRecords());
// The line above logs:
// [ { product: 1, description: 'ITEM ONE' },
// { product: 2, description: 'ITEM TWO' },
// { product: 2.5, description: 'TWO AND A HALF' },
// { product: 3, description: 'ITEM THREE' },
// { product: 4, description: 'ITEM FOUR' } ]Example 2: Insert a Record After the Row the User Selected
Uses display.grid.findIndex() to locate a record and inserts a new record directly after it. Two records are inserted in one call.
Prerequisite: a Rich Display File named display.json with a record format named screen that contains a grid whose record format name is mygrid, with the fields product and description bound to its columns.
pjs.defineDisplay("display.json"); // Object name defaults to "display"; display.json defines mygrid
display.mygrid.addRecords([
{ product: 1, description: "ITEM ONE" },
{ product: 2, description: "ITEM TWO" },
{ product: 3, description: "ITEM THREE" }
]);
// Find product 2 and insert two records after it
var index = display.mygrid.findIndex(record => record.product === 2);
if (index !== -1) {
display.mygrid.insert(index + 1,
{ product: 21, description: "ITEM TWO-A" },
{ product: 22, description: "ITEM TWO-B" });
}
console.log(display.mygrid.getRecordCount()); // 5