Tuesday, October 7, 2008

GWT SuggestBox: how to make multiple result

GWT offers a lot of nice components, but i was surprised, that they don't have SuggestBox as gmail has, where you can have several suggestions as a result.
So, at the beginning i wanted to subclass a SuggestBox, but found, that it is a final :(
Then decided to create MultipleSuggestBox from scratch. Did it, and than fount a hack way to do the same, but much simpler! There is a solution.


/**
* MultipleTextBox allow to have multiple suggestions at a result, separated by
* comma, like gmail has at compose message field "TO", "CC", "BCC".
*
* @author Viktor Zaprudnev
*
* Usage:
* SuggestBox(oracle, new MultipleTextBox());
*/

public class MultipleTextBox extends TextBoxBase {
/**
* Creates an empty multiple text box.
*/
public MultipleTextBox() {
this(Document.get().createTextInputElement(), "gwt-TextBox");
}

/**
* This constructor may be used by subclasses to explicitly use an existing
* element. This element must be an <input> element whose type is
* 'text'.
*
* @param element
* the element to be used
*/
protected MultipleTextBox(Element element) {
super(element);
assert InputElement.as(element).getType().equalsIgnoreCase("text");
}

MultipleTextBox(Element element, String styleName) {
super(element);
if (styleName != null) {
setStyleName(styleName);
}
}

@Override
public String getText() {
String wholeString = super.getText();
String lastString = wholeString;
if (wholeString != null && !wholeString.trim().equals("")) {
int lastComma = wholeString.trim().lastIndexOf(",");
if (lastComma > 0) {
lastString = wholeString.trim().substring(lastComma + 1);
}
}
return lastString;
}

@Override
public void setText(String text) {
String wholeString = super.getText();
if (text != null && text.equals("")) {
super.setText(text);
} else {
// Clean last text, to replace with new value, for example, if new
// text is v.zaprudnevd@gmail.com:
// "manuel@we-r-you.com, v" need to be replaced with:
// "manuel@we-r-you.com, v.zaprudnevd@gmail.com, "

if (wholeString != null) {
int lastComma = wholeString.trim().lastIndexOf(",");
if (lastComma > 0) {
wholeString = wholeString.trim().substring(0, lastComma);
} else {
wholeString = "";
}

if (!wholeString.trim().endsWith(",")
&& !wholeString.trim().equals("")) {
wholeString = wholeString + ", ";
}

wholeString = wholeString + text + ", ";
super.setText(wholeString);
}
}
}
}

2 comments:

Unknown said...

Great post, it works for a TextArea as well. Just what I was looking for.

Kanny said...

Gr8 post dude.......it really helped me......Thnks!!