getting values from primefaces components - java

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.

Related

Getting value from dynamically created inputText

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}" />

Get values from Selectiomenu with PrimeFaces

I have the following page xhtml where i have to get some values for populate a DB table. The problem are the selection menu that don't work. Actually, the values of the selections are chosen from the database and are displayed but the values aren't taken when i use the button:
<!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">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form>
<p:panel header="DefaultPackage Form">
<h:panelGrid columns="3" id="regGrid">
<h:outputLabel for="Name">Name:</h:outputLabel>
<p:inputText id="Name" value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<h:outputLabel for="location">Location:</h:outputLabel>
<p:inputText id="location" value="#{addDefaultPackageBean.defpackDTO.location}" />
<p:message for="location" />
<h:selectOneMenu value="#{addDefaultPackageBean.nameFlies}">
<f:selectItems value="#{addDefaultPackageBean.elelisfly}" var="ElementDTO" itemValue="#{ElementDTO.location}" itemLabel="#{ElementDTO.location}"/>
</h:selectOneMenu>
<h:selectOneMenu value="#{addDefaultPackageBean.nameHotels}">
<f:selectItems value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO" itemValue="#{ElementDTO.location}" itemLabel="#{ElementDTO.location}"/>
</h:selectOneMenu>
</h:panelGrid>
<p:commandButton value="Add" update="regGrid" action="#{addDefaultPackageBean.add()}" />
</p:panel>
</h:form>
</h:body>
</html>
The image displayed is:
The bean page:
package beans;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#RequestScoped
public class AddDefaultPackageBean {
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private String nameFlies;
private String nameHotels;
#EJB
private ElementMgr elemMgr;
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
defpackDTO.setElem(new ArrayList<ElementDTO>());
}
#PostConstruct
public void init()
{
setElelisfly(elemMgr.getAllFlights());
setElelishotel(elemMgr.getAllHotels());
}
public String add() {
this.AssignElemFlyFromSelection();
this.AssignElemHotelFromSelection();
defpackMgr.save(defpackDTO);
return "/employee/index?faces-redirect=true";
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public String getNameFlies() {
return nameFlies;
}
public void setNameFlies(String nameFlies) {
this.nameFlies = nameFlies;
}
public String getNameHotels() {
return nameHotels;
}
public void setNameHotels(String nameHotels) {
this.nameHotels = nameHotels;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getLocation()==this.nameFlies)
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getLocation()==this.nameHotels)
{
this.defpackDTO.getElem().add(elem);
}
}
}
}
Thank you for the help!
You're comparing Java String objects using == operator instead of .equals() method. That causes a comparison between Object references to be performed, instead of implemented String comparison.
elem.getLocation()==this.nameFlies
and
elem.getLocation()==this.nameHotels
Change them for String#equals().
See also:
Java String.equals versus ==
Add process to your commandobutton.
Like this:
<p:commandButton process="#form" value="Add" update="regGrid" action="#{addDefaultPackageBean.add()}" />

Re-rendering 3rd field with change event of <rich:calendar>

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.

how to display the mirror image of primefaces layout

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.

p:selectOneMenu value set to null, when in p:inplace in refreshed tab view

I'm using p:tabView to split the editable data into the sections. All edit elements are places inside p:inplace components. The problem is specifically with p:selectOneMenu component.
When the whole tab view is refreshed, the value of the p:selectOneMenu that are on the other tabs as active, are set to null. I don't know why. Is this a bug, or is this a false usage of PrimeFaces componenents?
The environment:
PrimeFaces 3.4
MyFaces 2.0.7
IBM WebSphere 7.0
The way to reproduce the error:
Make a tabView with more that one tab
place in one tab the selectOneMenu inside inplace
make button that will update the tabView
choose the value for selectOneMenu, change the tab, click refresh and return to the tab with selectOneMenu
The code of the sample page and bean:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<f:facet name="first">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</f:facet>
<title>QMWPSUI</title>
<h:outputScript library="qm" name="qmutils.js" />
<h:outputScript library="qmwpsui" name="process.js" />
</h:head>
<h:body>
<h:form id="main">
<p:blockUI block="main" trigger="refreshButton" widgetVar="block">
<p:graphicImage
value="#{resource['primefaces-qmui:images/waitprogress.gif']}" />
</p:blockUI>
<h3>Test</h3>
<p:commandButton id="refreshButton" widgetVar="refreshButton"
action="#{test.refresh}"
icon="ui-icon-refresh" title="#{i18n['action.reload']}"
onclick="block.show()"
update="tabView"/>
<p:tabView id="tabView" orientation="top" dynamic="TRUE">
<p:tab id="tab1" title="Tab 1" process="#this">
<h:outputLabel value="Type*:" for="type"/>
<p:inplace emptyLabel="Click here to change">
<p:selectOneMenu id="typ" value="#{test.type}" effect="fade"
style="width:300px">
<f:selectItem itemLabel="" itemValue="" />
<f:selectItem itemLabel="Type a" itemValue="a" />
<f:selectItem itemLabel="Type b" itemValue="b" />
<f:selectItem itemLabel="Type c" itemValue="c" />
</p:selectOneMenu>
</p:inplace>
</p:tab>
<p:tab id="tab2" title="Tab 2" process="#this">
</p:tab>
<p:tab id="tab3" title="Tab 3" process="#this">
</p:tab>
</p:tabView>
</h:form>
</h:body>
The bean class:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name = "test")
#ViewScoped
public class TestBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(TestBean.class);
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TestBean [");
if (type != null) {
builder.append("type=");
builder.append(type);
}
builder.append("]");
return builder.toString();
}
public void refresh() {
log.info("Refresh");
log.info("Test = <{}>", this);
}
}
you need a converter for this case
public class EmptyToNullConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value) {
Object retorno = value;
if (value == null || value.isEmpty()) {
if (component instanceof EditableValueHolder) {
((EditableValueHolder) component).setSubmittedValue(null);
}
retorno = null;
}
return retorno;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component,
Object value) {
return (value == null) ? null : value.toString();
}
}
and define in your faces-config.xml
<converter>
<converter-for-class>java.lang.String</converter-for-class>
<converter-class>org.converter.EmptyToNullConverter</converter-class>
</converter>

Categories

Resources