i am using datalist of primefaces jsf . I am just populating data from arraylist and show in datalist and also using dialog box for detailed view ,but problem this with selected values dialog box does not show them.here is the code
UI Class :
<?xml version="1.0"?>
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
<h:form id="form">
<p:dataList value="#{tableBean.applicantlist}" var="applicant"
id="applicants" paginator="true" rows="5"
paginatorTemplate="{PreviousPageLink} {CurrentPageReport} {NextPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" type="none">
<f:facet name="header">
Applicants
</f:facet>
<h:outputText value="#{applicant.jobtitle}, #{applicant.useremail}"
style="margin-left:10px" />
<p:commandButton icon="ui-icon-search" update=":form:appDetail"
oncomplete="appDialog.show()" title="View Detail">
<f:setPropertyActionListener value="#{applicant}"
target="#{tableBean.selectedApplicant}" />
</p:commandButton>
</p:dataList>
<p:dialog header="Car Detail" widgetVar="appDialog" modal="true"
showEffect="fade">
<p:outputPanel id="appDetail" style="text-align:center;"
layout="block">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="modelNo" value="Model No: " />
<h:outputText id="modelNo"
value="#{tableBean.selectedApplicant.useremail}" />
</h:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</h:body>
</f:view>
here is table bean :
package com.DTO;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
#ManagedBean
#SessionScoped
public class TableBean implements Serializable {
private List<InterViewDto> applicantlist;
private InterViewDto selectedApplicant;
public List<InterViewDto> getApplicantlist() {
return applicantlist;
}
public void setApplicantlist(List<InterViewDto> applicantlist) {
this.applicantlist = applicantlist;
}
public InterViewDto getSelectedApplicant() {
return selectedApplicant;
}
public void setSelectedApplicant(InterViewDto selectedApplicant) {
this.selectedApplicant = selectedApplicant;
}
public TableBean() {
getSelectedApplicant();
applicantlist = new ArrayList<InterViewDto>();
InterViewDto p1 = new InterViewDto();
p1.setJobtitle("junaid");
p1.setUseremail("email#hotmail.com");
applicantlist.add(p1);
}
}
Here is DTO Class:
package com.DTO;
import java.sql.SQLException;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#SessionScoped
public class InterViewDto {
String useremail,jobtitle;
Date date;
public String getUseremail() {
return useremail;
}
public InterViewDto(){
}
public void setUseremail(String useremail) {
this.useremail = useremail;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
p:commandButton and p:commandLink actions does not work inside data table, data list or any component which is populated by a List in backing bean if the list is not enclosed by p:column.
Enclose each item which is shown in table by p:column.
<p:dataList value="#{tableBean.applicantlist}" var="applicant"
id="applicants" paginator="true" rows="5"
paginatorTemplate="{PreviousPageLink} {CurrentPageReport} {NextPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" type="none">
<p:column >
<h:outputText value="#{applicant.jobtitle}, #{applicant.useremail}"
style="margin-left:10px" />
</p:column >
<p:column >
<p:commandButton icon="ui-icon-search" update=":form:appDetail"
oncomplete="appDialog.show()" title="View Detail">
<f:setPropertyActionListener value="#{applicant}"
target="#{tableBean.selectedApplicant}" />
</p:commandButton>
</p:column >
</p:dataList>
Related
first of all, I am writing this because I am desperate. The thing is I was doing a simple Spring Boot CRUD with Primefaces. I used a bean called "carBean" to access the data in the index.xhtml file. Until there everything ok, things started to turn weird from now on. I tried to use a simple inputText to bind a text given in the UI to a property in the bean.
But I was constantly getting error 500, telling me that the property "marca" was not found in the bean, and I have checked 10000 times and everything is OK in there. So I started testing, and eventually I figured out that, the property that was working fine "carBean.cars" if I change the name to whatever I change (and obviously the methods liked to the property), It stop working. Is like the only property that works has to be named "cars". What I am missing here? Is driving me crazy, I promise this was my last resource. Thanks in advance .
carBean
package com.example.bean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import com.example.controller.CarController;
import com.example.dto.CarDTO;
import lombok.Data;
#Data
#Named("carBean")
#Scope(value = "session")
public class CarBean implements Serializable {
private static final long serialVersionUID = -8338541378806874723L;
#Autowired
CarController carController;
private List<CarDTO> cars;
private Integer id;
private String marca;
private String modelo;
private String precio;
private String bastidor;
private String potencia;
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public List<CarDTO> getCars() {
cars = carController.getAllCars();
return cars;
}
public void delete(CarDTO car) {
carController.deleteCar(car.id);
cars = carController.getAllCars();
}
public void add() {
CarDTO newCar = new CarDTO();
newCar.marca = this.marca;
newCar.modelo = this.modelo;
newCar.precio = this.precio;
newCar.bastidor = this.bastidor;
newCar.potencia = this.potencia;
carController.create(newCar);
}
public String redirect() {
return "index.xhtml?faces-redirect=true";
}
}
index.xhtml
<!DOCTYPE xhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h3> REGISTRO DE COCHES </h3>
<h:form id = "tabla">
<div class="card">
<p:dataTable var="car" value="#{carBean.cars}">
<p:column sortBy="#{car.marca}" headerText="Marca">
<h:outputText value="#{car.marca}" />
</p:column>
<p:column sortBy="#{car.modelo}" headerText="Modelo">
<h:outputText value="#{car.modelo}" />
</p:column>
<p:column sortBy="#{car.precio}" headerText="Precio">
<h:outputText value="#{car.precio}" />
</p:column>
<p:column sortBy="#{car.bastidor}" headerText="Bastidor">
<h:outputText value="#{car.bastidor}" />
</p:column>
<p:column sortBy="#{car.potencia}" headerText="Potencia">
<h:outputText value="#{car.potencia}" />
</p:column>
<p:column>
<p:commandButton type="submit" value="Eliminar" actionListener="#{carBean.delete(car)}"
update=":tabla" />
<p:commandButton type="button" value="Editar"/>
</p:column>
</p:dataTable>
<p:commandButton value="Nuevo Coche" type="submit" oncomplete="PF('createModal').show();"/>
</div>
</h:form>
<p:dialog header="Agregar" widgetVar="createModal" id="createModal">
<h:form id="createDialog">
<p:panel header="Detalles del coche">
<h:panelGrid columns="1">
<h:outputLabel value="Marca:"/>
<h:inputText id="marca" value="#{carBean.marca}" required="true"> </h:inputText>
<h:outputLabel value="Modelo"/>
<h:inputText id="modelo"> </h:inputText>
<h:outputLabel value="Precio"/>
<h:inputText id="precio"> </h:inputText>
<h:outputLabel value="Bastidor"/>
<h:inputText id="bastidor"> </h:inputText>
<h:outputLabel value="Potencia"/>
<h:inputText id="potencia"> </h:inputText>
</h:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</h:head>
</html>
Why I cannot used other property that isn´t called "cars"?
Don't mess Lombok #Data autogenerated getters and setters with the one you've declared in the Bean.
You have used a getter as a method, which is not a good thing to do because it can be called multiple times, see: Why JSF calls getters multiple times
public List<CarDTO> getCars() {
cars = carController.getAllCars(); // remove business logic from getter
return cars;
}
Better initialize your private List<CarDTO> cars variable in a method annotated with #PostContruct
#PostConstruct
public void init() {
cars = carController.getAllCars();
}
For more check this example: PrimeFaces DataTable CRUD
I'm using Spring, Hibernate and JSF for a web application.
In my case I have a Table User having many columns, one of those is idRole. idRole is a foreign key from table Role which containes Id of the role and the role name.
What I want to know is how to make the role name shown in my place of the ID, and make that field a List showing only possible roles (which are all the columns of the Roles table)
Here is my ManagedBean :
package managedController;
import org.primefaces.event.RowEditEvent;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import spring.model.Customer;
import spring.service.CustomerService;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#ManagedBean(name="customerMB")
#RequestScoped
public class CustomerManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final String SUCCESS = "success";
private static final String ERROR = "error";
#ManagedProperty(value="#{CustomerService}")
CustomerService customerService;
List<Customer> customerList;
private int id;
private String name;
private String surname;
public String addCustomer() {
try {
Customer customer = new Customer();
customer.setId(getId());
customer.setName(getName());
customer.setSurname(getSurname());
getCustomerService().addCustomer(customer);
reset();
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
public String updateCustomer(Customer customer) {
try {
getCustomerService().updateCustomer(customer);
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
public String deleteCustomer(Customer customer) {
try {
getCustomerService().deleteCustomer(customer);
customerList = null;
getCustomerList();
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Edited");
FacesContext.getCurrentInstance().addMessage(null, msg);
updateCustomer((Customer)event.getObject());
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void reset() {
this.setId(0);
this.setName("");
this.setSurname("");
}
public List<Customer> getCustomerList() {
if(customerList == null){
customerList = new ArrayList<Customer>();
customerList.addAll(getCustomerService().getCustomers());
}
return customerList;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
and here is the file where I show them (Users or Customers let's say) :
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:sec="http://www.springframework.org/security/tags">
<h:head>
<title>Welcome</title>
</h:head>
<h:body>
<!-- View element level Spring Security : only can view for who has the role 'ROLE_ADMIN' -->
<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
<h:form id="form2">
<table>
<tr>
<td><h:outputLabel for="id" value="Id : "/></td>
<td><p:inputText id="id" value="#{customerMB.id}">
<f:converter converterId="javax.faces.Integer"/>
<p:ajax event="blur" update="idMsg"/>
</p:inputText>
<p:message id="idMsg" for="id" display="icon"/>
</td>
</tr>
<tr>
<td><h:outputLabel for="name" value="Name : "/></td>
<td><p:inputText id="name" value="#{customerMB.name}">
<f:validateLength minimum="1"/>
<p:ajax event="blur" update="nameMsg"/>
</p:inputText>
<p:message id="nameMsg" for="name" display="icon"/>
</td>
</tr>
<tr>
<td><h:outputLabel for="surname" value="Surname : "/></td>
<td><p:inputText id="surname" value="#{customerMB.surname}">
<f:validateLength minimum="1"/>
<p:ajax event="blur" update="surnameMsg"/>
</p:inputText>
<p:message id="surnameMsg" for="surname" display="icon"/>
</td>
</tr>
<tr>
<td><p:commandButton id="addUser" value="Add" action="#{customerMB.addCustomer}" ajax="false"/></td>
<td><p:commandButton id="reset" value="Reset" action="#{customerMB.reset}" ajax="false"/></td>
</tr>
</table>
</h:form>
</sec:authorize>
<br/>
<h:form id="form1">
<p:growl id="messages" showDetail="true"/>
<p:dataTable id="customers" var="customer" value="#{customerMB.customerList}" style="width: 10%" editable="true">
<p:ajax event="rowEdit" listener="#{customerMB.onEdit}" update=":form1:messages"/>
<p:ajax event="rowEditCancel" listener="#{customerMB.onCancel}" update=":form1:messages"/>
<p:column headerText="ID">
<h:outputText value="#{customer.id}"/>
</p:column>
<p:column headerText="Name">
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{customer.name}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{customer.name}" label="name"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Surname">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{customer.surname}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{customer.surname}" label="surname"/>
</f:facet>
</p:cellEditor>
</p:column>
<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
<p:column>
<f:facet name="header">Delete</f:facet>
<h:commandLink value="Delete" action="#{customerMB.deleteCustomer(customer)}"/>
</p:column>
<p:column style="width:20%">
<f:facet name="header">Update</f:facet>
<p:rowEditor/>
</p:column>
</sec:authorize>
</p:dataTable>
<br/>
<p:commandButton value="Logout" id="logout" action="#{loginBean.logout}"/>
</h:form>
</h:body>
</html>
Thank you
#ManagedBean(name="customerMB")
#RequestScoped
...
#ManagedProperty(value="#{CustomerService}")
CustomerService customerService;
It's advised to switch those to :
#Named
#RequestScoped
...
#Inject or #EJB
SomeService ss;
//for a managed property just use Inject without parameters.
Your code will still work. But take the javax.enterprise.context.RequestScoped package for request scoped.
Since you didn't post any entity whatsoever and probably copy pasted the tutorial, I'll post smtg generic to give you a general idea of how to go with it:
#Named
#RequestScoped
public class Mybean {
private List<User> userLists; // +getters and setters
#EJB
private SomeService ss;
//make the call to the Db in a PostConstruct annotated method, NOT in the constructor. So the injections are done.
#PostConstruct
public void init(){
userLists = ss.getUsers();
}
}
What I want to know is how to make the role name shown in my place of
the ID
Huh ? I guess you want this :
<h:dataTable value="#{mybean.userLists}" var="user">
<h:column>
#{user.role.name}
</h:column>
</h:dataTable>
In your entities you must have a relationship between the two. Probably #ManyToOne
and make that field a List showing only possible roles (which are all
the columns of the Roles table)
Same idea, get your list from db in the init method:
roleList = aService.getRoles();
Then You want to display those in a list ? I guess you meant a selectOneMenu. Follow the link the tutorial is well explained.
The following is my code snippet in my abc.xhtml page :
<p:panelGrid id="pnlGrd_numOfLbl"
style="align:center; width:100%;" cellpadding="5">
<c:forEach var="i" begin="1" end="${specificationMB.numOfLbl}" >
<p:row>
<p:column width="50%">
<p:outputLabel value="Label ${i}" />
</p:column>
<p:column width="50%">
<p:inputText id="inputTxt_${i}" style="width:150px;" />
</p:column>
</p:row>
</c:forEach>
</panelGrid>
This is my panelGrid I am generating inputText dynamically depending
numOfLable. After generation say 2 will be generate user will add some
text to each inputText so my Question is How can I get value of dyanamically
generated inputbox.
Thanks.
This can easily be done with basics of JSF and primefaces. Here is full working Example:
XHTML File (I am using p:panel and ui:repeater)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<link rel=" stylesheet" type="text/css" href="css/style.css"></link>
</h:head>
<h:body>
<h:form>
<p:panel header="Panel">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.lbl} :" />
</p:column>
<p:column width="50%">
<p:inputText value="#{lbl.value}" />
</p:column>
</p:row>
</ui:repeat>
</p:panel>
<p:commandButton actionListener="#{tBean.submit}" value="Subtmi" update="values"></p:commandButton>
<p:outputPanel id="values">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.value} :" />
</p:column>
</p:row>
</ui:repeat>
</p:outputPanel>
</h:form>
</h:body>
</f:view>
<body>
</body>
</html>
Managed Bean
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
#ManagedBean(name = "tBean")
#ViewScoped
public class TestBean {
private List<LabelClass> lblClassess;
public TestBean() {
lblClassess = new ArrayList<LabelClass>();
lblClassess.add(new LabelClass("First Label", ""));
lblClassess.add(new LabelClass("Second Label", ""));
lblClassess.add(new LabelClass("Third Label", ""));
}
public void submit(ActionEvent e) {
for (LabelClass lbl : lblClassess) {
System.out.println(lbl.getValue());
}
}
public List<LabelClass> getLblClassess() {
return lblClassess;
}
public void setLblClassess(List<LabelClass> lblClassess) {
this.lblClassess = lblClassess;
}
}
Label Class
public class LabelClass {
private String lbl;
private String value;
public LabelClass(String lbl, String value) {
super();
this.lbl = lbl;
this.value = value;
}
public String getLbl() {
return lbl;
}
public void setLbl(String lbl) {
this.lbl = lbl;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Output
In order to get the values of your dynamically generated inputTexts. You may do something like this.
<input type="text" id="inputTxt_${i}" name="inputTxt_${i}" style="width:150px;" />
Then retrieve the text value by using this code in servlet
String inputText1 = request.getParameter("nameOfFirstInputText");
You can bind the value into the bean value object:
<input type="text" id="inputTxt_${i}" value="${specificationMB.getValue(i).value}" />
I have a datatable with each row having Edit and Delete buttons.
It is almost similar to http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionByColumn.jsf datatable.
When I click on Edit button, if I display the selected row values using <h:outputText> the values are being displayed properly.
But If I want to display it in a input text field using <h:inputText value="#{userCRUDMB.selectedUser.userName}"/> it is throwing error saying selectedUser is resolved as null.
If I only use <h:outputText ...> then userCRUDMB.selectedUser() method is getting called properly.
But If I use <h:inputText ...> in the Dialog, the setter method is not at all getting called.
I am using Mojarra 2.1.6, PrimeFaces 3.0, Apache Tomcat7.0.32.
Any idea why it is happening?
Code: Code is same as http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionByColumn.jsf, except in the dialogue box instead of displaying the text using I am trying to display in input textbox using .
public class User
{
private Integer userId;
private String userName;
private String password;
private String firstname;
private String lastname;
private String email;
private Date dob;
private String gender;
//setters/getters
}
package com.sivalabs.primefacesdemo.managedbeans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.sivalabs.primefacesdemo.model.User;
import com.sivalabs.primefacesdemo.model.UserDataModel;
import com.sivalabs.primefacesdemo.service.SpringContainer;
import com.sivalabs.primefacesdemo.service.UserService;
#ManagedBean(name="UserCRUDMB")
#RequestScoped
public class UserCRUDMB
{
private UserDataModel userDataModel;
private User selectedUser;
private User[] selectedUsers;
public UserCRUDMB()
{
List<User> users = new ArrayList<User>();
for (int i = 0; i < 15; i++) {
User user = new User();
user.setUserId(i);
user.setUserName("userName"+i);
users.add(user);
}
this.userDataModel = new UserDataModel(users);
}
public UserDataModel getUserDataModel() {
return userDataModel;
}
public void setUserDataModel(UserDataModel userDataModel) {
this.userDataModel = userDataModel;
}
public User[] getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(User[] selectedUsers) {
this.selectedUsers = selectedUsers;
}
public User getSelectedUser() {
System.out.println("get-->"+selectedUser);
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
System.out.println("set--->"+selectedUser);
this.selectedUser = selectedUser;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body>
<h:form id="form">
<h:outputText value="PrimeFaces Demo - ShowUsers" />
<p:dataTable value="#{UserCRUDMB.userDataModel}" var="userObj"
selection="#{UserCRUDMB.selectedUsers}"
widgetVar="usersTbl">
<f:facet name="header">UserManagement</f:facet>
<p:column selectionMode="multiple"></p:column>
<p:column headerText="UserId">#{userObj.userId}</p:column>
<p:column headerText="UserName">#{userObj.userName}</p:column>
<p:column>
<p:commandButton value="Edit"
oncomplete="userEditDlg.show()"
update="form:userEditTbl">
<f:setPropertyActionListener target="#{UserCRUDMB.selectedUser}" value="#{userObj}"></f:setPropertyActionListener>
</p:commandButton>
</p:column>
<p:column>
<p:commandButton value="Delete" action="#{UserCRUDMB.deleteUser}"
update="usersTbl"
ajax="true">
<f:setPropertyActionListener target="#{UserCRUDMB.selectedUser}" value="#{userObj}"></f:setPropertyActionListener>
</p:commandButton>
</p:column>
<f:facet name="footer">
<p:commandButton value="Delete Selected" action="#{UserCRUDMB.deleteUsers}"
update="usersTbl"
ajax="true">
</p:commandButton>
</f:facet>
</p:dataTable>
<p:dialog widgetVar="userEditDlg" header="User Edit Form" hideEffect="explode"
minHeight="200" minWidth="300">
<h:panelGrid columns="2" id="userEditTbl" >
<h:outputLabel value="UserId" />
<h:outputText value="#{UserCRUDMB.selectedUser.userId}"/>
<h:outputLabel value="UserName" />
<h:inutText value="#{UserCRUDMB.selectedUser.userName}"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
Thanks,
Siva
If you are using ajax, the request scope ist not the "ideal" scope since the bean will be recreated for each request. This can be the reason that selectedUser is null. Use the view scope (#ViewScoped) instead.
I am trying to figure out, how the primefaces in-cell editor works.
For some reason, it does not work. I just see it activating and also i can type, but the values do not change. What is missing?
<?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://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:form>
<p:dataTable id="allSubjects" var="subject" value="#{subjectControllerUpdate.retrieve()}" paginator="true" rows="7" >
<p:column headerText="Name" sortBy="#{subject.name}" style="width:200px" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.name}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.description}" headerText="Description">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.description}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.description}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.credits}" headerText="Credits" style="width:50px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.credits}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.credits}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</html>
This is the managed bean
package controllers;
import crudfacades.SubjectFacade;
import entities.Subject;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named("subjectControllerUpdate")
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
private List<Subject> subjects;
private Subject currentSubject;
#EJB
private SubjectFacade ejbFacade;
//INITIALIZATION
public SubjectControllerUpdate() {
currentSubject = new Subject();
}
//RETRIEVE
public List<Subject> retrieve() {
return getSubjectFacade().findAll();
}
//UPDATE
//HELP METHODS
//RETURN THE FACADE FOR DATA MANIPULATION(Best practice)
private SubjectFacade getSubjectFacade() {
return ejbFacade;
}
//GETTERS AND SETTERS
public Subject getCurrentSubject() {
return currentSubject;
}
public void setCurrentSubject(Subject currentSubject) {
this.currentSubject = currentSubject;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
}
but when i click comfirm, the value in the UI is not changed
You've bound the value of the <p:dataTable> to retrieve() instead of getSubjects(). So every single getter call will get the values straight from the DB instead of the model.
and i see no changes in the database
You are not saving anything in the DB.
Fix your controller as follows:
#Named
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
private DataModel<Subject> subjects;
#EJB
private SubjectFacade ejbFacade;
#PostConstruct
public void init() {
subjects = new ListDataModel<Subject>(ejbFacade.findAll());
}
public void save() {
ejbFacade.save(subjects.getRowData());
}
public List<Subject> getSubjects() {
return subjects;
}
}
with
<h:form>
<p:dataTable value="#{subjectControllerUpdate.subjects}" ...>
<p:ajax event="rowEdit" listener="#{subjectControllerUpdate.save}" />
...
</p:dataTable>
</h:form>
Using DataModel<Subject> instead of List<Subject> is necessary in order to be able to get the current row.