在Tapestry中为具有多维枚举的select组件创建模型

时间:2013-08-19 17:35:57

标签: java enums tapestry

在我的网页课程中:

public SelectModel getCountryListEnum() {
    return new EnumSelectModel(CountryListEnum.class, resources.getMessages());
}

public CountryListEnumEncoder getCountryListEnumEncoder(){
        return new CountryListEnumEncoder();
}

在我的模板中(select.selectcountries扩展Tapestry Select Component btw):

      <t:select.selectcountries id="country" t:id="country" model="CountryListEnum"  value="user.address.countrycode" encoder="CountryListEnumEncoder"/>

我的枚举:

public enum CountryListEnum {

    AFGHANISTAN("Afghanistan", "AF"),
    ALBANIA("Albania", "AL"),
    ALGERIA("Algeria", "DZ"),
    (...ETC);

    private String country;
    private String code;

    private CountryListEnum( String country, String code) {
        this.country = country;
        this.code = code;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getId() {
        return getCode();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    private CountryListEnum() {
    }

    public static int getSize() {
        return values().length;
    }

    public static String getNameFromCode(String code) {

        for (CountryListEnum countryEnum : values()) {
            if (code.trim().equals(countryEnum.getCode())) {
                return countryEnum.getCountry();
            }
        }
        throw new IllegalArgumentException("Country Code: "+ code + " does not exist");
    }

}

我的ValueEncoder:

public class CountryListEnumEncoder implements ValueEncoder<CountryListEnum>, ValueEncoderFactory<CountryListEnum> {

    @Override
    public String toClient(CountryListEnum value) {
        return value.getId();
    }

    @Override
    public CountryListEnum toValue(String clientValue) {
        Validate.notEmpty(clientValue);

        for (CountryListEnum countryEnum : CountryListEnum.values()) {
            if (clientValue.trim().equals(countryEnum.getCode())) {
                return countryEnum;
            }
        }

        throw new IllegalArgumentException("Country Code: " + clientValue + " does not exist");
    }

    @Override
    public ValueEncoder<CountryListEnum> create(Class<CountryListEnum> type) {
        return this;  //To change body of implemented methods use File | Settings | File Templates.
    }
}

最后,我收到以下错误:

  

java.lang.String无法强制转换为   com.starpoint.instihire.api.domain.reference.CountryListEnum

我尝试提交类型coercer(如建议的here),但这也不起作用。我还尝试从select中省略模型参数,并将select.selectcountries组件的id更改为countryListEnum(如建议的here)。抓住我的头......

1 个答案:

答案 0 :(得分:1)

看起来user.address.countrycode是字符串,而不是CountryListEnum