I want to change the language on click one of the images. There are two image and one of them is turkish the other one is english. If I click to the english language is english. Another one is turkish with onclick.Here is my managed bean and xhtml;
public class DilSecimBean {
private boolean isTurkey = true;
private final Locale TR = new Locale("tr");
private final Locale EN = Locale.ENGLISH;
public Locale getLocale() {
if (isTurkey) {
return TR;
} else {
return EN;
}
}
public void swapLocale() {
System.out.println("SWAP LOCALE");
switchLocale();
}
private void switchLocale() {
isTurkey = !isTurkey;
Locale newLocale;
if (isTurkey) {
newLocale = TR;
} else {
newLocale = EN;
}
FacesContext.getCurrentInstance().getViewRoot().setLocale(newLocale);
}
}
Here is my xhtml;
<h:panelGrid columns="3" border="0">
<h:outputText value="Dil seçimi : " />
<h:graphicImage alt="JSF"
url="/resimler/tb.png"
width="20" height="20">
<f:ajax event="click" execute="#{dilSecimBean.swapLocale()}"/>
</h:graphicImage>
<h:graphicImage alt="JSFS"
url="/resimler/ib.png"
width="20" height="20">
<f:ajax event="click" execute="#{dilSecimBean.swapLocale()}"/>
</h:graphicImage>
</h:panelGrid>
When I click to the image there is no change on the language.How can I change the language with image click event?
first you should have a form to submit
second: why are yusing ajax here?
any way here is a working example
<h:form>
<h:commandLink action="#{localeChanger.turkishAction}">
<h:graphicImage library="images" name="de_flag.gif"
style="border: 0px; margin-right: 1em;"/>
</h:commandLink>
<h:commandLink action="#{localeChanger.englishAction}">
<h:graphicImage library="images"
name="en_flag.gif" style="border: 0px"/>
</h:commandLink>
</h:form>
for the managed bean:
import java.io.Serializable;
import java.util.Locale;
import javax.inject.Named;
// or import javax.faces.bean.ManagedBean;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
#Named // or #ManagedBean
#SessionScoped
public class LocaleChanger implements Serializable {
public String TurkishAction() {
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(new Locale("tr"));
return null;
}
public String englishAction() {
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(Locale.ENGLISH);
return null;
}
}
Related
Need some help to know if my solution is valid or not.
I have a primefaces datatable with single row selection, and I need to add a multiple selection checkbox column... My idea is to switch selection mode clicking on one button, that switch the selection mode from single to multiple and vice versa....
<pf:dataTable
value="${bean.notifications}"
var="notif"
selection="#{bean.isMultiple() ? consulterCorbeilleBean.selectedNotifs : consulterCorbeilleBean.selectedNotif}"
selectionMode="#{not bean.isMultiple() ? 'single' : ''}"
rowKey="${notification.cle.idNotification}">
<pf:ajax event="rowSelect" disabled="${bean.isMultiple()}"
listener="${bean.function()}" update=":table:notificationTable"
oncomplete="stopPropagationClick()" />
<pf:column selectionMode="multiple" rendered="#{bean.isMultiple()}"/>
</pf:dataTable>
I have a problem with the selection binding. I have this error :
Illegal Syntax for Set Operation:
javax.el.PropertyNotWritableException: /index.xhtml #114,50
selection="#{bean.isMultiple() ? bean.selectedNotifs :
bean.selectedNotif}"
Any idea to workaround ? I use Primefaces 3.2.
Best Regards and thanks for your help :)
You can't use dynamic setter values on the selection.
I would rethink the design if i were you, but if you really need both single and multiple selection options on the same table, you could use 2 datatables and render only 1 of them at a time, and switch between them with a button click.
If you really need it, then you can try this work example
View
<h:form id="form">
<p:growl id="msgs" showDetail="true" for="basicDT" />
<p:inputSwitch value="#{dtSelectionView.multiple}">
<p:ajax listener="#{dtSelectionView.addMessage}" update="basicDT, msgs" />
</p:inputSwitch>
<p:dataTable
id="basicDT"
var="car"
value="#{dtSelectionView.cars1}"
rowStyleClass="#{dtSelectionView.checkSelection(car)? 'ui-state-highlight':''}"
>
<f:facet name="header">
DoubleSelect
</f:facet>
<p:column style="width:32px">
<p:commandButton update="basicDT,:form:msgs,:form:carDetail,:form:multiCarDetail" icon="ui-icon-check" actionListener="#{dtSelectionView.addSelection(car)}" />
</p:column>
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
<p:dialog header="Car Info" widgetVar="carDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" closeOnEscape="true">
<p:outputPanel id="carDetail" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty dtSelectionView.selectedCar}" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{dtSelectionView.selectedCar.id}" />
<h:outputText value="Year" />
<h:outputText value="#{dtSelectionView.selectedCar.year}" />
<h:outputText value="Color:" />
<h:outputText value="#{dtSelectionView.selectedCar.color}" style="color:#{dtSelectionView.selectedCar.color}"/>
<h:outputText value="Price" />
<h:outputText value="$#{dtSelectionView.selectedCar.price}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<p:dialog header="Selected Cars" widgetVar="multiCarDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" width="200">
<p:outputPanel id="multiCarDetail" style="text-align:center;">
<ui:repeat value="#{dtSelectionView.selectedCars}" var="car">
<h:outputText value="#{car.id} - #{car.brand}" style="display:block"/>
</ui:repeat>
</p:outputPanel>
</p:dialog>
</h:form>
Model
import java.io.Serializable;
public class Car implements Serializable{
private String Id;
private String Brand;
private int Year;
private String Color;
private int Price;
private boolean SoldState;
public Car(String id, String brand, int year, String color, int price,
boolean soldState) {
super();
Id = id;
Brand = brand;
Year = year;
Color = color;
Price = price;
SoldState = soldState;
}
#Override
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof Car)) return false;
Car other = (Car) o;
if(! this.Id.equals(other.Id)) return false;
if(! this.Brand.equals(other.Brand)) return false;
if(this.Year != other.Year) return false;
if(! this.Color.equals(other.Color)) return false;
if(this.Price != other.Price) return false;
if(this.SoldState != other.SoldState) return false;
return true;
}
#Override
public int hashCode(){
return (int) Id.hashCode() *
Brand.hashCode() *
Year *
Color.hashCode() *
Price *
(SoldState ? 31 : 32)
;
}
/** getters/setters */
}
Bean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean(name="dtSelectionView")
#ViewScoped
public class SelectionView implements Serializable {
private List<Car> cars1;
private Car selectedCar;
private List<Car> selectedCars;
private boolean multiple= false;
#ManagedProperty("#{carService}")
private CarService service;
#PostConstruct
public void init() {
cars1 = service.createCars(10);/** random generated List. See PF showcase, datatable examples*/
selectedCars = new ArrayList<Car>();
}
public boolean checkSelection(Car car){
if(isMultiple())
return selectedCars.contains(car) ? true : false;
else
return car.equals(selectedCar) ? true : false;
}
public void addSelection(Car car){
String summary = "Car was ";
if(isMultiple())
if(selectedCars.contains(car)){
selectedCars.remove(car);
summary += "removed from list.";
}
else{
selectedCars.add(car);
summary += "added to list.";
RequestContext.getCurrentInstance().execute("PF('multiCarDialog').show();");
}
else
if(car.equals(selectedCar)){
selectedCar = null;
summary += "unselected.";
}
else{
selectedCar = car;
summary += "selected.";
RequestContext.getCurrentInstance().execute("PF('carDialog').show();");
}
FacesContext.getCurrentInstance().addMessage("basicDT", new FacesMessage(summary));
}
public void setService(CarService service) {
this.service = service;
}
public Car getSelectedCar() {
return selectedCar;
}
public List<Car> getSelectedCars() {
return selectedCars;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void addMessage() {
selectedCar = null;
selectedCars = new ArrayList<Car>();
String summary = multiple ? "Checked" : "Unchecked";
FacesContext.getCurrentInstance().addMessage("basicDT", new FacesMessage(summary));
}
public List<Car> getCars1() {
return cars1;
}
public void setCars1(List<Car> cars1) {
this.cars1 = cars1;
}
public CarService getService() {
return service;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
Hope You'll in right direction.
I want to develop a JSF Page which lets user edit a Employee from database. I loaded list of all employees in h:selectOneMenu. and second thing i want that with valueChangeEvent employee detail should be loaded in corresponding h:inputText. but nothing happens with every valueChangeEvent. So, where is the problem in codes.
<?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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<div id="hdr">
<h1>Vinweb Services</h1>
<hr/>
</div>
;
<div id="mnu" style="height: 50px; width: auto; background: skyblue;">
<h:form>
<h:commandLink value="Home" action="index"/>
<h:outputText value=" "/>
<h:commandLink value="Create" action="create"/>
<h:outputText value=" "/>
<h:commandLink value="View" action="view"/>
<h:outputText value=" "/>
<h:commandLink value="Edit" action="edit"/>
</h:form>
</div>
<div id="cnt">
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Select an Employee"/>
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
<h:outputLabel value="Employee Code"/>
<h:inputText value="#{esb.empCode}" required="true"/>
<h:outputLabel value="Employee Name"/>
<h:inputText value="#{esb.empName}" required="true"/>
<h:outputLabel value="Joining Date"/>
<h:inputText value="#{esb.joinDate}" required="true">
<f:convertDateTime pattern="MM/yy"/>
</h:inputText>
<h:outputLabel value="Salary"/>
<h:inputText value="#{esb.salary}" required="true"/>
<h:commandButton value="Update" action="#{esb.updateEmployeeDetail}"/>
</h:panelGrid>
</h:form>
</div>
</h:body>
</html>
Backing Bean:
package ems.bean;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import javax.annotation.Resource;
import javax.faces.event.ValueChangeEvent;
import javax.sql.DataSource;
#Named(value = "esb")
#SessionScoped
public class EmployeeServiceBean implements Serializable {
#Resource(name = "JPA4A")
private DataSource ds;
// Member Declaration
private String empCode;
private String empName;
private Date joinDate;
private long salary;
private ArrayList empList;
// Service Code Segment
// This method will publish all emloyees in table to selectOneMenu
public ArrayList getEmployeeList() throws SQLException{
empList = new ArrayList();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
ResultSet rslt = stmt.executeQuery("SELECT empName FROM Employee");
while(rslt.next()){
empList.add(rslt.getString("empName"));
}
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
return empList;
}
// This method should load selected empoyee's details in inputText fields
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
String qry = "SELECT * FROM Employee WHERE empName = '"+emp+"'";
ResultSet rslt = stmt.executeQuery(qry);
rslt.next();
this.empCode = rslt.getString("empCode");
this.empName = rslt.getString("empName");
this.joinDate = rslt.getDate("joinDate");
this.salary = rslt.getLong("salary");
}
catch(SQLException se) {
se.printStackTrace();
}
finally{
con.close();
}
}
public void updateEmployeeDetail() throws SQLException{
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
boolean rs = stmt.execute("UPDATE Employee SET empCode='"+empCode+"', empName='"+empName+"', joinDate='"+joinDate+"', salary="+salary);
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
}
// Property Getter & Setter code segment
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
The valueChangeListener is the wrong tool for the job.
You're here doing a onchange="submit()" which submits the entire form, including those required fields which in turn caused validation errors which in turn failed to reach your attention because you don't have any <h:message(s)> for them. If you have placed a <h:messages/> inside the form, or have paid more love and attention to server logs, you should have been notified of those required="true" validation errors.
You need <f:ajax listener>.
Replace
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
by
<h:selectOneMenu value="#{esb.empName}">
<f:selectItems value="#{esb.employeeList}"/>
<f:ajax listener="#{esb.loadEmployeeDetail}" render="#form" />
</h:selectOneMenu>
and replace
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
// ...
}
by
public void loadEmployeeDetail() throws SQLException{
String emp = empName; // You can also just use `empName` directly.
// ...
}
See also:
When to use valueChangeListener or f:ajax listener?
i am new on prime faces .I have a user with some attribute i have shown the table of user data . Now the requirement is that, on click of particular user row the data associated with that user must be shown on same window under the table please tell the way to do this i m trying to use layout but the problem is how i can get the data on same window .Give me learing site link if possible doing the same thing or tell me the procedure thanks
package com.poc.faces;
import java.util.Collection;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean
#ViewScoped
public class UserManagedBean {
UserService service = new UserService();
private String username;
private String password;
private String searchUser;
private Collection<User> searchUsersResults;
private User selectedUser;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSearchUser() {
return searchUser;
}
public void setSearchUser(String searchUser) {
this.searchUser = searchUser;
}
public Collection<User> getSearchUsersResults() {
return searchUsersResults = service.getAllUser();
}
public void setSearchUsersResults(Collection<User> searchUsersResults) {
this.searchUsersResults = searchUsersResults;
}
public User getSelectedUser() {
return selectedUser;
}
public String login() {
if ("sas".equalsIgnoreCase(getUsername())
&& "sas".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("User Selected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This home.xhtml
where i am getting the tabledata
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<link href="../css/style.css" type="text/css" rel="stylesheet" />
</h:head>
<h:body>
<p:layout style="min-width:400px;min-height:200px;" id="layout">
<p:layoutUnit position="center">
<h:form prependId="false">
<h:panelGroup layout="block" id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.searchUsersResults}"
var="user" pagination="true" rows="5" styleClass="userTable"
headerClass="userTableHeader"
rowClasses="userTableOddRow,userTableEvenRow"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<!-- <p:ajax event="rowSelect" listener="#{userManagedBean.onRowSelect}"
update=":form:display :form:growl" oncomplete="carDialog.show()" />
<p:ajax event="rowUnselect"
listener="#{userManagedBean.onRowUnselect}" update=":form:growl" /> -->
<p:column>
<f:facet name="header">UserId</f:facet>
<h:outputText value="#{user.userId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Username</f:facet>
<h:outputText value="#{user.username}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">EmailId</f:facet>
<h:outputText value=" #{user.emailId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Phone</f:facet>
<h:outputText value=" #{user.phone}"></h:outputText>
</p:column>
</p:dataTable>
</center>
</h:panelGroup>
</h:form>
<p:layoutUnit position="west" resizable="true" size="100"
minSize="40" maxSize="200">
West
</p:layoutUnit>
</p:layout>
</h:body>
</html>
I don't think there is a component of PF called layoutUnit. are you sure it's not layout?
My h:form contains a p:selectOneMenu component, which has two values single and multiple. The h:form also contains a default p:inputText. My objective is to add multiple p:inputText component only when value multiple is selected. Please see the attached screenshot-
Below is my view, which suppose to send ajax request, whenever icon button is clicked-
<h:form>
<p:panel header="Dynamically Add textbox">
<p:selectOneMenu id="runType" value="#{repeateRun.runType}">
<f:selectItems value="#{repeateRun.runList}" var="runType" itemLabel="#{runType}" itemValue="#{runType}" />
<p:ajax update="outPanel" listener="#{repeateRun.renderComponent}" />
</p:selectOneMenu>
<h:panelGrid id="runList">
<ui:repeat value="#{repeateRun.runs}" var="run">
<p:inputText value="#{run.runValue}" />
</ui:repeat>
</h:panelGrid>
<p:outputPanel id="outPanel">
<p:commandButton update="runList" icon="ui-icon-plusthick" title="Add more" rendered="#{repeateRun.showAddButton}">
<f:ajax render="runList" listener="#{repeateRun.addRun}" />
</p:commandButton>
</p:outputPanel>
</p:panel>
</h:form>
The #ViewScoped #ManagedBean RepeateRun is following-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
#ManagedBean
#ViewScoped
public class RepeateRun implements Serializable {
private static final long serialVersionUID = 1L;
private List<String> runList;
private List<Run> runs;
private int runValue;
private String runType;
private boolean showAddButton = false;
private static final String SINGLE = "Single";
private static final String MULTIPLE = "Multiple";
//Note : Getters Setters are removed while putting here
#PostConstruct
public void initBean() {
this.setRunList(this.populateRunList());
this.setRuns(this.populateRuns());
}
public void addRun() {
if (this.runs == null) {
this.setRuns(this.populateRuns());
} else {
this.runs.add(this.defaultRun());
}
}
public void renderComponent() {
if (this.getRunType().equals(SINGLE)) {
this.setShowAddButton(false);
} else {
this.setShowAddButton(true);
}
}
private List<String> populateRunList() {
List<String> runList = new ArrayList<String>();
runList.add(SINGLE);
runList.add(MULTIPLE);
return runList;
}
private Run defaultRun() {
Run defaultRun = new Run();
defaultRun.setRunValue(1);
return defaultRun;
}
private List<Run> populateRuns() {
List<Run> runs = new ArrayList<Run>();
runs.add(this.defaultRun());
return runs;
}
}
So after selecting the value Multiple in f:selectItems the plus icon button comes but the button is not invoking attached method i.e. addRun. To confirm the method addRun call after clicking, I put some sysout statements in addRun method. I saw that sysout is not flushed. At the same time I saw some xml response in the firebug.
Where is the problem?
The problem was with f:ajax which doesn't work with p:commandButton. Below are the culprit lines-
<p:commandButton update="runList" icon="ui-icon-plusthick" title="Add more" rendered="#{repeateRun.showAddButton}">
<f:ajax render="runList" listener="#{repeateRun.addRun}" />
</p:commandButton>
The above lines should be replaced with below line
<p:commandButton actionListener="#{repeateRun.addRun}" update="runList" icon="ui-icon-plusthick" title="Add more" rendered="#{repeateRun.showAddButton}" />
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
primefaces selectOneMenu doesn’t working when it should
my setPropertyActionListener is not setting the corresponding bean property. I need to get the select public after i click the corresponding delete button (cbViewExcluir) which shows a confirm dialog before delete. Below is my xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition 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"
template="./../../resources/templates/baseTemplate.xhtml">
<ui:define name="content">
<f:view id="vRoot">
<p:fieldset legend="Manage publics">
<h:form id="frmPublics">
<!-- Global messages -->
<p:growl id="gMessages" sticky="false" globalOnly="true" />
<!-- Public list on dataTable -->
<p:dataTable id="dtPublics"
value="#{publicBean.lstPublics}"
paginator="true" rows="5"
rowsPerPageTemplate="5,10"
paginatorPosition="bottom"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
var="actual">
<f:facet name="header">
<p:commandButton id="cbViewNew" value="New" type="button" onclick="dlgNew.show();" />
</f:facet>
<!-- Colunas de edição e exclusão -->
<p:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<p:commandButton id="cbViewEdit"
image="ui-icon-pencil"
title="Edit"
update=":frmEdit:pEditPublic"
oncomplete="dlgEdit.show();">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
<h:outputLabel value="Delete"/>
</f:facet>
<p:commandButton id="cbViewDelete" onclick="dlgDelete.show();"
icon="ui-icon-close" title="Delete">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputLabel id="olViewPublicName" value="#{actual.publicName}"/>
</p:column>
<p:column>
<f:facet name="header">
Public Type
</f:facet>
<h:outputLabel id="olViewPublicType" value="#{actual.publicType}"/>
</p:column>
</p:dataTable>
</h:form>
<!-- New dialog -->
<p:dialog id="dlgNewPublic" widgetVar="dlgNew" modal="true" header="New Public"
resizable="false">
<h:form id="frmNew">
<p:panel id="pNewPublico">
<p:messages id="mNewMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olNewPublicName" value="Name:" for="itNewPublicName"/>
<p:inputText id="itNewPublicName" value="#{publicBean.name}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olNewPublicType" for="somNewPublicType" value="Public type:"/>
<p:selectOneMenu id="somNewPublicType" value="#{publicBean.publicType}" effect="fade"
converter="#{publicBean.converter}"
required="true" requiredMessage="Enter the public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}" var="actual" itemLabel="#{actual.label}" itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgNew.hide()"/>
<p:commandButton id="cbSaveNew" value="Save"
actionListener="#{publicBean.save}"
oncomplete="handleSave(xhr, status, args);"
update=":frmPublics:dtPublics :frmNew :frmPublics:gMessages"
ajax="true"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
<!-- Delete dialog -->
<p:confirmDialog id="dialogDelete" message="Are you sure?"
header="Delete public" severity="alert"
widgetVar="dlgDelete">
<h:form id="frmDelete">
<p:commandButton id="cbDeleteCancel" value="Cancel" onclick="dlgDelete.hide()" type="button" />
<p:commandButton id="cbDeleteContinue" value="Continue"
update=":frmPublics:dtPublics :frmPublics:gMessages"
oncomplete="dlgDelete.hide()"
actionListener="#{publicBean.delete}"/>
</h:form>
</p:confirmDialog>
<!-- Edit dialog -->
<p:dialog id="dialogEdit" widgetVar="dlgEdit" header="Edit public"
resizable="false" modal="true">
<h:form id="frmEdit">
<p:panel id="pEditPublic">
<p:messages id="mEditMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olEditPublicName" value="Name:" for="itEditPublicName"/>
<p:inputText id="itEditPublicName" value="#{publicBean.selectedPublic.publicName}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olEditPublicType" for="somEditPublicType" value="Public type:"/>
<p:selectOneMenu id="somEditPublicType"
value="#{publicBean.selectedPublic.publicType}"
effect="fade"
converter="#{publicBean.converter}"
required="true"
requiredMessage="Select a public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}"
var="actual"
itemLabel="#{actual.label}"
itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgEdit.hide()"/>
<p:commandButton id="cbEditSave" value="Save"
actionListener="#{publicBean.alter}"
oncomplete="dlgEdit.hide();"
update=":frmPublics :frmEdit"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</p:fieldset>
</f:view>
<!-- Javascript callbacks -->
<script type="text/javascript">
function handleSaved(xhr, status, args){
if(args.saved){
dlgNew.hide();
}
}
function handleEdited(xhr, status, args){
if(args.edited){
dlgEdit.hide();
}
}
</script>
</ui:define>
And my bean is as follows:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.siseventos.managed;
import br.siseventos.dao.da.PublicoDAO;
import br.siseventos.dao.da.TipoPublicoDAO;
import br.siseventos.model.TbPublico;
import br.siseventos.model.TdTipoPublico;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "publicoBean")
#SessionScoped
public class PublicoBean {
// Campos
private TipoPublicoDAO daoTipoPublico = null;
private PublicoDAO daoPublico = null;
private String nome;
private List<SelectItem> lstMenuTipoPublico = new ArrayList<SelectItem>();
private TdTipoPublico tipoPublicoSelecionado = null;
private List<TbPublico> lstDataTablePublico = null;
private TbPublico publicoSelecionado;
// Util
private int maximoLinhasTablePublico = 5;
private boolean mostrarMsg = false;
// Construtor
public PublicoBean() {
// Inicializando as daos
daoPublico = new PublicoDAO();
daoTipoPublico = new TipoPublicoDAO();
// Carregando o datatable de publicos
lstDataTablePublico = daoPublico.consultarTodos();
// Carregando o menu de tipos de público
List<TdTipoPublico> l = getDaoTipoPublico().consultarTodos();
Iterator<TdTipoPublico> i = l.iterator();
while (i.hasNext()) {
TdTipoPublico atual = (TdTipoPublico) i.next();
lstMenuTipoPublico.add(new SelectItem(atual, atual.getNmeTipoPublico()));
}
}
public TipoPublicoDAO getDaoTipoPublico() {
return daoTipoPublico;
}
public void setDaoTipoPublico(TipoPublicoDAO daoTipoPublico) {
this.daoTipoPublico = daoTipoPublico;
}
public PublicoDAO getDaoPublico() {
return daoPublico;
}
public void setDaoPublico(PublicoDAO daoPublico) {
this.daoPublico = daoPublico;
}
// Getters e Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<SelectItem> getLstMenuTipoPublico() {
return lstMenuTipoPublico;
}
public void setLstMenuTipoPublico(List<SelectItem> lstMenuTipoPublico) {
this.lstMenuTipoPublico = lstMenuTipoPublico;
}
public TdTipoPublico getTipoPublicoSelecionado() {
return tipoPublicoSelecionado;
}
public void setTipoPublicoSelecionado(TdTipoPublico tipoPublicoSelecionado) {
this.tipoPublicoSelecionado = tipoPublicoSelecionado;
}
public List<TbPublico> getLstDataTablePublico() {
return lstDataTablePublico;
}
public void setLstDataTablePublico(List<TbPublico> lstDataTablePublico) {
this.lstDataTablePublico = lstDataTablePublico;
}
public int getMaximoLinhasTablePublico() {
return maximoLinhasTablePublico;
}
public void setMaximoLinhasTablePublico(int maximoLinhasTablePublico) {
this.maximoLinhasTablePublico = maximoLinhasTablePublico;
}
public boolean isMostrarMsg() {
return mostrarMsg;
}
public void setMostrarMsg(boolean mostrarMsg) {
this.mostrarMsg = mostrarMsg;
}
public TbPublico getPublicoSelecionado() {
return publicoSelecionado;
}
public void setPublicoSelecionado(TbPublico publicoSelecionado) {
this.publicoSelecionado = publicoSelecionado;
}
// Actions e listeners
public void cadastrarPublico(ActionEvent ex) {
FacesContext contexto = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
try {
TbPublico p = new TbPublico();
p.setNmePublico(getNome());
p.setTdTipoPublico(getTipoPublicoSelecionado());
getDaoPublico().incluir(p);
// Carregar a lista de publicos novamente
lstDataTablePublico = getDaoPublico().consultarTodos();
// Mostrando msg de sucesso!
msg.setSummary("Público cadastrado com sucesso!");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
// Invocando script no cliente
RequestContext rc = RequestContext.getCurrentInstance();
rc.addCallbackParam("salvo", true);
} catch (Exception e) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}
}
public void excluirPublico(ActionEvent e) {
FacesMessage msg = new FacesMessage();
FacesContext contexto = FacesContext.getCurrentInstance();
// Mostrando msg de sucesso!
msg.setSummary(publicoSelecionado.getNmePublico());
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
/*try {
// Excluindo o publico selecionado
daoPublico.excluir(getPublicoSelecionado().getIdtPublico());
} catch (Exception ex) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}*/
}
public void alterarPublico() {
FacesMessage msg = new FacesMessage("Publico alterado!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// Converters
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Transformar string em objeto
TdTipoPublico r = null;
try {
r = getDaoTipoPublico().consultarPorIdt(Integer.parseInt(value));
} catch (NumberFormatException e) {
}
return r;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Transformar objeto em string
String r = null;
if (value instanceof TdTipoPublico) {
r = ((TdTipoPublico) value).getIdtTipoPublico().toString();
}
return r;
}
};
}
}
There is something i'm doing wrong?
its because of the attribute type="button" which is not firing the actionlistener.
when you declare this attribute (type="button") its not a p:commandButton anymore.
type="button" is push button purposes, it does not do any action or submit the form
try to remove type="button" attribute. it'd fire the actionlistener.
<p:commandButton id="cbViewExcluir"
image="ui-icon-circle-close"
onclick="dlgExcluir.show()"
title="Excluir"
update=":frmExcluir">
<!-- This is not working properly -->
<f:setPropertyActionListener value="#{atual}" target="# {publicoBean.publicoSelecionado}" />
</p:commandButton>
lemme know if this helps :)