I have a custom widget (OrderItem) in a GWT project. This widget has a TextBox. I set it’s id to “Navid”. But what if I create multiple instances of OrderItem in a panel? The id would be repeated then. This’d make the html invalid.
How do I assign a unique id to the TextBox?
Well, normally, GWT widgets generate their own IDs that will automatically be unique and you would not typically worry about what the ID is. When you say that you are setting the ID of a TextBox, I’m assuming that you’re calling something like
myTextBox.getElement().setId("Navid").There are two simple methods I can think of, depending on your use-case. The HTMLPanel class has a static createUniqueId() method on it that you can use either on its own, or to easily create a unique id. Like
myTextBox.getElemement().setId("Navid-" + HTMLPanel.createUniqueId()). The only problem with this is that the ID that is generated is not deterministic.The other common method would be to generate an ID based on the ID of the parent widget.
myTextBox.getElement().setId("Navid-" + myTextBox.getParent().getElement().getId()).However, I’m going to take a guess here and assume that the reason why you’re wanting to assign your own custom ID to this widget is so that you can address it from outside of your GWT code, from Javascript, for example, from JQuery. In this case, I would recommend that instead of assigning an ID to it, which has to be unique to be useful, that you instead assign an html class name to the widget’s element. You would then address the widget’s element relative to the id, or class of your OrderItem’s id or class. You can add an html class name to an element as in the example
myTextBox.getElement().addStyleName("navid")So, assuming that you assign an html class of orderItemWidget to the root HTML element of your OrderItem widget, and an html class of navid to the TextBox, you could refer to the textbox from a JQuery with the selector
".orderItemWidget .navid"