JSF表单需要更新字段

Dim*_*ele 2 jsf date primefaces

我有一个带有2个日期的JSF表单.开始日期是必需的.

我需要的两件事:

  • 填写结束日期时 - >然后应计算并填写天数.
  • 填写天数时(例如:31) - >然后应填写结束日期.

如何在JSF中完成?

在此输入图像描述

我的表格:

<h:form id="date">

    <h:panelGrid columns="3">
        <p:outputLabel for="startDate" value="Start Date"/>
        <p:calendar id="startDate" value="#{dateBean.startDate}" required="true" pattern="d MMM yyyy"/>
        <p:message for="startDate"/>

        <p:outputLabel for="endDate" value="End Date"/>
        <p:calendar id="endDate" value="#{dateBean.endDate}" pattern="d MMM yyyy"/>
        <p:message for="endDate"/>

        <p:outputLabel for="days" value="Days"/>
        <p:inputText id="days" value="#{dateBean.days}"/>
        <p:message for="days"/>
    </h:panelGrid>

</h:form>
Run Code Online (Sandbox Code Playgroud)

我的豆子:

@Named(value = "dateBean")
@SessionScoped
public class DateBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Date startDate;
    private Date endDate;
    private Integer days;

    //getters and setters
    ...
Run Code Online (Sandbox Code Playgroud)

Mag*_*lex 5

我宁愿选择内置的Primefaces方式来做到这一点.有一个事件被调用dateSelect,当日期发生变化时将触发该事件:

Calendar提供dateSelect ajax行为事件,以便在选择日期时执行即时ajax选择.如果将方法定义为侦听器,则将通过传递org.primefaces.event.SelectEvent实例来调用它.

使用它,endDate看起来像(忽略日期格式属性,这似乎是错误的):

<p:calendar id="endDate" value="#{dateBean.endDate}">
    <p:ajax event="dateSelect" listener="#{dateBean.handleDateSelect}" update="days" />
</p:calendar>
Run Code Online (Sandbox Code Playgroud)

一旦选择了新日期,这将注册要调用的侦听器.它将调用您的辅助bean,然后重新呈现days输入字段以显示新值.

DateBean你那么将执行此方法来执行逻辑在日期选择的情况发生:

public void handleDateSelect(SelectEvent event) {
    Date date = (Date) event.getObject();
    // the below method would calculate the difference in days between the dates
    calculateDaysIfStartDateIsFilled(date);
}
Run Code Online (Sandbox Code Playgroud)

对于days标记,我将用于p:event触发更改事件,即字段中的值更改时:

<p:inputText id="days" value="#{dateBean.days}">
    <p:ajax event="change" update="endDate" listener="#{dateBean.handleDaysChange}" />
</p:inputText>
Run Code Online (Sandbox Code Playgroud)

并添加以下方法DateBean来执行逻辑:

public void handleDaysChange() {
    calculateToDateIfStartDateIsFilled();
}
Run Code Online (Sandbox Code Playgroud)