如何在SuggestBOX中保存除关键字以外的ID?

时间:2013-08-30 02:06:36

标签: java gwt

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

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

现在当用户保存他的记录时,我不会在该数据库中为该用户保存“London”,而是想在数据库中保存“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'中保存。

一切正常,但看起来不太好:
enter image description here

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

2 个答案:

答案 0 :(得分:6)

您还可以创建自己的类型化建议框。您需要实施“建议”并扩展“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(); 
    }
});

答案 1 :(得分:0)

Map<String, Integer>中将城市名称的引用保留为id,然后在保存之前查看ID。