Pages

Wednesday, May 4, 2016

The better way to detect when multiple records are selected

There are some instances when you want to know when multiple records are marked on a form. An example would be if you wanted a button to be enabled only when more than 1 record was selected.

You can make a button disabled when more than 1 record is selected, but not the other way around.

As far as I can tell, the way the grid functions is it stores an Array object of the cursor positions of the marked records. Below are the two ways I've seen to solve this problem. Method #2 is more common, but Method #1 seems more efficient to me as you're only interacting with the Array and not traversing the datasource's table buffer.


    FormDataSource  fds = salesTable.dataSource();

    // Method 1
    // The grid stores an array of marked records, and this
    // will return only the index, which is all that is needed
    if (fds.recordsMarked().lastIndex() > 1)
        info("Multiple records selected");
    else
        info("1 or 0 records selected");
    
    // Method 2
    // This will traverse the datasources buffer
    fds.getFirst(true);    
    if (fds.getNext())
        info("Multiple records selected");
    else
        info("1 or 0 records selected");

    // Enabling/Disabling button in one line
    myButton.enabled(SalesTable_ds.recordsMarked().lastIndex() > 1);

And how to enable/disable a button in one line:

    // Enabling/Disabling button in one line
    myButton.enabled(SalesTable_ds.recordsMarked().lastIndex() > 1);