10

Can I use enum values as field values inside UiBinder template ? I'm using GWT 2.4

Something like this

<ui:with field="en" type="com.mine.courierApp.shared.PayerType" />

looks promising, where

public enum PayerType
{
    Sender,
    Recipient
}

but I can't refer to values of the enum by en.Sender.

Is it even possible ?

expert
  • 29,290
  • 30
  • 110
  • 214

2 Answers2

13
<ui:import field='com.mine.courierApp.shared.PayerType.Sender' />

or

<ui:import field='com.mine.courierApp.shared.PayerType.*' />

And then you can use it as payerType='{Sender}'.

But UiBinder should automatically try to translate enum constant names into values, so the following should work without any need for a ui:with:

<my:MyWidget payerType='Sender' />

If the MyWidget widget has a public void setPayerType(PayerType type) method, UiBinder should look for an enum value named Sender (from the *.ui.xml file) in the PayerType enum (from the method's argument type).

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • Unfortunately it fails in runtime saying: `ERROR: Returns class com.mine.courierApp.shared.PayerType, can't be used as class java.lang.String` – expert Feb 29 '12 at 19:34
  • Thomas, can I ask you also take a look at [this question](http://stackoverflow.com/questions/9476341/)? You know a lot about GWT internals. – expert Feb 29 '12 at 20:04
  • Sorry, that should be `ui:import` instead of `ui:with`. I just checked in the [unit-tests for the feature](http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/test/com/google/gwt/uibinder/test/client/WidgetBasedUi.ui.xml#83) (and you can have a look at the `EnumeratedLabel` there for an example of automatically translating a string into an enum value. – Thomas Broyer Mar 01 '12 at 16:49
  • 1
    Thanks a lot! There is important note for those who stumble upon this. **You have to add `.name` to your enum so it's converted to String if necessary.** I'll modify answer to reflect that. – expert Mar 01 '12 at 21:01
  • Watch out if you enable Enum ellison in the compiler. – Joseph Lust Mar 24 '14 at 21:40
0

If you don't ui:import the enum class like this:

<ui:import field='com.mine.courierApp.shared.PayerType.*' />

then you don't get content-assist, which the whole point of this in the first place.

But then you run into another issue...

Although you can simple type { ctrl-space } to get a popup menu of the enum value, if you are using, say, bootstrap3, there are various enums that each have their own "DEFAULT" value. The ui template editor will complain about that; i.e. if you start making extensive use of this content-assist feature, you will need to ensure the imported enums have unique value names.

Ian White
  • 91
  • 1
  • 3