Best way to have auto-complete field in a form

Hi experts,

I am looking to add an autocomplete field in my form which would make an api call to get some data and based upon the selection, rest of the form fields gets populated with selected data.

For now, I don’t see Combobox component supporting this out of the box. I came across this add-on which seems to be doing what I need.

Please let me know if this add-on is good as it is compatible with Vaadin 24. Or do you guys recommend something different.

Thanks

Hi Sanjay.

Why do you think that Combobox component might not be suitable for your needs? … you can use custom filtering as a basis and in there fetch the data, re configure the items based on what you got from the database and even populate the rest of the form fields.

Regards.

Hi Martin,

Thanks for responding.

I could use custom filtering only if and when the value change listener would work when the user types something in the field. Upon my testing, this listener was not catching any events when I typed any text in the combobox field.

Because initially, the combobox is empty. I only set items when the user types something and based upon the text, I need to make a call to the API to get values and set that list as combobox items.

I am not sure if there is something wrong in what I am doing. Is it working on your end for this scenario?

If I understood what you want, the trick is not to use the value change listener, but instead provide a fetchCallback when calling the setItems() method.

Take a look at this example:

public class ComboWithBackendDataView extends VerticalLayout {
	
    List<String> countries = Arrays.asList(Locale.getISOCountries()).stream().map(isoCode->new Locale("es",isoCode).getDisplayCountry()).toList();

	public ComboWithBackendDataView() {
        ComboBox<String> comboBox = new ComboBox<>("Select a country");

        comboBox.setItems(query->{
            Optional<String> filter = query.getFilter();
            int limit = query.getLimit();
            int offset = query.getOffset();
            return simulateBackendQuery(filter,limit,offset);
        });

        add(comboBox);
	}

	private Stream<String> simulateBackendQuery(Optional<String> filter, long limit, long offset) {
		return  countries.stream()
	            .filter(item -> !filter.isPresent() || item.contains(filter.get())).skip(offset).limit(limit);
	}
    
}

Every time you type something the fetchCallback will be invoked so you can make your API call to get the filtered values.

Can you give it a try?

2 Likes

Hi Martin,

fetchCallback works great for my use case. Appreciate your help.