p:selectonemenu not working (JSF) - jsf

I have this problem.
I wanted to create selectOneMenu for custom select some data. But it's not working and i really don't know why. I spent cca 5 hours with this problem. I'm so desperate.
So some my code:
But when i will pick some item from selectonemenu, selected_id is still 0. Still, still. I tried to do almost everything but without result.
I tried this:
<p:selectOneMenu value="#{medicinesBean.selectedBranch}" required="true" effect="fade" id="listComboBox">
<f:selectItems value="#{medicinesBean.branchesForComboBox}" var="itm" itemLabel="#{itm.name}" itemValue="#{itm.id}" />
</p:selectOneMenu>
Backing Bean class:
/* private members */
private ArrayList<BranchDTO> branchesForComboBox = new ArrayList<BranchDTO>();
private BranchDTO selectedBranch;
/* getter and setters ... */
also i tried this with SelectItem[] model but result was same. NOT WORK.
Then i tried it like:
<p:selectOneMenu value="#{medicinesBean.selected_id}" required="true" effect="fade" id="listComboBox">
<f:selectItem itemLabel="First" itemValue="1"/>
<f:selectItem itemLabel="Second" itemValue="2"/>
<f:selectItem itemLabel="Third" itemValue="3"/>
<f:selectItem itemLabel="Fouth" itemValue="4"/>
</p:selectOneMenu>
/* private members */
private int selected_id;
But still 0. When i used object like value for selectonemenu, always null exception was always returned. So i will be glad for any advice for this.
Thanks
brw. backing bean is ViewScoped and data from DAO are correctly returned so some bug will be in component selectonemenu.
Thanks BalusC, so here is my implementation
Backing Bean
/**
* #author Sajmon
*/
package OraclBeans;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import EJBs.ZoznamLiekovEJB;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="zoznamLiekovBean")
#ViewScoped
public class ZoznamLiekovBean implements Serializable {
#EJB
private ZoznamLiekovEJB listOfMedicineEJB;
/* private members */
private ArrayList<ZoznamLiekovDTO> listOfMedicines;
private ArrayList<PobockaDTO> branchesForCombobox = new ArrayList<PobockaDTO>();
private ZoznamLiekovDTO selectedItem;
private PobockaDTO selectedBranch;
//private SelectItem[] branchesOptions;
//private SelectItem selectedOption;
private int selected_id;
public ZoznamLiekovBean() {
}
#PostConstruct
private void init() {
branchesForCombobox = listOfMedicineEJB.getBranches();
listOfMedicines = listOfMedicineEJB.getLists();
}
public void test() {
System.out.println("ID: " + selected_id);
}
/*
private SelectItem[] addItemsToOptions() {
SelectItem[] data = new SelectItem[branchesForCombobox.size()];
for (int i = 0; i < branchesForCombobox.size(); i++) {
data[i] = new SelectItem(branchesForCombobox.get(i).getId(), branchesForCombobox.get(i).getNazov());
}
return data;
}
*/
/* getters and setters */
/*
public SelectItem[] getBranchesOptions() {
return branchesOptions;
}
public void setBranchesOptions(SelectItem[] branchesOptions) {
this.branchesOptions = branchesOptions;
}
public void setSelectedOption(SelectItem selectedOption) {
this.selectedOption = selectedOption;
}
public SelectItem getSelectedOption() {
return selectedOption;
}
*/
public ArrayList<PobockaDTO> getBranchesForCombobox() {
return branchesForCombobox;
}
public void setBranchesForCombobox(ArrayList<PobockaDTO> branchesForCombobox) {
this.branchesForCombobox = branchesForCombobox;
}
public ArrayList<ZoznamLiekovDTO> getListOfMedicines() {
return listOfMedicines;
}
public void setListOfMedicines(ArrayList<ZoznamLiekovDTO> listOfMedicines) {
this.listOfMedicines = listOfMedicines;
}
public PobockaDTO getSelectedBranch() {
return selectedBranch;
}
public void setSelectedBranch(PobockaDTO selectedBranch) {
this.selectedBranch = selectedBranch;
}
public ZoznamLiekovDTO getSelectedItem() {
return selectedItem;
}
public void setSelectedItem(ZoznamLiekovDTO selectedItem) {
this.selectedItem = selectedItem;
}
public int getSelected_id() {
return selected_id;
}
public void setSelected_id(int selected_id) {
this.selected_id = selected_id;
}
}
EJB:
/**
* #author Sajmon
*/
package EJBs;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import OraclDAO.OracleZoznamLiekovDAO;
import java.io.Serializable;
import java.util.ArrayList;
import javax.ejb.Stateless;
#Stateless
public class ZoznamLiekovEJB implements Serializable {
private OracleZoznamLiekovDAO dao = new OracleZoznamLiekovDAO();
public ArrayList<ZoznamLiekovDTO> getLists() {
return dao.getListOfMedicines();
}
public ArrayList<PobockaDTO> getBranches() {
return dao.getBranchesForCombobox();
}
}
DAO:
/**
* #author Sajmon
*/
package OraclDAO;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import OraclDAOFactory.OracleDAOFactory;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OracleZoznamLiekovDAO implements Serializable {
private String SELECT_ALL = "SELECT Z.id_zoznamu, P.nazov_pobocky, L.nazov_lieku FROM Zoznam_liekov Z "
+ "JOIN Pobocka P ON (Z.id_pobocky = P.id_pobocky)"
+ "JOIN Liek L ON (Z.id_lieku = L.id_lieku)";
private String SELECT_BRANCHES = "SELECT DISTINCT P.id_pobocky, P.nazov_pobocky FROM Zoznam_liekov Z JOIN Pobocka P ON (Z.id_pobocky = P.id_pobocky)";
public OracleZoznamLiekovDAO() {
}
public ArrayList<PobockaDTO> getBranchesForCombobox() {
ArrayList<PobockaDTO> data = new ArrayList<PobockaDTO>();
PobockaDTO item;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OracleDAOFactory.getOracleDatabaseConnection();
ps = con.prepareStatement(SELECT_BRANCHES);
rs = ps.executeQuery();
while (rs.next()) {
item = new PobockaDTO();
item.setId(rs.getInt(1));
item.setNazov(rs.getString(2));
data.add(item);
}
System.out.println("Data imported to list successfully.");
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return data;
}
public ArrayList<ZoznamLiekovDTO> getListOfMedicines() {
ArrayList<ZoznamLiekovDTO> data = new ArrayList<ZoznamLiekovDTO>();
ZoznamLiekovDTO item;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OracleDAOFactory.getOracleDatabaseConnection();
ps = con.prepareStatement(SELECT_ALL);
rs = ps.executeQuery();
while (rs.next()) {
item = new ZoznamLiekovDTO();
item.setId(rs.getInt(1));
item.getPobocka().setNazov(rs.getString(2));
item.getLiek().setNazov(rs.getString(3));
data.add(item);
}
System.out.println("List of Medicines imported successfully.");
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return data;
}
}
And XHTML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Zoznam liekov - prehľad</title>
<link rel="stylesheet" type="text/css" href="../style.css" />
</h:head>
<h:body>
<div id="out">
<h:form id="mainForm">
<p:selectOneMenu value="#{zoznamLiekovBean.selected_id}" required="true" effect="fade" id="zoznamComboBox">
<f:selectItems value="#{zoznamLiekovBean.branchesForCombobox}" var="itm" itemLabel="#{itm.nazov}" itemValue="#{itm.id}"/>
</p:selectOneMenu>
<p:commandButton immediate="true" styleClass="submitClass" value="Generuj zoznam" update="dialogText" actionListener="#{zoznamLiekovBean.test()}"/>
<p:dataTable style="width: 1100px" widgetVar="zoznamLiekovTable" selection="#{zoznamLiekovBean.selectedItem}" selectionMode="single" rowKey="#{item.id}" var="item" value="#{zoznamLiekovBean.listOfMedicines}" rows="5" rowsPerPageTemplate="5,10,15,20"
paginator="true" paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink}">
<p:column>
<f:facet name="header">ID:</f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column>
<f:facet name="header">Pobočka:</f:facet>
<h:outputText value="#{item.pobocka.nazov}"/>
</p:column>
<p:column>
<f:facet name="header">Liek:</f:facet>
<h:outputText value="#{item.liek.nazov}"/>
</p:column>
</p:dataTable>
<p:dialog widgetVar="test" showEffect="explode" hideEffect="explode">
<h:outputText id="dialogText" value="#{zoznamLiekovBean.selected_id}"/>
</p:dialog>
</h:form>
</div>
</h:body>
</html>

