Pages

Friday, 2 March 2012

GWT: Trick for SuggestBox to make it work as ListBox

For example, when user selects Country from Country SuggestBox, we want to get not only the country name (as display string and replacement string of this suggestion) but also country id, code, ... from the corresponding Country object.



public static class CountryOracle extends MultiWordSuggestOracle { 

  public Map countries = new HashMap(); 

  @Override public void requestSuggestions(Request request, Callback callback) {  
    super.requestSuggestions(request, callback); 
  } 

  public void add(Country country) {
    super.add(country.getName()); 
    countries.put(country.getReplacementString(), country); 
  } 
} 

CountryOracle oracle = new CountryOracle();
List countries = DataProvider.getCountries();
if (countries != null) {
  for (Country c : countries) {
    oracle.add(c);
  }
}

SuggestBox suggestBox = new SuggestBox(oracle);
suggestBox.addSelectionHandler(new SelectionHandler() {
  @Override
  public void onSelection(SelectionEvent event) {
   // now we can get the country id via:
   // oracle.countries.get(event.getSelectedItem.getRepleacementString()).getId()
  }
}); 


1 comment: