Thursday, September 22, 2011

GWT Tricks #1

I've decided to post any "tricks" or common GWT mistakes that I've run into, researched and fixed. Hopefully these will be helpful to the next person who sees the same errors, researches the same information and wonders which fix to "try".

The SafeHTML warning

Ever see these warnings when running your GWT application?
[WARN] Template with variable in CSS context: The template code
generator cannot guarantee
HTML-safety of the template -- please inspect manually
What does this mean? How do I fix it?

Basically, it is telling you that you have inserted an "include" in your code to something in a .css file. Look for something like this:
sb.appendHtmlConstant("<div class=<\"myapp-CellSelect\">");

Where the myapp-CellSelect happens to be defined in your myapp.css file. Since you are bringing something in from "outside", the code generator can't insure it's going to work. That "outside" thing may be broken, missing, or malformed and is a bug waiting to happen.

So, what to do?
Remove this external reference and put it inline with your div. So, let say your: myapp-CellSelect is:

.myapp-CellSelect {
text-decoration:underline;
cursor: pointer;
}

then your code should look like:
sb.appendHtmlConstant("<div style=\"text-decoration:underline;cursor:point\">");
You no longer are pointing to something in your .css file and the warnings will now be gone.


Auto Selecting an Input Field

When implementing data input screens, like popup dialog boxes for example, you sometimes want to set the focus in the dialog box to something meaningful. Maybe this data entry screen has a Name field followed my other input fields. It might be nice to automatically select the Name field for the user so that they can just start typing when this popup opens. In typical application programming, you can just set the Name field as the initial focus field and it works, however, with web/GWT programming, this will not work as you expect.

Take this example:

TextBox nameBox = new TextBox();
nameBox.setFocus(true);

build the rest of your fields, populate them with data and then show() the dialog. The nameBox is not highlighted, not focused on, not ready for user input until they click on it. Why? Because the setFocus must be called after the dialog box has been rendered. Ok, so what to do?

In the code that will do the: dialog.show(); call, set the focus to the field you want when the system is not busy, meaning right after it has rendered your dialog. How? Like this:

Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
nameBox.setFocus(true);
}
});

dialog.show();

Remember, with GWT there are a lot of async operations that might happen. In my case, I make calls to my database to fill in my dialog and then once they have completed, I show my dialog. Had I tried to setFocus at the beginning, it would have failed. Setting focus at the end works.

No comments:

Post a Comment