Remove immediate="true" from the commandButton. You are skipping the whole Apply Request Value phase - Update Model value phase with that. That's why your value is always null or 0.
Check this out

Related

Update variable retrieved form the database after submitting

I have 2 classes Games and Fouls, there are lot of fouls in a game. The user sends a parameter with the game id to find the game he want and after that the currentGame variable is created.Its type is Game. I have a datatable which prints the fouls in the current game
The setCurentGame setter is called form the body of the page onload.
so far everything works okay, but when I add a new foul, is not added to the datatable, my assumption is that the game was already retrieved (because current game was created before) so the new foul is in the database and not in the Game currentGame.
Is there any way that i can update the currentGame every time a foul i added?
I have tried refreshing the page and even to call the seeter again after creating the foul but nothing worked
The datatable looks like this:
<p:dataTable id="datalist" value="#{gameController.currentGame.foulCollection}" var="item">
<f:facet name="{exporters}">
</f:facet>
<p:ajax event="rowSelect" update="createButton viewButton editButton deleteButton"/>
<p:ajax event="rowUnselect" update="createButton viewButton editButton deleteButton"/>
<p:column width="32" sortBy="#{item.id}" filterBy="#{item.id}">
<f:facet name="header">
<h:outputText value="#{bundle.ListFoulTitle_id}"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column sortBy="#{item.quarter}" filterBy="#{item.quarter}">
<f:facet name="header">
<h:outputText value="#{bundle.ListFoulTitle_quarter}"/>
</f:facet>
<h:outputText value="#{item.quarter}"/>
</p:column>
<p:column sortBy="#{item.foultime}" filterBy="#{item.foultime}">
<f:facet name="header">
<h:outputText value="#{bundle.ListFoulTitle_foultime}"/>
</f:facet>
<h:outputText value="#{item.foultime}"/>
</p:column>
<f:facet name="footer">
<p:commandButton id="createButton" icon="ui-icon-plus" value="#{bundle.Create}" actionListener="#{foulController.prepareCreate}" update=":FoulCreateForm" oncomplete="PF('FoulCreateDialog').show()"/>
</f:facet>
</p:dataTable>
GameController bean:
package onisiforos.fouls.classes;
import onisiforos.fouls.db.Game;
import onisiforos.fouls.classes.util.JsfUtil;
import onisiforos.fouls.classes.util.JsfUtil.PersistAction;
import onisiforos.fouls.bean.GameFacade;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
#Named("gameController")
#SessionScoped
public class GameController implements Serializable {
#EJB
private onisiforos.fouls.bean.GameFacade ejbFacade;
private List<Game> items = null;
private Game selected;
private Game currentGame;
public Game getCurrentGame() {
return currentGame;
}
public void setCurrentGame() {
int gid =
Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("gameid"));
Game cg = getGame(gid);
this.currentGame = cg;
}
public GameController() {
}
public Game getSelected() {
return selected;
}
public void setSelected(Game selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private GameFacade getFacade() {
return ejbFacade;
}
public Game prepareCreate() {
selected = new Game();
initializeEmbeddableKey();
return selected;
}
public void create() {
setCurrentGame()
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("GameCreated"));
updateCurrentGame();
if (!JsfUtil.isValidationFailed()) {
items = null;
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("GameUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("GameDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null;
}
}
public List<Game> getGames() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public Game getGame(java.lang.Integer id) {
return getFacade().find(id);
}
public List<Game> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<Game> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
#FacesConverter(forClass = Game.class)
public static class GameControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
GameController controller = (GameController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "gameController");
return controller.getGame(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Game) {
Game o = (Game) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Game.class.getName()});
return null;
}
}
}
}
It seems your setCurrentGame method will not be called, you can manually call it in your create() method to update the current game object from the database after the foul is created.

