2

我正在使用一个简单的城市 SuggestBox,我从数据库中获取城市列表并将它们放入 GWTSuggestBox oracle。

之后,用户可以从建议框建议中选择他的城市,然后用户保存他的记录。例如,他将从建议框列表中选择“伦敦”。

现在当用户保存他的记录时,我不会在数据库中为该用户保存“伦敦”,而是我想在数据库中保存“3”(伦敦 ID)。

为此,我正在做的是这样的:

       public MultiWordSuggestOracle createCitiesOracle(ArrayList<City> cities){
    for(int i=0; i<cities.size(); i++){
        oracle.add(cities.get(i).getCity()+","+cities.get(i).getCityId());

    }
    return oracle;
}

现在,我的 city 和 cityID 都显示在SuggestBox 中,然后可以从那里保存“city”和“cityId”。

一切正常,但看起来不太好:
在此处输入图像描述

喜欢它在建议框建议中显示为“London,3”等等。我不想显示这个 3,我如何以及在哪里保存这个 Id(3) 以供将来使用?

4

2 回答 2

6

您还可以创建自己的类型化建议框。您需要实施“Suggestion”并扩展“SuggestOracle”。

超级简单的版本可能看起来:

// CityOracle 
public class CityOracle extends SuggestOracle {

  Collection<CitySuggestion> collection;

  public CityOracle(Collection<CitySuggestion> collection) {
        this.collection = collection;
  }

  @Override
  public void requestSuggestions(Request request, Callback callback) {
    final Response response = new Response();

    response.setSuggestions(collection);
    callback.onSuggestionsReady(request, response);
  }

}



//CitySuggestion
public class CitySuggestion implements Suggestion, Serializable, IsSerializable {

    City value;

    public CitySuggestion(City value) {
        this.value = value;
    }

    @Override
    public String getDisplayString() {
        return value.getName();
    }

    @Override
    public String getReplacementString() {
        return value.getName();
    }

    public City getCity() {
        return value;
    }

}


 // Usage in your code:

// list of cities - you may take it from the server 
List<City> cities = new ArrayList<City>();
cities.add(new City(1l, "London"));
cities.add(new City(2l, "Berlin"));
cities.add(new City(3l, "Cracow"));

// revert cities into city-suggestions
Collection<CitySuggestion> citySuggestions = new ArrayList<CitySuggestion>();
for (City city : cities) {
    citySuggestions.add(new CitySuggestion(city));
}

//initialize city-oracle
CityOracle oracle = new CityOracle(citySuggestions);

// create suggestbox providing city-oracle     
SuggestBox citySuggest = new SuggestBox(oracle);

// now when selecting an element from the list, the CitySuggest object will be returned. This object contains not only a string value but also represents selected city
citySuggest.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {

    @Override
    public void onSelection(SelectionEvent<Suggestion> event) {
        Suggestion selectedItem = event.getSelectedItem();
        //cast returned suggestion
        CitySuggestion selectedCitySuggestion = (CitySuggestion) selectedItem;
        City city = selectedCitySuggestion.getCity();
        Long id = city.getId(); 
    }
});
于 2013-08-30T06:24:10.387 回答
0

在 a 中保留从城市名称到 id 的引用Map<String, Integer>,然后在保存之前在那里查找 ID。

于 2013-08-30T02:10:44.013 回答