GWT CellTable programmatically select CheckBoxCell

Noya picture Noya · May 30, 2011 · Viewed 19.2k times · Source

I've got a cellTable with a CheckBoxCell column. What I'm trying to do is to have a set of buttons outside the celltable which let the user to automatically check/uncheck a different set of elements (for example check all / uncheck all, but I'd like to have more complex rules).

What I don't understand is how to access the element (I suppose via row/col values ???) and get/set the value.

Can anyone help me to figure out how to resolve it?

Answer

Thomas Broyer picture Thomas Broyer · May 30, 2011

Assuming what you want is to bind the checkbox to "selection" and easily select a bunch of items programmatically (subtlety: select items, which will result in checkbox being checked, rather than checking boxes), you'll use a MultiSelectionModel.

You'll find sample code in http://gwt.google.com/samples/Showcase/Showcase.html#!CwCellTable, that is:

final MultiSelectionModel<ContactInfo> selectionModel = new MultiSelectionModel<ContactInfo>(
    ContactDatabase.ContactInfo.KEY_PROVIDER);
cellTable.setSelectionModel(selectionModel,
    DefaultSelectionEventManager.<ContactInfo> createCheckboxManager());
…
Column<ContactInfo, Boolean> checkColumn = new Column<ContactInfo, Boolean>(
    new CheckboxCell(true, false)) {
  @Override
  public Boolean getValue(ContactInfo object) {
    // Get the value from the selection model.
    return selectionModel.isSelected(object);
  }
};
cellTable.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
cellTable.setColumnWidth(checkColumn, 40, Unit.PX);

Then, to select an item (and have its checkbox checked automatically), you'll simply do:

selectionModel.setSelected(item, true);

and you can similarly get the set of all selected items with selectionModel.getSelectedSet().