play! framework ENUM and Groovy problem

自古美人都是妖i 提交于 2020-01-02 05:19:24

问题


I have something like the following-

Woman.java

...
@Entity
public class Woman extends Model {

    public static enum Outcome {
        ALIVE, DEAD, STILL_BIRTH, LIVE_BIRTH, REGISTER
    }
    ...
}

File.java

...
@Entity
public class Form extends Model {
    ...
    public Outcome autoCreateEvent;
    ...
}

Create.html

#{select "autoCreateEvent", items:models.Woman.Outcome.values(), id:'autoCreateEvent' /}

It saves ENUM value in DB, which is OK. But, when I reload/edit then the problem rises. Because it uses ALIVE, DEAD, etc. as the value for options so it can't show the list properly.

Any Insight?


回答1:


If I understand your question properly you want to use the valueProperty and labelProperty to set the proper values in the option. Something like:

#{select "autoCreateEvent", items:models.Woman.Outcome.values(), valueProperty:'ordinal', labelProperty: 'name', id:'autoCreateEvent' /}

EDIT:

For this to work you will need to tweak the enum a bit, like this:

public enum Outcome {
  A,B;

  public int getOrdinal() {
     return ordinal();
  }

}

The reason is that Play #{select} expects getters in the valueProperty and labelProperty params, and when not found defaults to the enum toString




回答2:


To add to previous answer, add this to your Enum declaration:

public String getLabel() {
    return play.i18n.Messages.get(name());
}

Make sure to use the following declaration:

#{select "[field]", items:models.[Enum].values(), valueProperty:'name', labelProperty: 'label' /}

You can also add this in the Enum:

    @Override
public String toString() {
    return getLabel();
}

Which will be useful if you want to display the internationalized value in your view file (since toString is being called automatically when displayed) but function name() uses toString() so you will have to bind valueProperty to another function, as follow:

public String getLabel(){
    return toString();
}

public String getKey() {
    return super.toString();
}

@Override
public String toString() {
    return Messages.get(name());
}

And the #select use:

#{select "[field]", items:models.[Enum].values(), value:flash.[field], valueProperty:'key', labelProperty: 'label' /}


来源:https://stackoverflow.com/questions/6974052/play-framework-enum-and-groovy-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!