onRowEdit(RowEditEvent event) in prime faces is not getting me updated value [duplicate]

This question already has an answer here:
Edited/updated values in p:dataTable rowEdit are not available in listener method as they are being overwritten by existing data from database
(1 answer)
Closed 7 years ago.
I am trying to update the row using the jsf with primefaces here is my code for each files but when I debug I am not getting updated value it gives me an old value every-time and persist it same as an old one.
user-type.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: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>
</h:head>
<h:body style="align:center;">
<div style="width: 100%">
<h:form id="form">
<div style="float: left; width: 54%;">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="userTypesTbl" var="varUserType"
value="#{userTypeTabMenuBean.userTypeMasters}" editable="true"
style="margin-bottom:20px" rowIndexVar="rowIndex">
<f:facet name="header">User Type Managging</f:facet>
<p:ajax event="rowEdit" listener="#{userTypeTabMenuBean.onRowEdit}"
update=":form:msgs" />
<p:ajax event="rowEditCancel"
listener="#{userTypeTabMenuBean.onRowCancel}" update=":form:msgs" />
<p:column headerText="Sr.">
#{rowIndex+1}.
</p:column>
<p:column headerText="Type">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{varUserType.type}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{varUserType.type}" style="width:100%"
label="type" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">View</f:facet>
<p:commandButton update=":form" oncomplete="userTypeDialog.show()"
icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{userType}"
var="#{selectedUserType}"
target="#{userTypeTabMenuBean.selectedUserType}" />
</p:commandButton>
</p:column>
<p:column style="width:32px;">
<f:facet name="header">Edit</f:facet>
<p:rowEditor />
</p:column>
<p:column style="width:32px;align-items: center;">
<f:facet name="header">Delete</f:facet>
<h:commandLink
action="#{userTypeTabMenuBean.deleteAction(varUserType)}">
<h:graphicImage library="images" name="delete.png" height="45%"
width="50%" />
</h:commandLink>
</p:column>
</p:dataTable>
<ui:debug hotkey="x" />
<p:dialog header="User type detail" widgetVar="userTypeDialog"
resizable="false" width="330" showEffect="explode"
hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="ID : " />
<h:outputText value="#{userTypeTabMenuBean.selectedUserType.id}" />
<h:outputText value="TYPE: " />
<h:outputText value="#{userTypeTabMenuBean.selectedUserType.type}" />
</h:panelGrid>
</p:dialog>
</div>
<div style="float: right; width: 44%;">
<p:panel menuTitle="Add User Type." header="Add User Type.">
<h:outputText value="User type *:" />
<p:inputText value="#{userTypeTabMenuBean.userType}"
title="Enter User Type.." id="myUserType"
style="margin:0px 10px 0px 10px;"></p:inputText>
<p:commandButton value="Add Type"
action="#{userTypeTabMenuBean.saveAction}" ajax="false">
</p:commandButton>
</p:panel>
</div>
</h:form>
</div>
</h:body>
</html>
UserTypeTabMenuBean.java
package com.convoy.gpack.managedbean;
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import com.convoy.gpack.dao.UserTypeMasterDAO;
import com.convoy.gpack.pack.models.UserTypeMaster;
#ManagedBean(name = "userTypeTabMenuBean")
#SessionScoped
public class UserTypeTabMenuBean implements Serializable {
private static final long serialVersionUID = 1467465633405172689L;
private static final Logger logger = Logger
.getLogger(UserTypeTabMenuBean.class);
private List<UserTypeMaster> userTypeMasters;
private UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
private UserTypeMaster selectedUserType;
private String userType;
public List<UserTypeMaster> getUserTypeMasters() {
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
logger.info("getUserTypeMasters=" + userTypeMasters);
return userTypeMasters;
}
public String deleteAction(UserTypeMaster userTypeMaster) {
logger.info("Deleting the object with id = " + userTypeMaster.getId());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
int result = userTypeMasterDAO.deleteUserType(userTypeMaster);
userTypeMasters.remove(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage(
"User type deleted successfuly.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to delete user types.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
public void onRowEdit(RowEditEvent event) {
UserTypeMaster userTypeMaster = (UserTypeMaster) event.getObject();
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
userTypeMasterDAO.saveOrUpdateUserTypeMaster(userTypeMaster);
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
FacesMessage msg = new FacesMessage("Edited type ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Editing Cancelled for ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public UserTypeMaster getSelectedUserType() {
return selectedUserType;
}
public void setSelectedUserType(UserTypeMaster selectedUserType) {
this.selectedUserType = selectedUserType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void saveAction() {
logger.info("Saving the object to database...." + userType);
if (userType.trim().length() < 1) {
FacesMessage msg = new FacesMessage("Can not save empty user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
UserTypeMaster userTypeMaster = new UserTypeMaster();
userTypeMaster.setType(userType);
int result = userTypeMasterDAO
.saveOrUpdateUserTypeMaster(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage("User type saved.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to save user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
UserTypeMasterDAO.java
package com.convoy.gpack.dao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.convoy.gpack.hibernate.util.HibernateUtil;
import com.convoy.gpack.pack.models.UserTypeMaster;
public class UserTypeMasterDAO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4005898944892506760L;
public UserTypeMaster getUserTypeById(long long1) {
return null;
}
public List<String> getAllUserTypesInString() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(UserTypeMaster.class);
#SuppressWarnings("unchecked")
List<UserTypeMaster> userTypeMasters = criteria.list();
List<String> userTypeMastersString = new ArrayList<String>();
for (UserTypeMaster userTypeMaster : userTypeMasters) {
userTypeMastersString.add(userTypeMaster.getType());
}
transaction.commit();
session.close();
return userTypeMastersString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<UserTypeMaster> getAllUserTypes() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(UserTypeMaster.class);
#SuppressWarnings("unchecked")
List<UserTypeMaster> userTypeMasters = criteria.list();
transaction.commit();
session.close();
return userTypeMasters;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int saveOrUpdateUserTypeMaster(UserTypeMaster userTypeMaster) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
userTypeMaster.setType(userTypeMaster.getType().toUpperCase());
session.saveOrUpdate(userTypeMaster);
transaction.commit();
session.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public int deleteUserType(UserTypeMaster userTypeMaster) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(userTypeMaster);
transaction.commit();
session.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
Thanks in advance ~ :)
Think it might be because of the database values list
#{userTypeTabMenuBean.userTypeMasters}
this always retrieves from the database and that is why getObject() returned an old value ( actually the value from the database)
update the method getUserTypeMasters() as follows
if (userTypeMasters == null){
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
}
return userTypeMasters ;
Exactly Primefaces follows strict structure and I think it is compulsory to add init() method with #PostConstruct annotation.
#PostConstruct
public void init(){
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
}
Here is the solution.
package com.convoy.gpack.managedbean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import com.convoy.gpack.dao.UserTypeMasterDAO;
import com.convoy.gpack.pack.models.UserTypeMaster;
#ManagedBean(name = "userTypeTabMenuBean")
#SessionScoped
public class UserTypeTabMenuBean implements Serializable {
private static final long serialVersionUID = 1467465633405172689L;
private static final Logger logger = Logger
.getLogger(UserTypeTabMenuBean.class);
private List<UserTypeMaster> userTypeMasters;
private UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
private UserTypeMaster selectedUserType;
private String userType;
// This is the required method to get the datatable list.
#PostConstruct
public void init() {
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
logger.info("getUserTypeMasters=" + userTypeMasters);
}
public List<UserTypeMaster> getUserTypeMasters() {
return userTypeMasters;
}
public String deleteAction(UserTypeMaster userTypeMaster) {
logger.info("Deleting the object with id = " + userTypeMaster.getId());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
int result = userTypeMasterDAO.deleteUserType(userTypeMaster);
userTypeMasters.remove(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage(
"User type deleted successfuly.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to delete user types.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
public void onRowEdit(RowEditEvent event) {
UserTypeMaster userTypeMaster = (UserTypeMaster) event.getObject();
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
userTypeMasterDAO.saveOrUpdateUserTypeMaster(userTypeMaster);
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
FacesMessage msg = new FacesMessage("Edited type ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Editing Cancelled for ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public UserTypeMaster getSelectedUserType() {
return selectedUserType;
}
public void setSelectedUserType(UserTypeMaster selectedUserType) {
this.selectedUserType = selectedUserType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void saveAction() {
logger.info("Saving the object to database...." + userType);
if (userType.trim().length() < 1) {
FacesMessage msg = new FacesMessage("Can not save empty user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
UserTypeMaster userTypeMaster = new UserTypeMaster();
userTypeMaster.setType(userType);
int result = userTypeMasterDAO
.saveOrUpdateUserTypeMaster(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage("User type saved.");
FacesContext.getCurrentInstance().addMessage(null, msg);
init();
} else if (result == -2) {
FacesMessage msg = new FacesMessage("User type already exist..");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to save user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
That's it~ :)
Thanks #Swathi for the hint.

Update Datalist value in primefaces

i am using primefaces datalist , it contains list binded with it ,, datalist contains radio button i want to change / update values of that binded list i tried this code but its not working
<p:dataList var="question" value="#{formTableBean.question}"
type="definition" >
<h:outputText value="#{question.text}"
style="font-size:14px;font-weight:bold" />
<h:panelGrid columns="2" width="100%" style="margin-bottom:10px"
cellpadding="10">
<h:outputText value="Options: " />
<p:selectOneRadio id="options" value="#{question.answer}" >
<f:selectItem itemLabel="Strongly Agree" itemValue="1" />
<f:selectItem style="margin-right:20px" itemLabel="Agree"
itemValue="2" />
<f:selectItem style="margin-right:20px" itemLabel="Disagree"
itemValue="3" />
<f:selectItem itemLabel="Strongly Disagree" itemValue="4" />
<p:spacer width="100"></p:spacer>
</p:selectOneRadio>
</h:panelGrid>
</p:dataList>
bean class package Bean;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import DAO.Dao;
import DTO.FormDTO;
import DTO.QuestionDTO;
#ManagedBean
#ViewScoped
public class FormTableBean {
FormDTO selectedForm;
List<QuestionDTO> question;
public List<QuestionDTO> getQuestion() {
return question;
}
public void setQuestion(List<QuestionDTO> question) {
this.question = question;
}
public FormDTO getSelectedForm() {
return selectedForm;
}
public void setSelectedForm(FormDTO selectedForm) {
this.selectedForm = selectedForm;
}
boolean renderFormPanal = false;
public boolean getRenderFormPanal() {
return renderFormPanal;
}
public void setRenderFormPanal(boolean renderFormPanal) {
this.renderFormPanal = renderFormPanal;
}
List<FormDTO> formList;
public List<FormDTO> getFormList() {
return formList;
}
public void setFormList(List<FormDTO> formList) {
this.formList = formList;
}
Dao daoclass = new Dao();
public FormTableBean() {
User u = getCurrentUser();
String email = u.getEmailAddress();
int eid = daoclass.emailToEid(email);
formList = new ArrayList<FormDTO>();
formList = daoclass.getAllForm(eid);
}
protected User getCurrentUser() {
User u = null;
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext externalContext = fc.getExternalContext();
Long id = Long.parseLong(externalContext.getUserPrincipal().getName());
try {
u = UserLocalServiceUtil.getUserById(id);
} catch (com.liferay.portal.kernel.exception.PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (com.liferay.portal.kernel.exception.SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return u;
}
public void showForm() {
question = new ArrayList<QuestionDTO>();
setRenderFormPanal(true);
int formid = selectedForm.getFid();
question = daoclass.getQuestion(formid);
}
public void saveForm() {
for (int i = 0; i < question.size(); i++) {
System.out.print("QID:"+question.get(i).getAnswer());
}
}
}
i want to get answers value updated in list .please help me
Use Ajax on p:selectOneRadio to submit the answer every time user selects an answer.
<p:selectOneRadio id="options" value="#{question.answer}" >
<p:ajax event="valueChange" update="any_component's_id_you_want_to_update" />
....
....
</p:selectOneRadio>

PrimeFaces get all row value of datatable

I am new for prime face. I had a checkbox and textbox value on dataTable.And dataTable will load data from database. Please see my code below
text.xhtml
<?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:c="http://java.sun.com/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="../templates/layout.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:event type="preRenderView" listener="#{kooBean.initEdit}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h:form prependId="false" id="growlForm">
<p:growl id="growl" showDetail="#{applicationBean.isShowDetailMessage()}" />
</h:form>
<h:form id="form">
<p:dataTable id="list" value="#{kooBean.model}" lazy="true" var="kooTable"
rendered="#{kooBean.dataVisible}" paginatorTemplate=" {CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,25,50" rows="10" sortBy="#{kooTable.id}" selection="#{kooBean.selectedCars}"
rowKey=" #{kooTable.id}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:10%;text-align:center" />
<p:column headerText="Description" >
#{kooTable.description}
<p:inputText value=" #{kooTable.param_str}" />
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
bean.java
package my.com.mesiniaga.sphere.web;
import static my.com.mesiniaga.sphere.domain.KooPredicate.nameLike;
import my.com.mesiniaga.sphere.domain.KooTable;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.model.LazyDataModel;
import org.springframework.roo.addon.jsf.managedbean.RooJsfManagedBean;
import org.springframework.roo.addon.serializable.RooSerializable;
import my.com.mesiniaga.sphere.service.KooService;
import my.com.mesiniaga.sphere.service.QueryDslSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.Date;
import com.mysema.query.types.Predicate;
#RooSerializable
#RooJsfManagedBean(entity = KooTable.class, beanName = "kooBean")
public class KooBean {
private KooTable kooTable = new KooTable();
private String attribute;
private List<String> cols;
public String userId;
public String emailNotification;
private boolean addGroup = false;
private boolean editGroup = false;
private boolean addGroupUser = false;
private KooTable selectedCar;
private KooTable[] selectedCars;
private final LazyDataModel<KooTable> model = new AbstractQueryDslJpaLazyDataModel<KooTable>() {
#Override
public Predicate getPredicate(){
// LOG.info(getKooTable().getName());
return nameLike(getKooTable().getDescription());
}
//
#Override
public QueryDslSupport<KooTable> getQueryDslSupport(){
return kooService;
}
};
public LazyDataModel<KooTable> getModel() {
return model;
}
public String getUserId() {
return userId;
}
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
public String getEmailNotification() {
return emailNotification;
}
//
// public void setEmailNotification(String emailNotification) {
// this.emailNotification = emailNotification;
// }
public List<String> getCols() {
return cols;
}
public void setCols(List<String> cols) {
this.cols = cols;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public boolean isAddGroup() {
return addGroup;
}
public void setAddGroup(boolean addGroup) {
this.addGroup = addGroup;
}
public boolean isEditGroup() {
return editGroup;
}
public void setEditGroup(boolean editGroup) {
this.editGroup = editGroup;
}
public boolean isAddGroupUser() {
return addGroupUser;
}
public void setAddGroupUser(boolean addGroupUser) {
this.addGroupUser = addGroupUser;
}
public void initCreatePage() {
//Initialize user group listing page
cols = new ArrayList<String>();
cols.add("id");
cols.add("description");
// displayGroupsList();
if (!FacesContext.getCurrentInstance().isPostback()) {
// if (FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("edit") != null) {
// LOG.info("EDIT....");
// attribute = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer");
// initEdit();
// editGroup = true;
// } else if (FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("create") != null) {
// LOG.info("CREATE....");
// addGroup = true;
// }
}
}
//
// public String displayGroupsList() {
// findAllGroupses();
// return LIST_NAVIGATION_PAGE;
// }
//
// public String cancelCreateGroup(){
// return LIST_NAVIGATION_PAGE;
// }
//
// public String createGroup() {
// String message = "";
// try {
//
// if (groups.getId() != null) {
// //submit response inquiry
//
// groupsService.responseInquiry(groups);
// message = "message_successfully_updated";
// } else {
// groups.setDescription("none");
// groups.setUpdatedby(1L);
// groups.setUpdatedon(new Date());
// groupsService.create(groups);
// message = "message_successfully_created";
// }
// } catch (NestedRuntimeException e) {
// LOG.error(e.getMostSpecificCause().getMessage(), e);
// message = "Failed to update";
// FacesMessage facesMessage = new FacesMessage(message);
// facesMessage.setDetail(e.getMostSpecificCause()
// .getLocalizedMessage());
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
// return null;
// }
// FacesMessage facesMessage = MessageFactory.getMessage(message,
// "groups");
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
// // FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
//// reset();
// return LIST_NAVIGATION_PAGE;
// }
public void initEdit() {
System.out.println("init edit !");
// String groupId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("groupId");
// if (groupId != null) {
// addGroupUser = true;
// groupsWithTask = groupsService.findGroupsWithTask(Long.valueOf(groupId));
// groups = groupsWithTask.getGroups();
// if (groupsWithTask.getTask() != null) {
// LOG.info("task name = " + groupsWithTask.getTask().getName());
// }
// }
}
public boolean isDataVisible() {
return true;
}
// public Car[] getSelectedCars() {
// return selectedCars;
// }
// public void setSelectedCars(Car[] selectedCars) {
// this.selectedCars = selectedCars;
// }
public KooTable[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(KooTable[] selectedCars) {
this.selectedCars = selectedCars;
}
public KooTable getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(KooTable selectedCar) {
this.selectedCar = selectedCar;
}
}
Here is my question.When I click view button, I need to get every row of value including checkbox value whether checkbox is checked or nt then update to database. Is it possible?

RichFaces dynamic TabPanel

How to implement a simple add/remove dynamic <rich:tabPanel>?
(I've seen people asking this around so I thought postin a Q&A of a simple implementation)
The implementation has 3 custom classes:
Content: contains the values to be displayed in a tab;
ItemTab: contais an UITab object and a Content object;
MyTabs: EJB managed bean that provides access to the tabs and adding/removal methods.
The code is:
Content:
public class Content {
String name;
String job;
String dept;
public Content() {
name = "John Doe";
job = "None";
dept = "None";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
TabItem:
public class TabItem {
UITab component;
Content content;
public TabItem() {
component = new UITab();
content = new Content();
}
public UITab getComponent() {
return component;
}
public void setComponent(UITab tab) {
this.component = tab;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
}
MyTabs:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class MyTabs implements Serializable {
private List<TabItem> tabs;
public MyTabs() {
tabs = new ArrayList<TabItem>();
}
#PostConstruct
private void init() {
createTab();
createTab();
createTab();
}
public void createTab() {
TabItem tab = new TabItem();
tab.getComponent().setId("Tab" + (tabs.size()+1));
tab.getComponent().setHeader("Tab " + (tabs.size()+1));
tab.getContent().setName("John Doe " + (tabs.size()+1));
tab.getContent().setJob("Salesman " + (tabs.size()+1));
tab.getContent().setDept("Sales " + (tabs.size()+1));
tabs.add(tab);
}
public void removeTab(TabItem tab) {
tabs.remove(tab);
}
public List<TabItem> getTabs() {
return tabs;
}
public void setTabs(List<TabItem> tabs) {
this.tabs = tabs;
}
}
tabview.xhtml:
<h:commandLink value="Add Tab"
actionListener="#{myTabs.createTab()}"/>
<rich:tabPanel switchType="client">
<c:forEach items="#{myTabs.tabs}" var="tab">
<rich:tab value="#{tab.component}">
<f:facet name="header">
<h:outputLabel value="#{tab.component.header}"/>
<h:commandLink value=" X" actionListener="#{myTabs.removeTab(tab)}"/>
</f:facet>
<h:panelGrid columns="2">
<h:outputLabel value="Name: "/>
<h:outputLabel value="#{tab.content.name}"/>
<h:outputLabel value="Dept: "/>
<h:outputLabel value="#{tab.content.dept}"/>
<h:outputLabel value="Job: "/>
<h:outputLabel value="#{tab.content.job}"/>
</h:panelGrid>
</rich:tab>
</c:forEach>
</rich:tabPanel>

Resources