Update Datalist value in primefaces - jsf

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>

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.

Datatable not saving any edits

Hi guys i have a datatable from the primefaces library, which i am trying to include the feature of editing each cell and when the user presses a "save" button at the row it will update the edited values to a database, however currently when a user edits a cell what ever they change the cell to the second they click off the cell the value goes the same as what it was before, it does not save the new values, and also another issues is when the user presses save at the end of the row the values passwed to the database is always Null, how can i solve these two issues ?
here is the xhtml
<p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15,25"
editable="true" editMode="cell"
>
<p:column>
<!--
<p:ajax event="rowEdit" listener="{u.onEdit}" update=":form:messages" />
<p:ajax event="rowEditCancel" listener="{u.onCancel}" update=":form:messages" />
-->
<f:facet name="header">
User ID
</f:facet>
#{u.userID}
</p:column>
<p:column headerText="Name" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.name}" />
</f:facet>
<f:facet name="input">
<p:inputText id="NameInput" value="#{u.name}"
style="width:96%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Email">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.email}" />
</f:facet>
<f:facet name="input">
<p:inputText id="EmailInput" value="#{u.email}"
/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Address">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.address}" />
</f:facet>
<f:facet name="input">
<p:inputText id="AddressInput" value="#{u.address}"
/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">
Created Date
</f:facet>
#{u.created_date}
</p:column>
<p:column>
<f:facet name="header">
Delete
</f:facet>
<h:commandButton value="Delete" action="#{user.delete(u.userID)}" />
</p:column>
<p:column>
<f:facet name="header">
Save Edit
</f:facet>
<h:commandButton value="Save" action="#{user.editData(u.userID)}" />
</p:column>
</p:dataTable>
and here is the backing bean although currently this is only updating the database with the values from the databale
public void editData(long userID) {
System.out.println(name);
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
System.out.println(name);
String sql = "UPDATE user1 set name = '" + name + "', email = '" + email + "', address = '" + address + "' WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row updated successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
the datable originally gets its values from the database
Thanks
Here is how i populate the datatable with values from the database,/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package richard.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import richard.test.User;
#ManagedBean(name = "userBean")
#SessionScoped
public class UserBean {
List<User> list;
PreparedStatement ps = null;
Connection con = null;
ResultSet rs = null;
public List<User> getList() {
return list;
}
public List<User> getUserList() {
list = new ArrayList<User>();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "select * from user1";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
User usr = new User();
usr.setUserID(rs.getLong("userId"));
usr.setName(rs.getString("name"));
usr.setEmail(rs.getString("email"));
usr.setAddress(rs.getString("address"));
usr.setCreated_date(rs.getDate("created_date"));
list.add(usr);
Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
List<User> checkedItems = new ArrayList<User>();
for (User item : list) {
if (checked.get(item.getUserID()) != null) {
checkedItems.add(item);
usr.delete(usr.getUserID());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
HERE is the full user bean code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package richard.test;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIColumn;
import javax.faces.event.ActionEvent;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
#ManagedBean
#RequestScoped
public class User {
List<User> list;
PreparedStatement ps = null;
Connection con = null;
ResultSet rs = null;
private long userID = 1;
private String name;
private String address;
private Date created_date;
private String email;
boolean editable;
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public String editAction(User order) {
order.setEditable(true);
return null;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
public String add() {
System.out.println("In add");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
int i = 0;
if (userID != 0) {
PreparedStatement ps = null;
Connection con = null;
try {
System.out.println("about to add to db");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "INSERT INTO user1( name, email, address, created_date) VALUES(?,?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, address);
if (created_date != null) {
String date = fmt.format(created_date);
Object obj = date;
if (obj == null) {
ps.setDate(4, null);
} else {
java.sql.Date dt = java.sql.Date.valueOf(new String(date));
ps.setDate(4, dt);
}
}
i = ps.executeUpdate();
System.out.println("Data Added Successfully");
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (i > 0) {
return "output";
} else {
return "invalid";
}
} else {
return "invalid";
}
}
public void delete(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "DELETE FROM user1 WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row deleted successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void editData(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
System.out.println(name);
String sql = "UPDATE user1 set name = '" + name + "', email = '" + email + "', address = '" + address + "' WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row updated successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
The main problem is that you have two User objects:
User u - currently selected user.
User user - just a ManagedBean, most probably with no state (no id, no name, no address).
When performing the edit operation you try to use u.id and user.name, user.address, etc.
What you need to do, is to take all the values from the u object.
There are many different approaches (I've never used the third one, but it should work and it's the closest to what you've already have):
A1. You can keep currently selected object in your UserBean and set it with setPropertyActionListener:
<f:setPropertyActionListener target="#{userBean.selectedUser}" value="#{u}" />
Then you can call the edit method implemented in the same bean (it has full access to selectedUser object and it can implement the edit itself of just delegate the action to object with edit method implementation).
A2. You can place your edit method in the UserBean and pass entire User object as a parameter:
<h:commandButton value="Save" action="#{userBean.editData(u)}" />
A3. Or you can just call:
<h:commandButton value="Save" action="#{u.editData()}" />
instead of:
<h:commandButton value="Save" action="#{user.editData(u.userID)}" />

How to use selectOneMenu without converter?

I'm using selectOneMenu for displaying some pictures and Strings, the pictures is for displaying purposes only i have (i.e. i have nothing to do with them on submitting) i want only to set the string next to the image, i have a conflict in setting the itemValue of the f:selectItems to the String required, when i do that the images doesn't appear at all, in a word i want to only submit the value of the string in the chosen selectItem without using converter:
JSF Code:
<p:selectOneMenu id="SkinChooser" value="#{personBean.ObjectDTO.personDescription.skin}"
panelStyle="width:150px" effect="fade" var="s"
style="width:160px" converter="#{personBean.converter}">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{missedPersonBean.selectedSkins}"
var="skin" itemLabel="#{skin.skinType}" itemValue="#{skin}" />
<p:column>
<p:graphicImage value="/resources/images/skin/#{s.skinPhoto}"
width="40" height="50" />
</p:column>
<p:column>
#{s.skinType}
</p:column>
</p:selectOneMenu>
Skin.Java
public class Skin {
String skinPhoto;
String skinType;
public Skin() {
}
public Skin(String photo, String type) {
this.skinPhoto = photo;
this.skinType = type;
}
public String getSkinPhoto() {
return skinPhoto;
}
public void setSkinPhoto(String skinPhoto) {
this.skinPhoto = skinPhoto;
}
public String getSkinType() {
return skinType;
}
public void setSkinType(String skinType) {
this.skinType = skinType;
}
}
personBean.Java
#ManagedBean(name = "personBean")
#SessionScoped
public class ReportPerson {
private Skin skin;
private static List<Skin> selectedSkins;
static {
System.err.println("Array is filled");
selectedSkins = new ArrayList<Skin>();
selectedSkins.add(new Skin("1", "Pale white"));
selectedSkins.add(new Skin("2", "Fair white"));
selectedSkins.add(new Skin("3", "Light brown"));
selectedSkins.add(new Skin("4", "Moderate brown"));
selectedSkins.add(new Skin("5", "Dark brown"));
selectedSkins.add(new Skin("6", "Deeply pigmented"));
System.err.println("Finished Filling");
}
public List<Skin> getSelectedSkins() {
return selectedSkins;
}
public void setSelectedSkins(List<Skin> selectedSkins) {
this.selectedSkins = selectedSkins;
}
public Skin getSkin() {
return skin;
}
public void setSkin(Skin skin) {this.skin = skin;}
}

p:selectonemenu not working (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

Resources