membersound
membersound

Reputation: 86747

How to set css error-styles programatically on a TextBox

Why can't I apply custom css styles to a single TextBox?

I'm trying to set some error styles on a single TextBox. What's wrong with the following implementation?

init:

static final String STYLES = ErrorRes.INSTANCE.css().style();

@UiField TextBox box;
box.setStylePrimaryName(STYLES);

Resource interface

interface ErrorRes extends ClientBundle {
    static final ErrorRes INSTANCE = GWT.create(ErrorRes.class);

    @Source("Error.css")
    Style css();

    interface Style extends CssResource {
        @ClassName("gwt-TextBox-error")
        String style();
    }
}

Error.css

.gwt-TextBox-error {
     border: 1px solid red !important;
}

Upvotes: 0

Views: 924

Answers (1)

A1exandr Belan
A1exandr Belan

Reputation: 4780

If you whant to get gwt-TextBox-error style name on widget, you need set box.setStylePrimaryName("gwt-TextBox"); - it's by default. And when error occured use box.setStyleDependentName("error", true); HTML will be class="gwt-TextBox gwt-TextBox-error". And to clear error style, use box.setStyleDependentName("error", false);

OR

You can use addStyleName("gwt-TextBox-error") and removeStyleName("gwt-TextBox-error") in a same way.

---UPDATE---

So, I tryed to run your case and it works well. At the first of all you need inject css from resources to page in runtime:

ErrorRes.INSTANCE.css().ensureInjected();

I use it in the begining of onModuleLoad()

Then, to add error style use: box.addStyleName(STYLES); and box.removeStyleName(STYLES); to remove it.

You can't use pair setStylePrimaryName() and setStyleDependentName() with bundled css becouse css name will be obfuscated.

Upvotes: 2

Related Questions