I wanted to remove rows from the data table when the checkbox is ticked and remove button is pressed..
This is the datatable snippet :
<p:dataTable id="cartTable" lazy="true" scrollable="true"
scrollHeight="115" selection="#{Cart_Check.selectedItems}"
value="#{Cart_Check.cart}" var="cart" rowKey="#{cart.sheetno}"
style="widht:100%;margin-top:10%;margin-left:1%;margin-right:30px ;box-shadow: 10px 10px 25px #888888;">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:2%">
</p:column>
//Here the columns are metion
<f:facet name="footer">
<p:commandButton id="viewButton" value="Remove" />
</f:facet>
</p:dataTable>
This is the backing bean
public class checkcart {
private int items;
private ArrayList<User_Cart> cart;
private ArrayList<User_Cart> selectedItems;
public checkcart() {
getvalues();
}
//getter and setter
public void getvalues() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(false);
System.out.println("Cart Request ::::" + session.getAttribute("regid"));
try {
Connection connection = BO_Connector.getConnection();
String sql = "Select * from cart_orderinfo where usrregno=?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, (String) session.getAttribute("regid"));
ResultSet rs = ps.executeQuery();
cart = new ArrayList<>();
while (rs.next()) {
User_Cart user_cart = new User_Cart();
user_cart.setSheetno(rs.getString("sheetno"));
user_cart.setState_cd(rs.getString("state_cd"));
user_cart.setDist_cd(rs.getString("dist_cd"));
user_cart.setLicensetype(rs.getString("license_type"));
user_cart.setFormat(rs.getString("sheet_format"));
user_cart.setQuantity(rs.getInt("quantity"));
cart.add(user_cart);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
and when i run this page i get the following error
datamodel must implement org.primefaces.model.selectabledatamodel when selection is enabled.
But when i remove the checkbox then their is no error but it is without a checkbox.
What to do and how to resolve the following error ..Kindly help..
I want something like this :
http://www.primefaces.org/showcase/ui/datatableRowSelectionRadioCheckbox.jsf
You just need to define ListDataModel as shown below,
public class SD_User_Cart extends ListDataModel<User_Cart> implements SelectableDataModel<User_Cart> {
public SD_User_Cart() {
}
public SD_User_Cart(List<User_Cart> data) {
super(data);
}
#Override
public User_Cart getRowData(String rowKey) {
//In a real app, a more efficient way like a query by rowKey should be implemented to deal with huge data
List<User_Cart> rows = (List<User_Cart>) getWrappedData();
for (User_Cart row : rows) {
if (row.getCartId.toString().equals(rowKey)) {//CartId is the primary key of your User_Cart
return row;
}
}
return null;
}
#Override
public Object getRowKey(User_Cart row) {
return row.get.getCartId();
}
}
Change your "cart" object into SD_User_Cart as shown below,
private SD_User_Cart cart;
Then define selection in p:datatable, and add a column as shown below,
<p:column selectionMode="multiple" style="width:18px"/>
Hope this helps:)
You need to define a your private ArrayList<User_Cart> selectedItems; data member in back class public class checkcart like this private User_Cart[] selectedItems; and give setter and getter method for the same it will work.
I had also faced same problem.
Related
I have list of h:selectBooleanCheckBox in rich:dataTabe. Also, there is pagination for the datatable.
The problem is when I click the next page number, the selected checkboxes at the first page of the datatable is gone. Though they are selected, clicking the next/previous page make them deselected.
Any idea about the problem?
These are the annotations for bean.
#ManagedBean(name = "bean")
#ViewScoped
To clarify it, I've attached my facelets and bean code below:
<rich:dataTable value="#{bean.ssTable}" var="data" iterationStatusVar="it" id="myDataTable">
...
<rich:column id="includeInWHMapping" >
<f:facet name="header">
<h:selectBooleanCheckbox value="#{bean.selectAll}" valueChangeListener="#{bean.selectAllCheckBox}">
<f:ajax render="myDataTable" />
</h:selectBooleanCheckbox>
</f:facet>
<h:selectBooleanCheckbox id="selectedForWHProcess" value="#{bean.checked[data]}">
<f:ajax actionListener="#{bean.selectAllRows}" />
</h:selectBooleanCheckbox>
</rich:column>
...
</rich:dataTable>
Bean code:
private Map<StandardStructure, Boolean> checked = new HashMap<StandardStructure, Boolean>();
private boolean selectAll;
/* Controller */
public MyController() {
super(new DataSetParameters());
logger.info("StandardStructureController created.");
Column rowid_col =new Column("rowid", "rowid", "No.", FilterTypes.NUMERIC, true, true, "");
Column fileid_col =new Column("fileid", "fileid", "File ID", FilterTypes.STRING, true, true, "");
Column releasetag_col =new Column("releasetag", "releasetag", "Releasetag ID", FilterTypes.STRING, true, true, "");
Column applicationid_col =new Column("applicationid", "applicationid", "Application ID", FilterTypes.STRING, true, true, "");
Column filename_col =new Column("filename", "filename", "Filename", FilterTypes.STRING, true, true, "ASC");
Column includeInWHMapping_col =new Column("includeInWHMapping", "includeInWHMapping", "Include in WH Mapping?", FilterTypes.NONE, true, true, "");
columns.put("fileid", fileid_col);
columns.put("releasetag", releasetag_col);
columns.put("applicationid", applicationid_col);
columns.put("filename", filename_col);
columns.put("includeInWHMapping", includeInWHMapping_col);
initialize();
setOrderField("importDate");
setOrder("DESC");
dataSetParameters.setColumns(columns);
loadTable();
}
/** getter/setter.. */
public boolean isSelectAll() {
return selectAll;
}
public void setSelectAll(boolean selectAll) {
this.selectAll = selectAll;
}
public Map<StandardStructure, Boolean> getChecked() {
return checked;
}
public void setChecked(Map<StandardStructure, Boolean> checked) {
this.checked = checked;
}
/** Load ssTable */
private void loadTable() {
try{
ssTable = new StandardStructureDao(dataSetParameters).getAllStandardStructure();
}catch (Exception ex){
System.out.println("Exception in loading table:"+ex);
}
}
/** Get ssTable */
public Collection<StandardStructure> getSsTable(){
return ssTable.getDto();
}
/** Pagination */
public void doPaginationChange(ActionEvent event) {
super.doPaginationChange(event);
loadTable();
/* trying to set the value of list of checkboxes after loading the table */
Iterator<StandardStructure> keys = checked.keySet().iterator();
while(keys.hasNext()){
StandardStructure ss = keys.next();
if(checked.get(ss)){ /* getting checked boxes */
/* Got stuck here. */
/* How do we just set the true (boolean) value only
for list of checkboxes though they are in Map?*/
System.out.println("Row id: " + ss.getRowid() + " Checked : " + checked.get(ss));
}
}
}
/** Select all the list of checkbox in datatable */
public void selectAllCheckBox(){
for(StandardStructure item : ssTable.getDto()){
if(!selectAll)
checked.put(item, true);
else
checked.put(item, false);
}
}
/** Select row of data in datatable */
public void selectAllRows(ValueChangeEvent e) {
boolean newSelectAll = (Boolean) e.getNewValue();
Iterator<StandardStructure> keys = checked.keySet().iterator();
logger.info("Rows selected..." + newSelectAll);
while(keys.hasNext()) {
StandardStructure ss = keys.next();
checked.put(ss, newSelectAll);
System.out.println("File::"+ss.getRowid()+":"+newSelectAll);
}
}
Many Thanks!
Since your code is unclear and confusing, I'll provide you the minimal example how pagination with select all on current page MIGHT look like. With no action listeners, just getters and setter. As simple as I could.
First XHTML:
<h:form>
<rich:dataTable value="#{bean.valuesOnPage}" var="data" id="dataTable" rows="20">
<rich:column>
<f:facet name="header">
<h:selectBooleanCheckbox value="#{bean.selectAll}">
<f:ajax render="dataTable" />
</h:selectBooleanCheckbox>
</f:facet>
<h:selectBooleanCheckbox value="#{bean.checked[data]}">
<f:ajax />
</h:selectBooleanCheckbox>
</rich:column>
<!-- other columns -->
</rich:dataTable>
</h:form>
Then the bean:
#ManagedBean(name = "bean")
#ViewScoped
public class MyBean {
// when the view is first loaded this is empty
// until someone will click one of checkboxes
private Map<Object, Boolean> checked = new HashMap<Object, Boolean>();
private boolean selectAll;
private List<Object> valuesOnPage;
private int currentPage = -1;
MyBean() {
setCurrentPage(1);
}
// no setter
public Map<Object, Boolean> getChecked() {
return checked;
}
public int getCurrentPage() {
return currentPage;
}
public boolean getSelectAll() {
return selectAll;
}
// no setter
public List<Object> getValuesOnPage() {
return valuesOnPage;
}
private void loadTable() {
try {
// gets data from data base
valuesOnPage = getData(currentPage);
} catch (Exception ex) {
System.out.println("Exception in loading table:" + ex);
}
}
public void setCurrentPage(int currentPage) {
if (this.currentPage != currentPage) {
this.currentPage = currentPage;
loadTable();
// we don't need it selected, especially if it
// was a paged we've never been on
selectAll = false;
}
}
public void setSelectAll(boolean selectAll) {
this.selectAll = selectAll;
for (Object o : valuesOnPage) {
checked.put(o, selectAll);
}
}
}
Look how and when the data is changing and when it is loaded. Check out that there's no unnessecary new action for checkbox of single row. JSF will take care of that with: value="#{bean.checked[data]}".
And once again: Your keys in map are objects. You have to make sure that equals method is good. In 95% of case the default is not, especially if they are #Entity. Check i.e. this topic.
I am trying to display below list of list of object in datatable. But nothing is showing up. Help is very much appreciated!
public class TimrsDisplayBean {
private static final long serialVersionUID = 1L;
private String teamName = "";
private String teamType = "";
private boolean reported;
private boolean noProd;
private boolean missing;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamType() {
return teamType;
}
public void setTeamType(String teamType) {
this.teamType = teamType;
}
public boolean getReported() {
return reported;
}
public void setReported(boolean reported) {
this.reported = reported;
}
public boolean getNoProd() {
return noProd;
}
public void setNoProd(boolean noProd) {
this.noProd = noProd;
}
public boolean getMissing() {
return missing;
}
public void setMissing(boolean missing) {
this.missing = missing;
}
}
XHTML FILE
<p:dataTable value="#{dashboardMBean.timrsDisplayDataList}" var="var" rowIndexVar="row"
styleClass="large-card-datatable alternatingRowTable no-border nowrap">
<f:facet name="header">
<span class="updateDate"> </span>
</f:facet>
<p:column headerText="Type" value=" #{dashboardMBean.timrsDisplayDataList[0]}" columnIndexVar="i">
#{var[i].teamType}
</p:column>
<p:column headerText="Type" value=" #{dashboardMBean.timrsDisplayDataList[0]}" columnIndexVar="i">
#{var[i].teamName}
</p:column>
Please support full code parts if possible. Your datatable tag doesn't even finish.
Beside that, it seems like you've done too much work. Did you try to calculate the row indices by yourself? Not needed. The basic column definiton is more comfortable. Use your defined variable var to name each element/row as shown in the Primefaces showcase:
http://www.primefaces.org/showcase/ui/data/datatable/basic.xhtml
In your case, it will be something like
<p:column headerText="Type">
<h:outputText value="#{var.teamType}"/>
</p:column>
Plus, as Jasper De Vries said correctly, there is no attribute called columnIndexVar. Remove it to prevent strange behaviour.
If this is not enough, you need to share some more code of your ManagedBean. Not sure if your posted java class represent your Bean, but if so, you need to declare it as a ManagedBean like
#ManagedBean(name = "timrsDisplayBean)
#SessionScoped
public class TimrsDisplayBean {
I hope this helps!
This question already has an answer here:
p:password doesn't redisplay prefilled model value
(1 answer)
Closed 6 years ago.
So, I am taking in a password value from a form which is being saved to an object. The objects are saved to a data table. I have the functionality to allow a user to select a row from the data table, and the values for that object will be populated back into the form. Unfortunately, all values will populate except the password field. If I alter the password field to become an inputText, the value will be shown after selecting the row from the data table. Below is the code. Thanks.
HTML
Customer Registration
<p:panelGrid columns="2">
<p:commandButton value="Submit" image="ui-icon-check" ajax="false" actionListener="#{createPerson.createPerson()}"/>
</p:panelGrid><br/>
<p:panel id="table">
<p:dataTable id="dataTable" editable="false" var="person" paginator="true" rows="5" selectionMode="single"
value="#{createPerson.dataModel}" rowKey="#{person.id}">
<f:facet name="header">
Record
</f:facet>
<p:ajax listener="#{createPerson.processUserSelection}" event="rowSelect" update=":createPersonForm"/>
<p:ajax listener="#{createPerson.processUserUnselection}" event="rowUnselect" update=":createPersonForm"/>
<p:column sortBy="id" headerText="ID">
<h:outputText value="#{person.id}" />
</p:column>
<p:column sortBy="ssn" headerText="SSN">
<h:outputText value="#{person.ssn}" />
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</h:body>
</html>
Person
public class Person {
private String ssn;
private String id;
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Create Person
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean(name = "createPerson")
#SessionScoped
public class CreatePerson {
private Person person;
List<Person> personList = new ArrayList<>();
private PersonDataModel dataModel;
private static int id = 0;
public CreatePerson() {
person = new Person();
dataModel = new PersonDataModel(personList);
}
public String getSsn() {
return person.getSsn();
}
public void setSsn(String ssn) {
person.setSsn(ssn);
}
public void createPerson(){
System.out.println(" Submit Button clicked..");
System.out.println(" SSN: " + person.getSsn());
if (person.getId() == null || person.getId().equalsIgnoreCase("-1")) {
//New Person
person.setId("" + (id++));
personList.add(person);
person = new Person();
person.setId("-1");
}
else {
}
}
public void processUserSelection(SelectEvent evt) {
System.out.println(" Row selected from the Data Table .");
this.person = (Person) evt.getObject();
}
public void processUserUnselection(UnselectEvent evt) {
System.out.println(" Row unselected from the Data Table .");
this.person = new Person();
this.person.setId("-1");
}
public PersonDataModel getDataModel(){
return this.dataModel;
}
}
Data Table Class
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class PersonDataModel extends ListDataModel<Person> implements SelectableDataModel<Person>{
public PersonDataModel() {
}
public PersonDataModel(List<Person> data) {
super(data);
}
#Override
public Person getRowData(String rowKey){
System.out.println("Key = " + rowKey);
List<Person> persons = (List<Person>) getWrappedData();
for (Person person : persons) {
if(person.getId().equals(rowKey)){
return person;
}
}
System.out.println("Valid Person not found");
return null;
}
#Override
public Object getRowKey(Person person){
return person.getId();
}
}
Its a high risk to display password ,if you will look into Primeface <p:password /> its a extension of JSF <h:inputSecret /> .
It have a attribute called redisplay by default its value should be false
Boolean flag indicating whether or not a previously entered password
should be rendered in form. Default is false.
Now add this attribute(redisplay="true") in your component.
For more information you can check Tag inputSecret
Render the clientId of the component as the value of the "name"
attribute. Render the current value of the component as the value of
the "value" attribute, if and only if the "redisplay" component
attribute is the string "true". If the "styleClass" attribute is
specified, render its value as the value of the "class" attribute.
I know this is not a bug.
But i need a suggestion, what can i do not to lose checked knowledge of checked lines?
On JSF page:
<h:form prependId="false" id="searchUserFormTable" >
<p:dataTable id="selectUserTable" var="user"
value="#{userListController.lazyDataModel}" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rows="2" paginatorPosition="bottom" rowKey="#{user}"
lazy="true"
rowsPerPageTemplate="2,10,20,30,40,50"
rendered="#{userListController.lazyDataModel != null}" selection="#{systemMessageEditController.receiverList}"
scrollable="true" scrollHeight="250" resizableColumns="false" >
<p:column selectionMode="multiple" width="18" />
<f:facet name="header">
<h:outputText value=" Users (#{userListController.lazyDataModel.rowCount})" />
</f:facet>
<p:column filterBy="#{user.name}" headerText="Name" filterMatchMode="contains" width="80">
#{user.name}
</p:column>
<p:column filterBy="#{user.surname}" headerText="Surname" filterMatchMode="contains" width="80">
#{user.surname}
</p:column>
<p:column headerText="Gender" width="80">
#{user.gender}
</p:column>
<p:column headerText="City" width="80">
#{user.address.city.name}
</p:column>
<p:column headerText="Status" width="80">
#{user.userStatus}
</p:column>
<p:column headerText="User Detail" width="80">
<h:link value="User Detail" outcome="/view/admin/usermanagement/userInfo.jsf">
<f:param name="userId" value="#{user.id}" />
</h:link>
</p:column>
</p:dataTable>
<p:commandButton value="Tamam" oncomplete="userListDlg.hide();" update=":newMessageForm"></p:commandButton>
</h:form>
All the controller:
#ManagedBean(name="systemMessageEditController")
#ViewScoped
public class SystemMessageEditController {
#ManagedProperty(value = "#{systemMessageService}")
SystemMessageService systemMessageService;
#ManagedProperty(value = "#{securityBean}")
SecurityBean securityBean;
#ManagedProperty(value = "#{systemMessageReceiverService}")
SystemMessageReceiverService systemMessageReceiverService;
#ManagedProperty(value = "#{systemMessageAnswerService}")
SystemMessageAnswerService systemMessageAnswerService;
private SystemMessage systemMessage = new SystemMessage();
private SystemMessageAnswer systemMessageAnswer = new SystemMessageAnswer();
private SystemMessageReceiver systemMessageReceiver = new SystemMessageReceiver();
private User[] receiverList;
private boolean dummy;
public void prepareToEdit(){
systemMessage = systemMessageService.findById(systemMessage.getId());
}
public void prepareToSendMessage(){
systemMessage = new SystemMessage();
receiverList = null ;
}
public void sendMessage(){
if(Util.isNotNull(systemMessage.getTitle())){
boolean success = false;
systemMessageAnswer.setUser(securityBean.getUser());
systemMessage.getSystemMessageAnswerList().add(systemMessageAnswer);
systemMessage.setUserSender(securityBean.getUser());
systemMessageAnswer.setSystemMessage(systemMessage);
if(!systemMessage.isSendAll()){
addMessageReceiver();
}
systemMessage = systemMessageService.save(systemMessage);
systemMessageAnswer = new SystemMessageAnswer();
success = true;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, FacesUtils.getMessageByKey("systemmessage.send.success"), FacesUtils.getMessageByKey("systemmessage.send.success"));
FacesContext.getCurrentInstance().addMessage("", message);
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("success", success);
}
else{
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, FacesUtils.getMessageByKey("systemmessage.null.title"), FacesUtils.getMessageByKey("systemmessage.null.title"));
FacesContext.getCurrentInstance().addMessage("", message);
}
}
public void setRead(SystemMessage message){
message.setReaded(true);
systemMessageService.save(message);
}
public void addMessageReceiver(){
for(User user : receiverList){
SystemMessageReceiver messageReceiver = new SystemMessageReceiver();
messageReceiver.setReceiver(user);
messageReceiver.setSystemMessage(systemMessage);
messageReceiver.setReaded(false);
systemMessage.getSystemMessageReceiverList().add(messageReceiver);
}
}
public void deleteMessage(){
boolean success = false;
systemMessageService.delete(systemMessageService.findById(systemMessage.getId()));
success = true;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, FacesUtils.getMessageByKey("systemmessage.delete.success"), FacesUtils.getMessageByKey("systemmessage.delete.success"));
FacesContext.getCurrentInstance().addMessage("", message);
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("success", success);
}
public void sendMessageAnswer(){
systemMessageAnswer.setUser(securityBean.getUser());
systemMessageAnswer.setSystemMessage(systemMessage);
systemMessageAnswerService.save(systemMessageAnswer);
if(!systemMessage.isSendAll()){
systemMessage.setSystemMessageReceiverList(systemMessageService.getReceiverListOfMessage(systemMessage));
for(SystemMessageReceiver systemMessageReceiver : systemMessage.getSystemMessageReceiverList()){
if(!systemMessageReceiver.getReceiver().getId().equals(securityBean.getUser().getId())){
systemMessageReceiver.setReaded(false);
systemMessageReceiver.setShowed(false);
systemMessageReceiverService.save(systemMessageReceiver);
}
}
}
systemMessage.getSystemMessageAnswerList().add(systemMessageAnswer);
systemMessageAnswer = new SystemMessageAnswer();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, FacesUtils.getMessageByKey("systemmessage.send.success"), FacesUtils.getMessageByKey("systemmessage.send.success"));
FacesContext.getCurrentInstance().addMessage("", message);
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("success", true);
}
public SystemMessageService getSystemMessageService() {
return systemMessageService;
}
public void setSystemMessageService(SystemMessageService systemMessageService) {
this.systemMessageService = systemMessageService;
}
public SystemMessage getSystemMessage() {
return systemMessage;
}
public void setSystemMessage(SystemMessage systemMessage) {
ArrayList<String> fetchedAttributes = new ArrayList<String>();
fetchedAttributes.add("systemMessageAnswerList");
this.systemMessage = systemMessageService.loadWithFetchedAttributes(systemMessage.getId(),fetchedAttributes);
}
public SystemMessageAnswer getSystemMessageAnswer() {
return systemMessageAnswer;
}
public void setSystemMessageAnswer(SystemMessageAnswer systemMessageAnswer) {
this.systemMessageAnswer = systemMessageAnswer;
}
public SecurityBean getSecurityBean() {
return securityBean;
}
public void setSecurityBean(SecurityBean securityBean) {
this.securityBean = securityBean;
}
public SystemMessageReceiverService getSystemMessageReceiverService() {
return systemMessageReceiverService;
}
public void setSystemMessageReceiverService(
SystemMessageReceiverService systemMessageReceiverService) {
this.systemMessageReceiverService = systemMessageReceiverService;
}
public SystemMessageAnswerService getSystemMessageAnswerService() {
return systemMessageAnswerService;
}
public void setSystemMessageAnswerService(
SystemMessageAnswerService systemMessageAnswerService) {
this.systemMessageAnswerService = systemMessageAnswerService;
}
public SystemMessageReceiver getSystemMessageReceiver() {
return systemMessageReceiver;
}
public void setSystemMessageReceiver(SystemMessageReceiver systemMessageReceiver) {
this.systemMessageReceiver = systemMessageReceiver;
}
public User[] getReceiverList() {
return receiverList;
}
public void setReceiverList(User[] receiverList) {
this.receiverList = receiverList;
}
I am losing checked info while jumping one pagination number to another, when i checked some rows, then jump another pagination number in datatable, and go back to old pagination number i loose the checked info, i see nothing has changed.
This is how #ViewScoped works. See the following answer from BalusC:
A view scoped bean lives as long as you interact with the same view (i.e. you return void or null in bean action method). When you navigate away to another view, e.g. by clicking a link or by returning a different action outcome, then the view scoped bean will be trashed by end of render response and not be available in the next request.
which explains that in cases like yours (I just read in one of your comment that you jump to another page before you lose the selection, you should note that in your question too!) the bean is destroyed, so when you navigate back to your dataTable view it gets reconstructed again. This is the reason why receiverList is empty => no selection.
If you want to save your data while navigating between different views, use a bean with scope wider than #ViewScoped, or simply save the selection to a table in your DB.
EDIT
The problem could be in your rowKey attribute. In the current code it points to the user object, in this case make sure that this objects has proper hashCode, equals and toString implementations. If the user class actually has a key or something, it would be easier to change rowKey to rowKey="#{user.id}".
Check the Showcase. I think it works just like you want.
You are probably sending the data via ajax request you should make sure that it process dataTable itself
I'm trying to create a DataTable with Multiple Row Selection but i'm getting an error here's the link of the tutorial http://www.primefaces.org/showcase/ui/datatableRowSelectionMultiple.jsf :
Here's my xhtml:
<p:dataTable border="1" value="#{projectAdminisrationMB.projectNoUsersList}"
var="userObj"
selection="#
{projectAdminisrationMB.selectedUsers}"
selectionMode="multiple" rowIndexVar="rowIndex"binding="#{table2}">
<p:column id="column3">
<f:facet name="header">
<h:outputText value=" user "></h:outputText>
</f:facet>
<h:outputText value="#{userObj.name}"/>
/
<h:outputText value="#{userObj.lastName}"></h:outputText>
<h:outputText value="#{userObj.firstName}"></h:outputText>
</p:column>
<f:facet name="footer">
<p:commandButton id="addProjectUser" value=" Add " onclick="dlg1.show()" />
<p:commandButton id="deleteProjectUser" value=" Delete " />
</f:facet>
</p:dataTable>
Managed Bean :
#ManagedBean
#SessionScoped
public class ProjectAdminisrationMB implements Serializable {
private static final long serialVersionUID = 1L;
private String projectName;
private List <User> projectUsersList;
private List<User> projectNoUsersList;
private List<User> selectedUsers;
private String projectAdmin;
public ProjectAdminisrationMB() {
super();
AdministrationProjectFinal administrationProjectFinal =new
AdministrationProjectFinal();
this.projectUsersList=administrationProjectFinal.getUserList();
this.projectNoUsersList=administrationProjectFinal.getNotUserList();
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public List<User> getProjectUsersList() {
return projectUsersList;
}
public void setProjectUsersList(List<User> projectUsersList) {
this.projectUsersList = projectUsersList;
}
public String getProjectAdmin() {
return projectAdmin;
}
public void setProjectAdmin(String projectAdmin) {
this.projectAdmin = projectAdmin;
}
public List<User> getProjectNoUsersList() {
return projectNoUsersList;
}
public void setProjectNoUsersList(List<User> projectNoUsersList) {
this.projectNoUsersList = projectNoUsersList;
}
public List<User> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<User> selectedUsers) {
this.selectedUsers = selectedUsers;
}
}
i'm getting this error:
javax.faces.FacesException: DataModel must implement
org.primefaces.model.SelectableDataModel when selection is enabled.....
just add this attribute rowKey to the datatable tag :
<p:dataTable border="1" value="#{projectAdminisrationMB.projectNoUsersList}"
var="userObj"
rowKey="#{userObj.name}"selection="#{projectAdminisrationMB.selectedUsers}"
selectionMode="multiple" rowIndexVar="rowIndex"
binding="#{table2}">
You can get this error if you try to add a new item to the underlying list and forget to assign a value to that new item's rowKey.
Alternatively to rowKey you can wrap your data in a custom model which really implements org.primefaces.model.SelectableDataModel. This is helpful if
all of your your classes have the same kind of #Id (e.g. a long) and can implement the same interface (e.g. EjbWithId)
you want to add additional functionalities to your data which are not domain specific and don't belong e.g. User.
The interface may be something like this:
public interface EjbWithId
{
public long getId();
public void setId(long id);
}
Then a generic implementation of SelectableDataModel for all your classes can be used:
public class PrimefacesEjbIdDataModel <T extends EjbWithId>
extends ListDataModel<T> implements SelectableDataModel<T>
{
public PrimefacesEjbIdDataModel(List<T> data)
{
super(data);
}
#Override public T getRowData(String rowKey)
{
List<T> list = (List<T>) getWrappedData();
for(T ejb : list)
{
if(ejb.getId()==(new Integer(rowKey))){return ejb;}
}
return null;
}
#Override public Object getRowKey(T item) {return item.getId();}
}
In your #ManagedBean:
private PrimefacesEjbIdDataModel<User> dmUser; //+getter
dmUser = new PrimefacesEjbIdDataModel<User>(administrationProjectFinal.getUserList());
first check whether you've added
rowKey="#{userObj.id}"
then you need to have the data table List set in filteredValue attribute of your data table in xhtml, instead of value.