Back to the index of articles and examples

Delete Rows By

It has to be remembered that the main repository for data in the DataTable is the RecordSet, not the screen. If we put interactive controls on the screen such as checkboxes, it is important that their state is stored in the RecordSet immediately as any information stored in the screen is volatile. Any screen refresh, such as a column sort or when moving to another page in a paged DataTable, will wipe out whatever was stored on the screen, not so with the RecordSet.

The checkbox in the header is added via the label property of the column defs, while those on each of the rows are provided by the 'checkbox' formatter. There is no "Select" field in the incoming data, a call to getData('Select') will return undefined which the checkbox formatter considers false and the checkbox will be unchecked.

When clicking each checkbox, the following code updates the underlying record:

The second half of the above code makes sure the 'Select All' checkbox always reflects the state of the buttons. If all of them are checked, the Select All checkbox will be selected. This second half is surrounded by a condition asking whether the checkbox clicked is in the Select column. While the first part of the code is completely generic and it would work for any checkbox on any of the several columns, after all, any checkbox change has to be recorded on its Record, the second only applies to the checkboxes on the Select

The forAllRecords method, a handy addition to DataTable, is defined like this:

If will execute the function received as the first argument for every Record in the RecordSet, providing it with a reference to each Record and the index. The function can return false to stop looping.

The following code listens to a click on the 'Select All' button:

We read the value of the actual target of the click on the header cell (that is, the checkbox) and we copy that value into every record on the RecordSet. This does not refresh the UI at once, we need to call method render when all values have been set.

We listen for the Delete Selected button to be clicked:

The listener calls method deleteRowsBy that I added to the DataTable, which receives a function that should return true or false depending on whether you want the record deleted or not. The function receives an object (data) which contains the values for each record as a simple object with the field names as its keys. data is not a Record instance but a plain object.

deleteRowsBy

The deleteRowsBy method uses DataTable's own deleteRows method to delete records in batches. It tries to collect as many contiguous records in each batch. It does not fire any events by itself, but deleteRows will fire rowsDeleteEvent. A single operation may fire several of these events, one for each batch.