Select box value not one of values in list

We have a few select boxes (NativeSelect, Combobox, ListSelect) that based on other changes, can cause the current value to no longer be one of the items added as a possible choice.

So, let’s say my bean/object has a value “1” but the list only shows “10” and “20”. Naturally, the select looks correct in that no item is shown to be selected, yet it clearly has a value. When the Form is committed, if the user does not change the select box, the bad “1” value remains. Is there a way to have it become the null value on save/commit of the Form?

Just trying to see if there’s a common scheme used to know if the value a select box has no longer matches any of the valid choices if the user doesn’t manipulate the select box directly?

Thanks for any ideas…

Seems like the Form.isValid() check would catch this somehow, saying the value is invalid since it’s not in the list of selectable values.

Is there a pre-built validator that does this sort of check that I can use, or would I have to build my own?

Could anybody at Vaadin maybe comment on whether this is a reasonable validator to ensure that a select box’s value is one of the elements in the list?

public class SelectValidator extends AbstractValidator {

	AbstractSelect select;
	String defaultErrorMessage;

    public SelectValidator(AbstractSelect select) {
    	super("The value ({0}) does not match any of the selection choices.");
    	this.defaultErrorMessage = super.getErrorMessage();
        this.select = select;
    }
    
    
    @Override
    public boolean isValid(Object value) {
    	setErrorMessage(defaultErrorMessage);
    	
    	if ( value == null ) {
    		return select.isNullSelectionAllowed();
    	}

		if ( value instanceof java.util.Set ) {
			java.util.Set<?> set = (java.util.Set<?>)value;
			for( Object setValue : set ) {
		    	return isValid(setValue);
			}
		}
		else {
	    	for( Object itemId : select.getItemIds() ) {
        		if ( value.equals(itemId) ) {
        			return true;
        		}
	    	}
		}
    	
		return false;
    }
}

Hi!

Seems a reasonable validator to me. But why does isValid method checks only first element of Set, if value is a Set? That part looks like a bug if all objects in the set should be in the datasource.

Thanks for the good eyes. Yes, that loop shouldn’t return (and thus only do the first).

    public boolean isValid(Object value) {
    	setErrorMessage(defaultErrorMessage);
    	
    	if ( value == null ) {
    		return select.isNullSelectionAllowed();
    	}

    	// Special logic for a multi-select
		if ( value instanceof java.util.Set ) {
			java.util.Set<?> set = (java.util.Set<?>)value;
			for( Object setValue : set ) {
		    	if ( ! isValid(setValue) ) {
		    		return false;
		    	}
			}
			return true;
		}
		
    	for( Object itemId : select.getItemIds() ) {
    		if ( value.equals(itemId) ) {
    			return true;
    		}
    	}
    	
		return false;
    }