JSF - 将值与动态构建的复选框相关联

时间:2011-08-21 16:24:51

标签: jsf-2

我发现了一个非常接近我要做的教程:http://www.andygibson.net/blog/tutorial/binding-dynamic-multi-select-checkboxes-with-jsf/

唯一的变化是我在我的支持bean中而不是在我的.xhtml文件中构建我的复选框,但是'value'属性没有正确设置。

来自我的.xhtml文件的

片段:

<h:form>
<h:panelGrid binding="#{myBean.myGrid}"></h:panelGrid>
<h:commandButton id="submit" type="submit">
</h:form>
来自myBean的

片段:

public HtmlPanelGrid getMyGrid()
{
  resultGrid = new HtmlPanelGrid();
  resultGrid.setColumns(2)
  List children = resultGrid.getChildren();

  FacesContext myFacesInstance = FacesContext.getCurrentInstance();
  Application myApp = myFacesInstance.getApplication();
  ExpressionFactory expFactory = myApp.getExpressionFactory();

  SelectItem tempSelectItem;
  String valuStringExpression;
  ValueExpression valExpression;

  //create panel for the checkboxes
  HtmlSelectManyCheckbox checkboxPanel = new HtmlSelectManyCheckbox();
  checkboxPanel.setLayout("pageDirection");

   List<SelectItem> checkChoiceList = new ArrayList<SelectItem>();

   for (int i=0;i<numChoices;i++)
   {
    valStringExpression = "#{myBean.responseValue["+i+"]}";
valExpression = expFactory.createValueExpression(myFacesInstance.getELContext(), valStringExpression, String.class);        
    tempSelectItem = new SelectItem(valExpression,choiceLabels.get(i));
    checkChoiceList.add(tempSelectItem);
   }

  UISelectItems checkboxList = new UISelectItems();
  checkboxList.setValue(checkChoiceList);
  checkboxPanel.getChildren().add(checkboxList);

  children.add(checkboxPanel);

return resultGrid;
}

问题是每个复选框的value属性都没有正确映射到我的“#{myBean.responseValue [”+ i +“]}”。

如果我从网页上提取“查看来源”,则复选框标记的值显示为:

value="ValueExpression[#{myBean.responseValue[0]}]"

我一直在谷歌上搜索数小时,我很难过。非常感谢任何帮助或想法!!

1 个答案:

答案 0 :(得分:0)

SelectItem构造函数的第一个参数需要实际选择项值,而不是某个值表达式。相应地修复它:

Object value = valExpression.getValue(elContext);
tempSelectItem = new SelectItem(value, choiceLabels.get(i));