在 h:dataTable 中使用 h:commandButton

6
我正在使用JSF数据表格。表格中的一列是一个命令按钮。
当单击此按钮时,我需要使用表达式语言传递几个参数(例如所选行的值)。这些参数需要传递到JSF托管的bean中,该bean可以对它们执行方法。
我已经使用了以下代码片段,但我在JSF bean上得到的值始终为null。
<h:column>
    <f:facet name="header">
        <h:outputText value="Follow"/>
    </f:facet>

    <h:commandButton id="FollwDoc" action="#{usermanager.followDoctor}" value="Follow" />
    <h:inputHidden id="id1" value="#{doc.doctorid}" />
</h:column>

Bean方法:

public void followDoctor() {
    FacesContext context = FacesContext.getCurrentInstance();
    Map requestMap = context.getExternalContext().getRequestParameterMap();
    String value = (String)requestMap.get("id1");
    System.out.println("Doctor Added to patient List"+ value);
}

如何使用命令按钮将值传递到JSF托管的bean中?

1个回答

11

在操作方法中使用DataModel#getRowData()来获取当前行。

@ManagedBean
@ViewScoped
public class Usermanager {
    private List<Doctor> doctors;
    private DataModel<Doctor> doctorModel;

    @PostConstruct
    public void init() {
        doctors = getItSomehow();
        doctorModel = new ListDataModel<Doctor>(doctors);
    }

    public void followDoctor() {
        Doctor selectedDoctor = doctorModel.getRowData();
        // ...
    }

    // ...
}

在数据表格中使用它。

<h:dataTable value="#{usermanager.doctorModel}" var="doc">

并且在视图中摆脱那个与 h:commandButton 相邻的 h:inputHidden


-不太优雅的-替代方法是使用f:setPropertyActionListener

public class Usermanager {
    private Long doctorId;

    public void followDoctor() {
        Doctor selectedDoctor = getItSomehowBy(doctorId);
        // ...
    }

    // ...
}

使用以下按钮:

<h:commandButton action="#{usermanager.followDoctor}" value="Follow">
    <f:setPropertyActionListener target="#{usermanager.doctorId}" value="#{doc.doctorId}" />
</h:commandButton>

相关信息:


1
在我看来,“不太优雅”的方法对于初学者来说更直观一些。那么另一种方法怎么样? - s_t_e_v_e

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接