Combobox to trigger actions as you type

Hi community, I would like to filter a table on the fly by typing in a combo box. i.e. I want the things happen as soon as I input characters, and not wait till I press TAB or ENTER.

I have two difficulties:

  1. The combo does not seem to accept any value that is not in the list. I tried setInvalidAllowed(true) and setInvalidCommitted(true), but no joy.

  2. ValueChangeEvent seems to be triggered only when field loose focus. Is this the right behaviour? I tried setImmediate(true) and setBuffered(false), but no joy. I cannot seem to attach a Keypress Listener to the combo either.

I will appreciate any advise.

Here is the code I am using:

private ComboBox unitsFilter;
private JPAContainer<Expense> expenses;

/** code to initialize expenses here
  - removed for clarity
  ...
*/

EntityManager em = expenses.getEntityProvider().getEntityManager();
List qr = em.createQuery("SELECT DISTINCT c.unit FROM Expense c").getResultList();

unitsFilter.removeAllItems();
for (int i=0; i<qr1.size(); i++) {
unitsFilter.addItem(qr1.get(i).toString());
}

unitsFilter.setInputPrompt("Filter by Unit");
unitsFilter.setFilteringMode(FilteringMode.OFF);
unitsFilter.setBuffered(false);
unitsFilter.setTextInputAllowed(true);
unitsFilter.setInvalidAllowed(true);
unitsFilter.setInvalidCommitted(true);
unitsFilter.setReadOnly(false);
unitsFilter.setImmediate(true);

unitsFilter.addValueChangeListener(new ValueChangeListener() {
SimpleStringFilter filter = null;

    @Override
public void valueChange(ValueChangeEvent event) {
     if (filter != null) 
        expenses.removeContainerFilter(filter);

if (unitsFilter.getValue() != null) {
String seekStr = unitsFilter.getValue().toString();
            filter = new SimpleStringFilter("unit", seekStr,false,true);
            expenses.addContainerFilter(filter);
        }
    }
});

Hi Oscar,

"ValueChangeEvent seems to be triggered only when field loose focus. Is this the right behaviour? "

That’s the correct behaviour for ValueChangeListener. Anyway, you could use TextChangeListener in your case. If user should also be able to add new items to combobox, use setNewItemsAllowed() -method in ComboBox.

Hopefully this helps.

There’s no TextChangeListener for ComboBox (only for TextField) so this is not doable out of the box. What you could look into, is subclassing the ComboBox and overriding the changeVariables -method. This method is run when some event comes from the browser to the server. There you could check for the “filter” variable and do your filtering based on that.

Disclaimer: I haven’t tried this so not sure what issues may come up.