使用datatable列中的commandbutton在JSF中传递行索引

时间:2011-01-06 21:36:46

标签: web-applications jsf datatable

我在像这样的数据表列中添加了一个命令按钮。单击该按钮时,记录的ID将用于更新数据库中的某些其他记录。这是我试过的:

<ice:dataTable value="#{myBean.storedRecords}" var="record" rows="10">
   <h:column>
     <h:commandButton id="myButton#{record.id}" value="#{record.id}" 
             actionListener="myBean.buttonActionListener" />
   </h:column>
</ice:dataTable>

在输出中我可以看到该值是记录的id。但是,在buttonAction侦听器方法中,按钮的id似乎只是“myButton”而没有记录的id。

请指出如何动态设置按钮的ID。或者,您可以建议一种通过按钮单击将行的索引传递到服务器的方法。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

DataModel返回到数据表而不是List

private DataModel storedRecords;

public MyBean() {
    storedRecords = new ListDataModel(recordDAO.listStoredRecords());
}

// ...

然后你可以通过bean的action方法中的DataModel#getRowData()来获取当前行。

public String buttonAction() {
    StoredRecord storedRecord = (StoredRecord) storedRecords.getRowData();
    // ...
    return "outcome";
}

请注意,我隐式提示在按钮上使用action而不是actionListener

答案 1 :(得分:0)

这是我的解决方案。

通过调试和谷歌搜索我意识到我HtmlDataTable是HtmlCommandButton的祖父母(!)。和HtmlDataTable扩展了UIData类。和UIData有一个公共方法来获取当前行中的存储值。

public void btnActionListenerMethod(Action e) {
  if(e.getSource() instanceof HtmlCommandButton) {
    HtmlCommandButton button = (HtmlCommandButton) e.getSource();
    UIData dataTable = (UIData) button.getParent().getParent();
    MyRecord record = (MyRecord) dataTable.getRowData();
    // ......
  }
}