我正在尝试将默认值设置为h:selectOneMenu。但是,它没有用。
这是我的代码
的index.xhtml
<h:body>
<h:form id="test">
<h:selectOneMenu value="#{selectMenuBean.selectedItem}"
title="select version"
onchange="submit()"
disabled="false" id="combo">
<f:selectItems value="#{selectMenuBean.selectItems}" />
</h:selectOneMenu>
</h:form>
</h:body>
BackingBean
private String selectedItem;
private List selectItems;
private int version=3;
public List getSelectItems() {
List<Version> selectedItems = ExportDao.getVersionsList();
System.out.println("List size: "+selectedItems.size());
selectItems = new ArrayList();
for (Version v1 : selectedItems) {
String DATE_FORMAT = "yyyy-MM-dd HH:mm";
//Create object of SimpleDateFormat and pass the desired date format.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
selectItems.add(new SelectItem(v1.getVersion(), "V" + v1.getVersion() + "/" + sdf.format(v1.getDate())));
if(version = v1.getVersion()) // I have to check the version and set the matching version as selected.
selectedItem = "V" + v1.getVersion() + "/" + sdf.format(v1.getDate());
}
return selectItems;
}
答案 0 :(得分:4)
您使用商品标签而不是商品值设置selectedItem
。
替换
selectedItem = "V" + v1.getVersion() + "/" + sdf.format(v1.getDate());
通过
selectedItem = v1.getVersion();
答案 1 :(得分:3)
一些可能的解决方案:
1)将selectItems的类型设置为SelectItem[]
,而不是类型为List
。
或2)尝试设置selectItems的var,itemValue和itemLabel属性,如下所示,并将实际的Version对象放入列表中。
或我最喜欢的,3)创建一个知道如何将Version对象转换为String的VersionConverter。如果您的Version对象持久存储在数据库中并且具有Id,则下面的示例。在构造之后,您的selectedItem和List selectItems应该具有typ Version(和List),而不是String。 JSF将自行处理转换。
@FacesConverter(forClass=Version.class)
public class VersionConverter implements Converter{
public VersionConverter() {
}
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
try {
// Get an EJB that can fetch the Version from a DB. Alternativly, do whatever you need to get your object from a string.
InitialContext ic = new InitialContext();
MyDao myDao = (MyDao)ic.lookup(String.format("java:global/%s/MyBean", (String)ic.lookup("java:module/ModuleName")));
return myDao.findEntity(Version.class, getKey(value));
} catch (NamingException e) {
return null;
}
}
Long getKey(String value) {
Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Version) {
Version e = (Version) object;
return getStringKey(e.getId());
}
else
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Version.class.getName());
}
}