Tuesday, September 12, 2017

Re: How do you create a custom HTML element?

If you have a larger view which should contain a datalist for a given input then something like the following might work (untested):

<g:HTMLPanel>
  ... some view stuff
 
<g:TextBox ui:field="inputBox" />
 
<datalist ui:field="datalist" />
  ... some view stuff
</g:HTMLPanel>

class MyView {

 
@UiField TextBox inputBox;
 
@UiField Element datalist;

 
public MyView() {
    initWidget
(...uibinder...);
    datalist
.setId("countries"); // maybe you can set it in xml as well but it could be that GWT overrides it if it uses temporary ids to get a reference to all @UiField annotated widgets/elements during construction of the uibinder.
    inputBox
.getElement().setAttribute("datalist", "countries");
 
}
}

You can either fill the datalist statically in your xml or dynamically using Document.get().createElement("option") in your java class.

If you want a datalist component that you can use with UiBinder then you should extend Widget and not Composite. A very simple example might look like:

public class DataList extends Widget implements HasHTML {

 
public DataList() {
   setElement
(Document.get().createElement("datalist"));
 
}

 
public void setId(String id) {
   getElement
().setId(id);
 
}

 
public void connectTo(TextBox box) {
   
final String uniqueId = Document.get().createUniqueId();
   setId
(uniqueId);
   box
.getElement().setAttribute("list", uniqueId);
 
}

 
public void setOptions(Set<String> options) {
   
Element datalist = getElement();
   datalist
.removeAllChildren();
   
for (final String option : options) {
     
Element optionElem = Document.get().createElement("option");
     optionElem
.setAttribute("value", option);
     datalist
.appendChild(optionElem);
   
}
 
}

 
@Override
 
public String getHTML() {
   
return getElement().getInnerHTML();
 
}

 
@Override
 
public void setHTML(final String html) {
   getElement
().setInnerHTML(html);
 
}

 
@Override
 
public String getText() {
 
return getElement().getInnerText();
 
}

 
@Override
 
public void setText(final String text) {
   getElement
().setInnerText(text);
 
}
}

The above class allows you to use setOptions() through code or <option value=".." /> child tags (well actually it allows any HTML code as child of <datalist>) in your UiBinder XML.

-- J.

--
You received this message because you are subscribed to the Google Groups "GWT Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit+unsubscribe@googlegroups.com.
To post to this group, send email to google-web-toolkit@googlegroups.com.
Visit this group at https://groups.google.com/group/google-web-toolkit.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment