How to access widgets from ManagedBean

2019-06-11 19:33发布

问题:

Using Primefaces 3.1.1.

I would like to add two date values and subtract two date values.

<p:calendar widgetVar="Var1" id="ID1" value="#{Bean.Till}" pattern="HH:mm" timeOnly="true" mode="popup" showOn="button">

<p:calendar widgetVar="Var2" id="ID2" value="#{Bean.Late}" pattern="HH:mm" timeOnly="true" mode="popup" showOn="button">

A managed bean is called on the click of a submit button.

<h:commandButton value="Save" action=" #{timePickingBean.submitMethod}" >
<f:ajax execute="@form" render="SUM DIFFERENCE" />
</h:commandButton>

My question: How does one read the two 'IDs' or 'WIdgetVars' from the managedbean (.java) file to add them and subtract them later and store the values back into 'SUM' and 'DIFFERENCE'?

Thank you in advance!

-V

回答1:

You could bind your Calendar to the Backing Bean identified as timePickingBean.

Something like this:

<p:calendar widgetVar="Var1" id="ID1" value="#{Bean.Till}" pattern="HH:mm" timeOnly="true" mode="popup" showOn="button" binding="#{timePickingBean.calendar1}"></p:calendar>

<p:calendar widgetVar="Var2" id="ID2" value="#{Bean.Late}" pattern="HH:mm" timeOnly="true" mode="popup" showOn="button" binding="#{timePickingBean.calendar2}"></p:calendar>

And in your backing bean:

public class TimePickingBean {
 private org.primefaces.component.calendar.Calendar calendar1;
 private org.primefaces.component.calendar.Calendar calendar2;

 public void  submitMethod(AjaxBehaviorEvent event) {
    Date cal1 = (Date)calendar1.getValue();
    Date cal2 = (Date)calendar2.getValue();
    do some stuff...
 }
}

Don't forget to control the Nullvalue and the getter and setter. But that is only useful if you need these calendars only in your backing bean and not somewhere else.

A different approach is to trigger the calculation with the datechange event from PrimeFaces. In this case the backing bean is called when changing the value of calendar 2 (and you could include the same for calendar 1):

<p:calendar widgetVar="Var2" id="ID2" value="#{Bean.Late}" pattern="HH:mm" timeOnly="true" mode="popup" showOn="button" binding="#{timePickingBean.calendar2}">
   <f:ajax event="dateSelect" execute="@form" render="SUM DIFFERENCE" action="#{timePickingBean.submitMethod}" ></f:ajax>
</p:calendar>