I am trying to update a duration (difference of two dates being captured by . When I add the fireDrillEvacTime to the rendering of the following stack trace dump:
JBWEB000309: type JBWEB000066: Exception report
JBWEB000068: message <f:ajax> contains an unknown id 'fireDrillStartTime,fireDrillEvacTime' - cannot locate it in the context of the component fireDrillStartTime
JBWEB000069: description JBWEB000145: The server encountered an internal error that prevented it from fulfilling this request.
JBWEB000070: exception
javax.servlet.ServletException: <f:ajax> contains an unknown id 'fireDrillStartTime,fireDrillEvacTime' - cannot locate it in the context of the component fireDrillStartTime
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
org.monarchnc.filter.LoginFilter.doFilter(LoginFilter.java:41)
JBWEB000071: root cause
javax.faces.FacesException: <f:ajax> contains an unknown id 'fireDrillStartTime,fireDrillEvacTime' - cannot locate it in the context of the component fireDrillStartTime
com.sun.faces.renderkit.html_basic.AjaxBehaviorRenderer.getResolvedId(AjaxBehaviorRenderer.java:289)
com.sun.faces.renderkit.html_basic.AjaxBehaviorRenderer.appendIds(AjaxBehaviorRenderer.java:276)
com.sun.faces.renderkit.html_basic.AjaxBehaviorRenderer.buildAjaxCommand(AjaxBehaviorRenderer.java:218)
com.sun.faces.renderkit.html_basic.AjaxBehaviorRenderer.getScript(AjaxBehaviorRenderer.java:88)
javax.faces.component.behavior.ClientBehaviorBase.getScript(ClientBehaviorBase.java:103)
Here is my xhtml file:
<h:outputLabel for="fireDrillStartTime" value="Fire Drill Start Time:"/>
<rich:calendar value="#{fireDrillBean.fireDrill.fireDrillStartTime}" id="fireDrillStartTime"
popup="true" datePattern="yyyy-MM-dd HH:mm:ss"
enableManualInput="true" required="true"
showApplyButton="true" cellWidth="24px" cellHeight="22px" style="width:200px">
<f:ajax event="change" execute="#this" bypassUpdates="#{true}" render="fireDrillStartTime,fireDrillEndTime"/>
</rich:calendar>
<h:outputText value="*"/>
<h:outputLabel for="fireDrillEndTime" value="Fire Drill End Time:"/>
<rich:calendar value="#{fireDrillBean.fireDrill.fireDrillEndTime}" id="fireDrillEndTime"
popup="true" datePattern="yyyy-MM-dd HH:mm:ss"
enableManualInput="true" required="true"
showApplyButton="true" cellWidth="24px" cellHeight="22px" style="width:200px">
<f:ajax event="change" execute="#this" bypassUpdates="#{true}" render="fireDrillEndTime,fireDrillEndTime"/>
</rich:calendar>
<h:outputText value="*"/>
<h:outputLabel for="fireDrillEvacTime" value="Fire Drill Evac Time:"/>
<h:outputText id="fireDrillEvacTime" value="#{fireDrillBean.evacDuration}" style="width: 175px;"/>
<h:outputText value="" />
Here is the setter/getter:
public Long getEvacDuration() {
return evacDuration;
}
public void setEvacDuration(long evacDuration) throws Exception{
try{
if (this.fireDrill.getFireDrillStartTime() != null && this.fireDrill.getFireDrillEndTime() != null){
evacDuration= fireDrill.getFireDrillStartTime().getTime() - fireDrill.getFireDrillEndTime().getTime();
evacDuration = timeUnit.convert(evacDuration,TimeUnit.SECONDS);
this.fireDrill.setEvacuationDuration(evacDuration);
}
}
catch (Exception up) {
throw up;
}
this.evacDuration=evacDuration;
}
I am new to this, and have searched on how to calculate the date, but having a hard time with figuring how to get a rich:calendar to execute an ajax call when either of the dates are changed to rerender the fireEvacTimeTime without having to click a calculation button. What am I doing wrong?
Hej Azulitabijou,
i wrote a small example for you. It is working, but you'll have to adapt it to your needs.
I left out all the patterns and evaluations..
The Controller Class
package de.professional_webworkx.so.controller;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.inject.Inject;
import javax.inject.Named;
#Model
public class FireCalendarController {
#Inject
FacesContext context;
private Date startDate;
private Date endDate;
private long duration;
#Produces
#Named
public Date getStartDate() {
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "MSG");
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
#Produces
#Named
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Produces
#Named
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public void doSomething() {
duration = endDate.getTime()-startDate.getTime();
Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "Start was " + startDate);
}
}
UPDATE
create your own calendar component like this and place it under webapp/resources/emcomp/calendar.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:composite="http://java.sun.com/jsf/composite">
<!-- INTERFACE -->
<composite:interface>
<composite:attribute name="date" />
<composite:clientBehavior name="date_change" event="change" targets="#{cc.id}"/>
</composite:interface>
<!-- IMPLEMENTATION -->
<composite:implementation>
<h:panelGrid columns="2">
<h:outputText value="Startdatum" />
<rich:calendar id="#{cc.id}" value="#{cc.attrs.date}" datePattern="dd.MM.yyyy"></rich:calendar>
</h:panelGrid>
</composite:implementation>
</html>
And use your calendar-component like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:em="http://java.sun.com/jsf/composite/emcomp">
<h:head></h:head>
<h:body>
<rich:panel>
<f:facet name="header">
fireDrill at SO ;9
</f:facet>
<h:form>
<h:panelGrid columns="2">
<h:outputText value="Startdate:" />
<!--
<rich:calendar value="#{fireCalendarController.startDate}"></rich:calendar>
-->
<em:calendar id="start" date="#{fireCalendarController.startDate}">
</em:calendar>
<em:calendar id="end" date="#{fireCalendarController.endDate}">
<a4j:ajax event="date_change" execute="start,end" render="duration"/>
</em:calendar>
<h:outputText value="Duration" />
<h:outputText id="duration" value="#{fireCalendarController.duration}" />
</h:panelGrid>
</h:form>
</rich:panel>
</h:body>
</html>
I hope this will help you to go on working.
Related
first of all, I am writing this because I am desperate. The thing is I was doing a simple Spring Boot CRUD with Primefaces. I used a bean called "carBean" to access the data in the index.xhtml file. Until there everything ok, things started to turn weird from now on. I tried to use a simple inputText to bind a text given in the UI to a property in the bean.
But I was constantly getting error 500, telling me that the property "marca" was not found in the bean, and I have checked 10000 times and everything is OK in there. So I started testing, and eventually I figured out that, the property that was working fine "carBean.cars" if I change the name to whatever I change (and obviously the methods liked to the property), It stop working. Is like the only property that works has to be named "cars". What I am missing here? Is driving me crazy, I promise this was my last resource. Thanks in advance .
carBean
package com.example.bean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import com.example.controller.CarController;
import com.example.dto.CarDTO;
import lombok.Data;
#Data
#Named("carBean")
#Scope(value = "session")
public class CarBean implements Serializable {
private static final long serialVersionUID = -8338541378806874723L;
#Autowired
CarController carController;
private List<CarDTO> cars;
private Integer id;
private String marca;
private String modelo;
private String precio;
private String bastidor;
private String potencia;
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public List<CarDTO> getCars() {
cars = carController.getAllCars();
return cars;
}
public void delete(CarDTO car) {
carController.deleteCar(car.id);
cars = carController.getAllCars();
}
public void add() {
CarDTO newCar = new CarDTO();
newCar.marca = this.marca;
newCar.modelo = this.modelo;
newCar.precio = this.precio;
newCar.bastidor = this.bastidor;
newCar.potencia = this.potencia;
carController.create(newCar);
}
public String redirect() {
return "index.xhtml?faces-redirect=true";
}
}
index.xhtml
<!DOCTYPE xhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h3> REGISTRO DE COCHES </h3>
<h:form id = "tabla">
<div class="card">
<p:dataTable var="car" value="#{carBean.cars}">
<p:column sortBy="#{car.marca}" headerText="Marca">
<h:outputText value="#{car.marca}" />
</p:column>
<p:column sortBy="#{car.modelo}" headerText="Modelo">
<h:outputText value="#{car.modelo}" />
</p:column>
<p:column sortBy="#{car.precio}" headerText="Precio">
<h:outputText value="#{car.precio}" />
</p:column>
<p:column sortBy="#{car.bastidor}" headerText="Bastidor">
<h:outputText value="#{car.bastidor}" />
</p:column>
<p:column sortBy="#{car.potencia}" headerText="Potencia">
<h:outputText value="#{car.potencia}" />
</p:column>
<p:column>
<p:commandButton type="submit" value="Eliminar" actionListener="#{carBean.delete(car)}"
update=":tabla" />
<p:commandButton type="button" value="Editar"/>
</p:column>
</p:dataTable>
<p:commandButton value="Nuevo Coche" type="submit" oncomplete="PF('createModal').show();"/>
</div>
</h:form>
<p:dialog header="Agregar" widgetVar="createModal" id="createModal">
<h:form id="createDialog">
<p:panel header="Detalles del coche">
<h:panelGrid columns="1">
<h:outputLabel value="Marca:"/>
<h:inputText id="marca" value="#{carBean.marca}" required="true"> </h:inputText>
<h:outputLabel value="Modelo"/>
<h:inputText id="modelo"> </h:inputText>
<h:outputLabel value="Precio"/>
<h:inputText id="precio"> </h:inputText>
<h:outputLabel value="Bastidor"/>
<h:inputText id="bastidor"> </h:inputText>
<h:outputLabel value="Potencia"/>
<h:inputText id="potencia"> </h:inputText>
</h:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</h:head>
</html>
Why I cannot used other property that isnĀ“t called "cars"?
Don't mess Lombok #Data autogenerated getters and setters with the one you've declared in the Bean.
You have used a getter as a method, which is not a good thing to do because it can be called multiple times, see: Why JSF calls getters multiple times
public List<CarDTO> getCars() {
cars = carController.getAllCars(); // remove business logic from getter
return cars;
}
Better initialize your private List<CarDTO> cars variable in a method annotated with #PostContruct
#PostConstruct
public void init() {
cars = carController.getAllCars();
}
For more check this example: PrimeFaces DataTable CRUD
The following is my code snippet in my abc.xhtml page :
<p:panelGrid id="pnlGrd_numOfLbl"
style="align:center; width:100%;" cellpadding="5">
<c:forEach var="i" begin="1" end="${specificationMB.numOfLbl}" >
<p:row>
<p:column width="50%">
<p:outputLabel value="Label ${i}" />
</p:column>
<p:column width="50%">
<p:inputText id="inputTxt_${i}" style="width:150px;" />
</p:column>
</p:row>
</c:forEach>
</panelGrid>
This is my panelGrid I am generating inputText dynamically depending
numOfLable. After generation say 2 will be generate user will add some
text to each inputText so my Question is How can I get value of dyanamically
generated inputbox.
Thanks.
This can easily be done with basics of JSF and primefaces. Here is full working Example:
XHTML File (I am using p:panel and ui:repeater)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<link rel=" stylesheet" type="text/css" href="css/style.css"></link>
</h:head>
<h:body>
<h:form>
<p:panel header="Panel">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.lbl} :" />
</p:column>
<p:column width="50%">
<p:inputText value="#{lbl.value}" />
</p:column>
</p:row>
</ui:repeat>
</p:panel>
<p:commandButton actionListener="#{tBean.submit}" value="Subtmi" update="values"></p:commandButton>
<p:outputPanel id="values">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.value} :" />
</p:column>
</p:row>
</ui:repeat>
</p:outputPanel>
</h:form>
</h:body>
</f:view>
<body>
</body>
</html>
Managed Bean
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
#ManagedBean(name = "tBean")
#ViewScoped
public class TestBean {
private List<LabelClass> lblClassess;
public TestBean() {
lblClassess = new ArrayList<LabelClass>();
lblClassess.add(new LabelClass("First Label", ""));
lblClassess.add(new LabelClass("Second Label", ""));
lblClassess.add(new LabelClass("Third Label", ""));
}
public void submit(ActionEvent e) {
for (LabelClass lbl : lblClassess) {
System.out.println(lbl.getValue());
}
}
public List<LabelClass> getLblClassess() {
return lblClassess;
}
public void setLblClassess(List<LabelClass> lblClassess) {
this.lblClassess = lblClassess;
}
}
Label Class
public class LabelClass {
private String lbl;
private String value;
public LabelClass(String lbl, String value) {
super();
this.lbl = lbl;
this.value = value;
}
public String getLbl() {
return lbl;
}
public void setLbl(String lbl) {
this.lbl = lbl;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Output
In order to get the values of your dynamically generated inputTexts. You may do something like this.
<input type="text" id="inputTxt_${i}" name="inputTxt_${i}" style="width:150px;" />
Then retrieve the text value by using this code in servlet
String inputText1 = request.getParameter("nameOfFirstInputText");
You can bind the value into the bean value object:
<input type="text" id="inputTxt_${i}" value="${specificationMB.getValue(i).value}" />
I got some issue regarding Primefaces. There is a requirement that when we change language in my top panel from Engish to Arabic the entire layout should be displayed in right to left position (Like mirror image applying to all inner pages).please help me out.
i am including english version layout,top panel and controller beans.
1.layout
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
<style type="text/css">
.ui-growl{
left:20px;
}
</style>
</h:head>
<body>
<ui:composition template="/home/template/common/commonLayout.xhtml">
<ui:define name="content">
<h:form enctype="multipart/form-data" dir="#{localeControllerBean.direction}" id="form1">
<div id="add">
<p:growl id="msgs" autoUpdate="true" display="icon" style="left:20px"></p:growl>
</div>
<p:panel header="#{msg['sponsor_detail']}">
<h:panelGrid columns="2">
<f:event listener="#{localeControllerBean.islang}" type="preRenderView" />
<p:outputLabel for="sname" value="#{msg['sponsor_name']}"
styleClass="label" />
<p:inputText id="sname" value="#{sponsorBean.sponsor_name}"
required="true" requiredMessage="#{msg['sponsor_name_msg']}"
styleClass="input">
<f:validator validatorId="sponsorValidator" />
</p:inputText>
<p:outputLabel for="sadd" value="#{msg['sponsoraddress']}:"
styleClass="label" />
<p:inputText id="sadd" value="#{sponsorBean.s_address}"
required="true" requiredMessage="#{msg['Sponsor_address_msg']}"
styleClass="input" />
<p:outputLabel for="smb" value="#{msg['sponsor_mbno']}:"
styleClass="label" />
<p:inputText id="smb" value="#{sponsorBean.s_mobile_no}"
required="true" requiredMessage="#{msg['sponsor_mbno_msg']}"
styleClass="input" />
<p:outputLabel for="ss" value="#{msg['sponsor_status']}:" styleClass="label" />
<p:inputText id="ss" value="#{sponsorBean.status}" required="true"
requiredMessage="#{msg['sponsor_mbno_msg']}" styleClass="input" />
</h:panelGrid>
<p:commandButton id="submit" value="#{msg['save']}" ajax="false"
action="#{sponsorBean.save}" style="margin-bottom:50px;"
update="msgs" />
<p:commandButton type="reset" value="#{msg['reset']}"
style="margin-bottom:50px;margin-left:30px;" ajax="false" />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
2.toppanel Here i change language..
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body>
<ui:composition>
<h:form>
<p:growl id="messages" >
<p:toolbar style="Font-size:small;">
<p:toolbarGroup align="left">
<h:outputText value="User : " style=" margin-left:15px;" />
<h:outputText value="#{loginBean.username}">
</h:outputText>
<p:commandButton value="Logout" action="#{loginBean.doLogout}" icon="ui-icon-extlink" />
</p:toolbarGroup>
<p:toolbarGroup align="right">
<p:commandButton value="#{loginBean.toggleButton}" action="#{loginBean.goHome}" icon="ui-icon-home"/>
<p:inputText id="firstname" value="#{manageEmployee.search}" dir="ltr" styleClass="input" style="margin-right:15px" />
<h:selectOneMenu
value="#{manageEmployee.searchFilter}" style="FONT-STYLE: plain; FONT-SIZE:small;margin-right:10px">
<f:selectItem itemLabel="All" itemValue="All" />
<f:selectItem itemLabel="Search by company" itemValue="company" />
<f:selectItem itemLabel="Search by sponsor" itemValue="sponsor" />
</h:selectOneMenu>
<p:commandButton id="submit" value="Search" ajax="false"
action="#{manageEmployee.searchRecords}" update="msgs" style="margin-left:10px" icon="ui-icon-search" />
<h:selectOneMenu value="#{localeBean.language}" onchange="submit()" style="margin-left:10px" >
<f:selectItem itemValue="en" itemLabel="English" />
<f:selectItem itemValue="ar" itemLabel="Arabic" />
</h:selectOneMenu>
</p:toolbarGroup>
</p:toolbar></p:growl>
</h:form>
</ui:composition>
</body>
</html>
3.Local Bean contoller:
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
#ManagedBean
#SessionScoped
public class LocaleBean {
private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
public Locale getLocale() {
return locale;
}
public String getLanguage() {
return locale.getLanguage();
}
public void setLanguage(String language) {
locale = new Locale(language);
FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("user", locale);
// session.setAttribute("language", language);
}
public String save()
{
return "homePage";
}
}
4.Language controller:
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpSession;
#ManagedBean
#SessionScoped
public class LocaleControllerBean {
public static String dir="";
private String direction="";
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public void islang(ComponentSystemEvent event)
{
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
Locale l=(Locale) session.getAttribute("user");
if(l.toString().equals("ar"))
{
// dir="rtl";
setDirection("rtl");
}
else
{
setDirection("ltr");
// dir="ltr";
}
System.out.println("locale"+l);
facesContext.getViewRoot().setLocale(l);
}
}
The RTL support is something new in primefaces. I think it is not possible, just to have the whole page looking like a mirror image without actually recreating the page. The css itself probably will not do it, so you will need to create a separate page (or set of pages) to which you will be redirected after changing your locale.
More about RTL support in primefaces can be found here: http://code.google.com/p/primefaces/issues/detail?id=3890 and as you can see- it is component, by component, rather than global.
I have a datatable with each row having Edit and Delete buttons.
It is almost similar to http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionByColumn.jsf datatable.
When I click on Edit button, if I display the selected row values using <h:outputText> the values are being displayed properly.
But If I want to display it in a input text field using <h:inputText value="#{userCRUDMB.selectedUser.userName}"/> it is throwing error saying selectedUser is resolved as null.
If I only use <h:outputText ...> then userCRUDMB.selectedUser() method is getting called properly.
But If I use <h:inputText ...> in the Dialog, the setter method is not at all getting called.
I am using Mojarra 2.1.6, PrimeFaces 3.0, Apache Tomcat7.0.32.
Any idea why it is happening?
Code: Code is same as http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionByColumn.jsf, except in the dialogue box instead of displaying the text using I am trying to display in input textbox using .
public class User
{
private Integer userId;
private String userName;
private String password;
private String firstname;
private String lastname;
private String email;
private Date dob;
private String gender;
//setters/getters
}
package com.sivalabs.primefacesdemo.managedbeans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.sivalabs.primefacesdemo.model.User;
import com.sivalabs.primefacesdemo.model.UserDataModel;
import com.sivalabs.primefacesdemo.service.SpringContainer;
import com.sivalabs.primefacesdemo.service.UserService;
#ManagedBean(name="UserCRUDMB")
#RequestScoped
public class UserCRUDMB
{
private UserDataModel userDataModel;
private User selectedUser;
private User[] selectedUsers;
public UserCRUDMB()
{
List<User> users = new ArrayList<User>();
for (int i = 0; i < 15; i++) {
User user = new User();
user.setUserId(i);
user.setUserName("userName"+i);
users.add(user);
}
this.userDataModel = new UserDataModel(users);
}
public UserDataModel getUserDataModel() {
return userDataModel;
}
public void setUserDataModel(UserDataModel userDataModel) {
this.userDataModel = userDataModel;
}
public User[] getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(User[] selectedUsers) {
this.selectedUsers = selectedUsers;
}
public User getSelectedUser() {
System.out.println("get-->"+selectedUser);
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
System.out.println("set--->"+selectedUser);
this.selectedUser = selectedUser;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body>
<h:form id="form">
<h:outputText value="PrimeFaces Demo - ShowUsers" />
<p:dataTable value="#{UserCRUDMB.userDataModel}" var="userObj"
selection="#{UserCRUDMB.selectedUsers}"
widgetVar="usersTbl">
<f:facet name="header">UserManagement</f:facet>
<p:column selectionMode="multiple"></p:column>
<p:column headerText="UserId">#{userObj.userId}</p:column>
<p:column headerText="UserName">#{userObj.userName}</p:column>
<p:column>
<p:commandButton value="Edit"
oncomplete="userEditDlg.show()"
update="form:userEditTbl">
<f:setPropertyActionListener target="#{UserCRUDMB.selectedUser}" value="#{userObj}"></f:setPropertyActionListener>
</p:commandButton>
</p:column>
<p:column>
<p:commandButton value="Delete" action="#{UserCRUDMB.deleteUser}"
update="usersTbl"
ajax="true">
<f:setPropertyActionListener target="#{UserCRUDMB.selectedUser}" value="#{userObj}"></f:setPropertyActionListener>
</p:commandButton>
</p:column>
<f:facet name="footer">
<p:commandButton value="Delete Selected" action="#{UserCRUDMB.deleteUsers}"
update="usersTbl"
ajax="true">
</p:commandButton>
</f:facet>
</p:dataTable>
<p:dialog widgetVar="userEditDlg" header="User Edit Form" hideEffect="explode"
minHeight="200" minWidth="300">
<h:panelGrid columns="2" id="userEditTbl" >
<h:outputLabel value="UserId" />
<h:outputText value="#{UserCRUDMB.selectedUser.userId}"/>
<h:outputLabel value="UserName" />
<h:inutText value="#{UserCRUDMB.selectedUser.userName}"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
Thanks,
Siva
If you are using ajax, the request scope ist not the "ideal" scope since the bean will be recreated for each request. This can be the reason that selectedUser is null. Use the view scope (#ViewScoped) instead.
I have facelets page and managed bean that is associated with it.
i have used primefaces components and my problem is i want to get the values selected by the user of each components when a commandbutton is clicked.
when i try to write a JoptionPane or system.out.print it does not work. i have set the commandbutton action property to btnsearchFlight method whcih is found in the managedbean. so any one what is the problem what i am missing. Or an example will be very much appreciated.
Here is the Facelets page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="./resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<title>Airline Travel Planner</title>
</h:head>
<h:body>
<h:form id="form">
<div id="top">
<ui:insert name="top">AirLine Travel Planner</ui:insert>
</div>
<div>
<div id="left">
<ui:insert name="left"></ui:insert>
</div>
<div>
<div id="right">
<ui:insert name="right"></ui:insert>
</div>
<div id="content" class="right_content" style="height: 500px">
<ui:insert name="content">
<p:selectOneRadio binding="#{calendarBean1.rdbTripType}" id="rdbTripType" value="#{calendarBean1.rdbTripType}">
<f:selectItem itemLabel="One Way" itemValue="1" />
<f:selectItem itemLabel="Round Trip" itemValue="2" />
</p:selectOneRadio>
<br/>
<h:outputLabel>From:</h:outputLabel>
<p:selectOneMenu value="#{calendarBean1.cityInfo}" style="" effect="fold" editable="true">
<f:selectItems value="#{calendarBean1.cityInfo}" />
</p:selectOneMenu>
<h:outputLabel style="position: relative">To:</h:outputLabel>
<p:selectOneMenu value="#{calendarBean1.cityInfo}" effect="fold" editable="true">
<f:selectItems value="#{calendarBean1.cityInfo}" />
</p:selectOneMenu>
<br/><br/>
<h:outputLabel>Depart On:</h:outputLabel>
<p:calendar value="#{calendarBean1.date3}" id="popupButtonDepartOn" showOn="button" />
<h:outputLabel>Arrive On:</h:outputLabel>
<p:calendar value="#{calendarBean1.date2}" id="popupButtonArriveOn" showOn="button" />
<br/> <br/>
<h:outputText value="Passenger Type" />
<p:selectOneMenu id="selectOneMenuPassengerType" binding="#{calendarBean1.selectOneMenuPassengerType}" value="#{calendarBean1.selectOneMenuPassengerType}" >
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItem itemLabel="Adult" itemValue="1" />
<f:selectItem itemLabel="Child" itemValue="2" />
<f:selectItem itemLabel="Infant" itemValue="3" />
</p:selectOneMenu>
<br/> <br/>
<p:selectBooleanCheckbox value="#{calendarBean1.lowestFareChecked}" />
<h:outputText value="Lowest Fare" />
<br/>
<p:commandButton id="btnSearchFlight" value="Search" action="#{calendarBean1.searchFlight}" >
</p:commandButton>
Here is the managed bean class
package test.sample;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;
import javax.swing.JOptionPane;
import org.primefaces.component.commandbutton.CommandButton;
import org.primefaces.component.selectonemenu.SelectOneMenu;
import org.primefaces.component.selectoneradio.SelectOneRadio;
import storageMethods.FlightMethod;
/**
*
* #author Nati
*/
#ManagedBean(name = "calendarBean1")
public class CalendarBean1 implements Serializable{
/**
* Creates a new instance of CalendarBean1
*/
public CalendarBean1() {
}
private Date date1;
private Date date2;
private Date date3;
private boolean lowestFareChecked;
public boolean isLowestFareChecked() {
return lowestFareChecked;
}
public void setLowestFareChecked(boolean lowestFareChecked) {
this.lowestFareChecked = lowestFareChecked;
}
public Date getDate1() {
return date1;
}
public void setDate1(Date date1) {
this.date1 = date1;
}
public Date getDate2() {
return date2;
}
public void setDate2(Date date2) {
this.date2 = date2;
}
public Date getDate3() {
return date3;
}
public void setDate3(Date date3) {
this.date3 = date3;
}
private SelectOneRadio rdbTripType = new SelectOneRadio();
public SelectOneRadio getRdbTripType() {
return rdbTripType;
}
public void setRdbTripType(SelectOneRadio rdbTripType) {
this.rdbTripType = rdbTripType;
}
public CommandButton btnSearchFlight = new CommandButton();
public CommandButton getBtnSearchFlight() {
return btnSearchFlight;
}
public void setBtnSearchFlight(CommandButton btnSearchFlight) {
this.btnSearchFlight = btnSearchFlight;
}
private SelectOneMenu selectOneMenuPassengerType = new SelectOneMenu();
public SelectOneMenu getSelectOneMenuPassengerType() {
return selectOneMenuPassengerType;
}
public void setSelectOneMenuPassengerType(SelectOneMenu selectOneMenuPassengerType) {
this.selectOneMenuPassengerType = selectOneMenuPassengerType;
}
public ArrayList<SelectItem> CityInfo;
public ArrayList<SelectItem> getCityInfo() {
CityInfo = CityInfo();
return CityInfo;
}
public void setCityInfo(ArrayList<SelectItem> CityInfo) {
this.CityInfo = CityInfo;
}
public String SearchFlight() {
// JOptionPane.showMessageDialog(null, rdbTripType.getValue().toString());
// JOptionPane.showMessageDialog(null, selectOneMenuPassengerType.getValue().toString());
JOptionPane.showMessageDialog(null,date3);
// System.out.print("hi");
// System.out.print(isLowestFareChecked());
return null;
}
}
Maybe just a typo when posting on stackoverflow, but your method is Capitalized:
SearchFlight
And your action in .xhtml button is lowercase.
action="#{calendarBean1.searchFlight}
Shouldn't it be
public String searchFlight() {
I never used Swing components in a JSf franework. But the system.out should work when commented out. If you method is called. Don't you get any errors in your logs?
I think you mixed webapp development (JSF) with desktop development (Swing). With JSF you don't need to create a backing bean component for every single facelet component. You don't need
org.primefaces.component.commandbutton.CommandButton
org.primefaces.component.selectonemenu.SelectOneMenu
org.primefaces.component.selectoneradio.SelectOneRadio
in your bean if you only want to bind the input values of these components.
Of course in some situations you will get benefits from component binding but it is not necessary in your example.
In the facelet you use the value attribute and the binding attribute, but they have the same content.
If you are only interested in input values, the value attribute is all you need. Let this attribute point to a backing bean field that only will hold the value, e.g. an int or String.