Sanjaya Liyanage Sanjaya Liyanage - 6 months ago 34
Java Question

How to define a max limit of selected items in TwinColSelect

I want to define a maximum number of selected items in TwinColSelect in my vaadin ui. How can I achieve it. I want to allow the user to select only 4 planets out of available 8.My current code is

TwinColSelect table = new TwinColSelect();
table.setImmediate(true);

String planets[] = {"Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune"};
for (int pl=0; pl<planets.length; pl++)
table.addItem(planets[pl]);
table.addListener(new Property.ValueChangeListener() {

public void valueChange(ValueChangeEvent event) {
/*String [] arr=(String [] )event.getProperty().getValue();
if(arr.length>=4){
return;
}*/
}
});

Answer

You can implement something like this by changing select's value:

//Constant declared somewhere in the class
private static final int SELECTED_ITEMS_LIMIT = 4;

...

table.addListener(new Property.ValueChangeListener() {

    @Override
    public void valueChange(ValueChangeEvent event) {
        Collection selectedItems = (Collection) event.getProperty().getValue();
        if(selectedItems.size()>SELECTED_ITEMS_LIMIT) { //Set no more than SELECTED_ITEMS_LIMIT values
            Set<String> noMoreThanLimitItems = new HashSet<String>(selectedItems.size());
            int counter = 0;
            for(Object item : selectedItems) {
                if(counter>=SELECTED_ITEMS_LIMIT) {
                    break;
                }
                noMoreThanLimitItems.add((String) item);
                counter++;
            }
            event.getProperty().setValue(noMoreThanLimitItems);
        }  
    }
});

Drawbacks:

  • Code is server-side. So, more than four planets might appear as selected between browser requests.
  • Call to Property.setValue fires ValueChangeEvent. So, handling code will be executed twice every time when user tries to select more than four planets