Hi, I’m using Vaadin 10.0.12 for a project, and I’d like to customize how a ComboBox filters the items inside of it.
For example, if I have the following:
ComboBox<String> combo = new ComboBox<>();
combo.setItems("Colombia", "México", "Venezuela");
If the user types “méx” or “mex”, the combo should display the “México” item. I know there’s already a way to do this in Vaadin 13, but I don’t seem to find how it’s done in Vaadin 10.
Thanks in advance.
PS: I’m using V10 since it is the latest LTS version.
Unfortunately there’s no API for changing the filtering logic in V10.
The next LTS release V14 is going to be released in June, so I’d suggest to wait for a couple of months and update to the new LTS version of Vaadin if you can.
Or if it’s acceptable for you to use a non-LTS version for two months, you could update to V13 now and then lock the version to V14 LTS in June.
As a hacky workaround, you could override the client-side private _filterItems function, but this is not recommended, as we don’t support this and won’t guarantee that it will work in the future.
Okay, I think I’ll wait for the next LTS to be released. In the mean time, I’ll use the “hacky” workaround, and then migrate to the official way. Thanks for your support
Just for the record, I didn’t override the client side _filterItems function. Instead, I extended the ComboBox<T> class and used the addFilterChangeListener(e -> {}) function. This allowed me to remove accents from the String typed by the user, and set the new filter using setFilter("unaccented string").
FilterComboBox.java
public class FilterComboBox<T> extends ComboBox<T> {
{
addFilterChangeListener(e -> {
setFilter(Controller.normalizeString(e.getFilter()));
});
}
}
Controller.java
public class Controller {
public static String normalizeString(String s) {
return Normalizer.normalize(s.toLowerCase(), Form.NFD).replaceAll("[^\\p{ASCII}]
", "");
}
}
The only difference now is that I have to set the FilterComboBox<T> items to the unaccented version. For example, “México” is now “Mexico”. And it doesn’t matter if the user types “mèx”, “Méx”, “Mex”. All of them match the correct item.
My previous answer is actually incorrect. The way to do any kind of custom server-side filtering in V10 is to use addFilterChangeListener and then call setFilteredItems inside the listener. I had forgotten about this, as this API was removed in V12 in favor of the improved DataProvider and ItemFilter APIs. Sorry about that.