i have a datatable :
<p:dataTable id="marksTable"
var="item"
value="#{markingBean.markToEdit}"
rowKey="#{markingBean.markToEdit}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15"
scrollable="true"
liveScroll="true"
scrollRows="20"
emptyMessage="No details was found with given criteria">
<p:column headerText="#{bundle.labelMarkSectionOne} ">
<h:outputText value="#{item.markSectionOne}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionTwo}">
<h:outputText value="#{item.markSectionTwo}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionThree}">
<h:outputText value="#{item.markSectionThree}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionFour}">
<h:outputText value="#{item.markSectionFour}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionFive}">
<h:outputText value="#{item.markSectionFive}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionSix}">
<h:outputText value="#{item.markSectionSix}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionSeven}">
<h:outputText value="#{item.markSectionSeven}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionEight}">
<h:outputText value="#{item.markSectionEight}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionNine}">
<h:outputText value="#{item.markSectionNine}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionTen}">
<h:outputText value="#{item.markSectionTen}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionEleven}">
<h:outputText value="#{item.markSectionEleven}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionTwelve}">
<h:outputText value="#{item.markSectionTwelve}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionThirteen}">
<h:outputText value="#{item.markSectionThirteen}" />
</p:column>
</p:dataTable>
this will only show one row, what i want to do is simply add up all these values and then take the average
how best can i do this ?
EDIT
as request
The data is retrived from a database where all values are stored, in the data table it only displays one row from the db one pre selected before hand
This is the marking bean
#Named(value = "markingBean")
#ViewScoped
//#RequestScoped
public class MarkingController {
private String searchString;
private String ordering;
private String criteria;
private String match;
private Date today;
private String caseMatch;
private Boolean changed;
//private Marking markSectionOne;
// private Marking studentNumber;
// private Marking markSectionTwo;
// private Marking markToEdit;
private int spinnerField;
private Marking markToCreate, markToEdit;
private String searchMark;
private List<Marking> userSearchResults;
private List<Marking> marksList;
private Person user;
private Progress progress;
private Marking marking;
private Boolean isCompleted;
private String disabled;
private boolean value1;
private boolean value2;
private List<String> selectedOptions;
private Integer option;
private Integer number;
private List<Marking> totalMark;
#Inject
PersonFacade personFacade;
#Inject
CohortFacade cohortFacade;
#Inject
MilestoneFacade milestoneFacade;
#Inject
ProjectFacade projectFacade;
#Inject
ProgressFacade progressFacade;
#Inject
MilestoneService milestoneService;
#Inject
MarkingFacade markingFacade;
#Inject
MarkingService markingService;
#PostConstruct
public void init() {
this.markToCreate = new Marking();
this.marking = new Marking();
this.marksList = markingFacade.findAll();
// totalMark = mark.list();
changed = false; //required otherwise will work opposite of how we want
String username = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
// Get the logged in user
List<Person> usernameSearchResults = this.personFacade.usernameSearch(FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName());
if (usernameSearchResults.size() > 0) {
this.user = usernameSearchResults.get(0);
}
String marking_id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("edit_id");
System.out.println(marking_id);
if (marking_id != null) {
this.markToEdit = this.markingFacade.find(Long.parseLong(marking_id));
}
}
public void createMarkingOne() {
System.out.println("in Create mark one");
this.markingService.createMarking(this.markToCreate);
// this.markingFacade.create(this.markToCreate);
this.setMessage(" saved");
}
public void createMarking() {
System.out.println("in Create mark");
this.markingService.createMarking(this.markToCreate);
// this.markingFacade.create(this.markToCreate);
this.setMessage(" saved");
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
/* Delete mark*/
public void deleteMark(Marking markToDelete) {
/* this.markingService.deleteMark(markToDelete);
listMarks(); //need to add the list marks function
this.setMessage("Mark has been deleted.");*/
//this.markingFacade.remove(this.marking_id);
}
// Edit existing marks
public void editMark() throws IOException {
System.out.println("in edit mark");
this.markingFacade.edit(this.markToEdit);
this.setMessage("Mark(s) for the project has been successfully been recorded.");
MarkingLog loadProp = new MarkingLog(); // re anable for testing when finished
loadProp.loadProp();
}
public void addMessage(boolean markingCompleted) {
String summary = markingCompleted ? "Checked" : "Unchecked";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(summary));
}
public void editChange() {
changed = true;
}
/**
* SEARCHES *
*/
//for the advanced search query
public void basicMarkingSearch() {
userSearchResults = markingFacade.basicMarkingSearch(searchString, criteria, ordering, match);
}
public void testMarkingSearch() {
userSearchResults = markingFacade.testMarkingSearch(searchString, ordering, match);
}
Marking entity
#Entity(name = "MARKING")
public class Marking implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
private Person marker;
#ManyToOne
private Project project;
// #ManyToOne
// private Project project;
//#ManyToMany(mappedBy = "title")
//private Project projectBeMarked;
private String markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour,
markSectionFive, markSectionSix, markSectionSeven, markSectionEight,
markSectionNine, markSectionTen, markSectionEleven, markSectionTwelve, markSectionThirteen, markAdjust, overalMark, thirdMarker, plagorism;
What i am trying to do, is add up a row markSectionOne to Thirteen and then take the average and display this to the user
Related
When i am not using filter in primefaces datatable and try to select row then for example press edit it working well and takes the selected row.but when i use primefaces filter and then select the filtered row then edit
i got org.primefaces.model.SelectableDataModel when selection is enabled exception.
i know that mean i have a null row key but i don't know why.i am using a valid row key(id) the primary key of the datatable and when i use the debug i found that it get the id two times in the failure case,first time it got the right filtered id and the second time it get null id.
my question why it gets the rowkey id two times which get the null in the second time and cause the exception
<h:body>
<h:form prependId="false" id="growlForm">
<p:growl id="growl" showDetail="false" />
</h:form>
<h:form id="dataForm">
<p:panel id="ingerdientsTable">
<f:facet name="header">
<h:outputText value="Standard Food List" />
</f:facet>
<p:dataTable id="ingedientsTable" widgetVar="ingedientsTable" var="ingerdients" resizableColumns="true"
selectionMode="single" selection="#{mealBean.selectedStandardIngerdients}"
rowKey="#{ingerdients.getId()}" value="#{mealBean.allIngerdients}" rowsPerPageTemplate="5,10,25,50" rows="20"
paginator="true" style="padding-top:10px;padding-bottom:10px" tableStyle="table-layout: auto"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown} ">
<p:column headerText="Food Type" filterBy="#{ingerdients.name}"><h:outputText value="#{ingerdients.name}" /></p:column>
<p:column headerText="Protein(gm)" filterBy="#{ingerdients.containedProtiens}"><h:outputText value="#{ingerdients.containedProtiens}" /></p:column>
<p:column headerText="Carbs(gm)" filterBy="#{ingerdients.containedCarbs}"><h:outputText value="#{ingerdients.containedCarbs}" /></p:column>
<p:column headerText="Fats(gm)" filterBy="#{ingerdients.containedFats}"><h:outputText value="#{ingerdients.containedFats}" /></p:column>
<p:column headerText="Total Calories" filterBy="#{ingerdients.totalCalories}"><h:outputText value="#{ingerdients.totalCalories}" /></p:column>
<p:column styleClass="action-column">
<f:facet name="header">
<h:outputText value="Actions" />
</f:facet>
<p:commandButton id="addToMeal" value="Add To Meal" icon="ui-icon-create" update="addToMealDialog"
action="#{mealBean.showIngerdientsToMealDialog(ingerdients)}" immediate="true"
title="Add To meal" ajax="true">
</p:commandButton>
<p:tooltip for="addToMeal" value="Add To Meal"
showEffect="fade" hideEffect="fade" />
</p:column>
</p:dataTable>
</p:panel>
public class StandardIngerdients{
#Id
#Column(name="Id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#ManyToOne
#JoinColumn(name="FolderPathId",referencedColumnName="Id",nullable=true)
private FolderPath folderPath;
#Column(name="Name")
private String name;
#Column(name="ContainedProteins")
#NotNull
private Double containedProtiens;
#Column(name="ContainedCarbs")
#NotNull
private Double containedCarbs;
#Column(name="ContainedFats")
#NotNull
private Double containedFats;
#Column(name="TotalCalories")
#NotNull
private Double totalCalories;
#Column(name="ImageName")
private String imageName;
public Integer getId() {
return id;
}
public void setId(Integer Id) {
this.id = Id;
}
public FolderPath getFolderPath() {
return folderPath;
}
public void setFolderPath(FolderPath folderPath) {
this.folderPath = folderPath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getContainedProtiens() {
return containedProtiens;
}
public void setContainedProtiens(Double containedProtiens) {
this.containedProtiens = containedProtiens;
}
public Double getContainedCarbs() {
return containedCarbs;
}
public void setContainedCarbs(Double containedCarbs) {
this.containedCarbs = containedCarbs;
}
public Double getContainedFats() {
return containedFats;
}
public void setContainedFats(Double containedFats) {
this.containedFats = containedFats;
}
public Double getTotalCalories() {
return totalCalories;
}
public void setTotalCalories(Double totalCalories) {
this.totalCalories = totalCalories;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
}
I was having the same problem. The thing is I make my class to implement Serializable which guarantee the "integrity" (so to speak) of data in order not to disappear hehe... so your class would be like this:
public class StandardIngerdients implements Serializable {
you can try below code i think solve it
rowKey="#{ingerdients.id}"
I am having a problem with showing cell value using primefaces datatable. Originally table was displaying fields from only one entity class (Document). I needed to add additional field from another class (DocData). I managed to do that by adding the transient field "oib" into the Document class (field name oib is stored in the third class DocTypeField).
The problem now is that after inserting new row only fields from Document class are displayed. Refresh page also doesn't help. Only thing that will result with displaying new data (oib) is server restart.
This is my database model:
This is Document class:
#Entity
#Table(name="ACQ_DOCUMENT")
#NamedQuery(name="Document.findAll", query="SELECT a FROM Document a")
#NoArgsConstructor
#ViewScoped
public #Data class Document implements Serializable {
private static final long serialVersionUID = 2611447987879527170L;
#Id
#SequenceGenerator(name = "DocumentSEQ",sequenceName = "ACQ_DOCUMENT_SEQ",allocationSize=1)
#GeneratedValue(strategy = GenerationType.IDENTITY,generator = "DocumentSEQ" )
#Column(name="DOCUMENT_ID")
private Integer id;
#Column(name="DOCUMENT_FIRST_NAME")
private String firstName;
#Column(name="DOCUMENT_LAST_NAME")
private String lastName;
#ManyToOne
#JoinColumn(name="DOCUMENT_DOC_TYPE_ID")
private DocType docType;
#OneToMany
#JoinColumn(name="DATA_DOCUMENT_ID")
private List<DocData> docData;
#Transient
private String oib;
public String getOib() {
if (oib == null) {
for(DocData dd : docData) {
if(dd.getDocTypeField().getName().equals("oib") && (dd.getDocument().getId().equals(id))) {
oib = dd.getStringValue();
}
}
}
return oib;
}
public void setOib(String oib){
this.oib = oib;
}
#Override
public String toString() {
return this.getClass().getName() + "[id=" + id + "]";
}
}
This is DocTypeField class:
#Entity
#Table(name="ACQ_DOC_TYPE_FIELD")
#NamedQuery(name="DocTypeField.findAll", query="SELECT a FROM DocTypeField a")
#NoArgsConstructor
public #Data class DocTypeField implements Serializable {
private static final long serialVersionUID = 2109749245241103862L;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ACQ_DOC_TYPE_FIELD_SEQ")
#Column(name="FIELD_ID")
private Integer id;
#Column(name="FIELD_NAME")
private String name;
#Column(name="field_type")
private String type;
//bi-directional many-to-one association to AcqDocType
#ManyToOne
#JoinColumn(name="FIELD_DOC_TYPE_ID")
private DocType docType;
#Column(name="field_active")
private Boolean active;
#Override
public String toString() {
return this.getClass().getName() + "[id=" + id + "]";
}
}
This is DocData class:
#Entity
#Table(name="ACQ_DOC_DATA")
#NamedQuery(name="DocData.findAll", query="SELECT a FROM DocData a")
#NoArgsConstructor
public #Data class DocData implements Serializable {
private static final long serialVersionUID = 915219051205073130L;
#Id
#SequenceGenerator(name = "DocDataSEQ",sequenceName = "ACQ_DOC_DATA_SEQ",allocationSize=1)
#GeneratedValue(strategy = GenerationType.IDENTITY,generator = "DocDataSEQ" )
#Column(name="DATA_ID")
private Integer id;
#Temporal(TemporalType.DATE)
#Column(name="DATA_DATE_VALUE")
private Date dateValue;
#Column(name="DATA_DECIMAL_VALUE")
private BigDecimal decimalValue;
#Column(name="DATA_INT_VALUE")
private Integer intValue;
#Column(name="DATA_STRING_VALUE")
private String stringValue;
#Lob
#Column(name="DATA_TEXT_VALUE")
private String textValue;
#Column(name="DATA_TIMESTAMP_VALUE")
private Timestamp timestampValue;
//bi-directional many-to-one association to AcqBlobValue
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="DATA_BLOB_VALUE_ID")
private BlobValue blobValue;
//bi-directional many-to-one association to AcqDocTypeField
#ManyToOne
#JoinColumn(name="DATA_DOC_TYPE_FIELD_ID")
private DocTypeField docTypeField;
//bi-directional many-to-one association to AcqDocument
#ManyToOne
#JoinColumn(name="DATA_DOCUMENT_ID")
private Document document;
#Override
public String toString() {
return this.getClass().getName() + "[id=" + id + "]";
}
}
And finally this is datatable definition:
<p:dataTable lazy="true" id="documents" var="item" value="#{documentManager.lazyModel}" selection="#{documentManager.formObject}"
selectionMode="single" rowKey="#{item.id}" sortBy="#{item.id}" sortMode="single"
paginator="true" rows="15" paginatorPosition="bottom" styleClass="alignTop">
<p:ajax event="rowSelect" listener="#{documentManager.onRowSelect}" />
<f:facet name="header">#{e['adrDocument']}</f:facet>
<p:column width="10%" sortBy="#{item.id}">
<f:facet name="header">#{e['adrDocument.id']}</f:facet>
<h:outputText value="#{item.id}" />
</p:column>
<p:column width="10%" sortBy="#{item.firstName}">
<f:facet name="header">#{e['adrDocument.firstName']}</f:facet>
<h:outputText value="#{item.firstName}" />
</p:column>
<p:column width="10%" sortBy="#{item.lastName}">
<f:facet name="header">#{e['adrDocument.lastName']}</f:facet>
<h:outputText value="#{item.lastName}" />
</p:column>
<p:column width="10%" sortBy="#{item.docType.descr}">
<f:facet name="header">#{e['adrDocument.tipDokumenta']}</f:facet>
<h:outputText value="#{item.docType.descr}" />
</p:column>
<p:column width="10%" sortBy="#{item.oib}">
<f:facet name="header">#{e['adrDocument.oib']}</f:facet>
<h:outputText value="#{item.oib}" />
</p:column>
<p:confirmDialog global="true" width="250">
<p:commandButton value="#{m['ui.edit.confirm.yes']}" type="button" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"/>
<p:commandButton value="#{m['ui.edit.confirm.no']}" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</p:dataTable>
So, item.oib isn't properly displayed. I also tried removing lazyloading, different oib fetching and so on... Have no more ideas.
Want to filter the resultset of a query which is displayed through a datatable. The row selection, row sorting clicking on column headers and the pagination functionnalities of the datatable works fine. When I add the primefaces filtering functionnality to the datatable, I then run into the
javax.faces.FacesException: DataModel must implement
org.primefaces.model.SelectableDataModel when selection is enabled.
Object Entity:
#Entity
#Table(name="Customer",
uniqueConstraints={#UniqueConstraint(columnNames={"ID"})})
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID", nullable=false, unique=true, length=11)
private Integer id;
#Column(name="LASTNAME", length=40, nullable=false)
private String lastName;
#Column(name="FIRSTNAME", length=30, nullable=true)
private String firstName;
....
}
Managed Bean:
#ManagedBean(name = "customerController")
#ViewScoped
public class CustomerController implements Serializable {
private static final long serialVersionUID = 1L;
private Customer selectedCustomer = new Customer();
private List<Customer> customers = new ArrayList<Customer>();
private String message;
public CustomerController() {
}
#PostConstruct
void init() {
CustomerDAO custDAO = new CustomerDAO();
customers = custDAO.getAllCustomers();
// select first row
if (customers != null) selectedCustomer=customers.get(0);
}
public void onRowSelect(SelectEvent event) {
message = "";
}
public void onRowUnselect(UnselectEvent event) {
message = "";
}
// getters and setters
...
}
Facelet:
<ui:define name="contentPart1" >
<h:form id="contentPart1Form">
<p:dataTable id="singleSelection" var="customer" value="#{customerController.customers}" rowKey="#{customer.id}"
selection="#{customerController.selectedCustomer}" selectionMode="single" paginator="true" rows="10">
<p:ajax event="rowSelect" listener="#{customerController.onRowSelect}" />
<p:column headerText="#{msg['customerCRUD.labelIdentifier']}" style="width:15%;">
<h:outputText value="#{customer.id}" readonly="#{facesContext.currentPhaseId.ordinal eq 6}"/>
</p:column>
<p:column headerText="#{msg['customerCRUD.labelFirstName']}" sortBy="#{customer.firstName}" style="width:30%;">
<h:outputText value="#{customer.firstName}" />
</p:column>
<p:column headerText="#{msg['customerCRUD.labelLastName']}" filterBy="#{customer.lastName}" filterMatchMode="contains"
sortBy="#{customer.lastName}">
<h:outputText value="#{customer.lastName}" />
</p:column>
<f:facet name="footer">
<h:outputText value=" "/>
</f:facet>
</p:dataTable>
</h:form>
</ui:define>
After hours of investigation, I finally realized the object entity on which I was appliyng the filter to was not serializable.
The resolution was to inherit the object entity from the Serialization class.
#Entity
#Table(name="Customer",
uniqueConstraints={#UniqueConstraint(columnNames={"ID"})})
public class Customer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID", nullable=false, unique=true, length=11)
private Integer id;
#Column(name="LASTNAME", length=40, nullable=false)
private String lastName;
#Column(name="FIRSTNAME", length=30, nullable=true)
private String firstName;
....
}
I need your help in enabling and disabling inputText based on rowSelectCheckbox and rowUnselectCheckbox if the checkbox is ticked or unticked. If it is ticked, then I need to enable the inputText otherwise it should be disabled on page load and on untick. By default the inputText is disabled on the page load. Here is the code for the jsf:
<h:form id="request">
<p:dataTable value="#{dataTableView.employeeList}" id="Employee" var="emp"
selection="#{dataTableView.selectedEmployees}" rowKey="#{emp.id}">
<p:ajax event="rowSelectCheckbox" listener="#{dataTableView.EnableInputText}" />
<p:ajax event="rowUnselectCheckbox" listener="#{dataTableView.EnableInputText}" />
<p:columnGroup type="header">
<p:row>
<p:column/>
<p:column headerText="ID"/>
<p:column headerText="Name"/>
<p:column headerText="Location"/>
<p:column headerText="Remarks"/>
</p:row>
</p:columnGroup>
<p:column selectionMode="multiple" style="width:2%;text-align:center"/>
<p:column headerText="ID">
<h:outputText value="#{emp.id}"/>
</p:column>
<p:column headerText="Name">
<h:outputText value="#{emp.name}"/>
</p:column>
<p:column headerText="Location">
<h:outputText value="#{emp.location}"/>
</p:column>
<p:column headerText="Remarks">
<h:inputText id="inputT1" value="#{emp.remarks}" disabled="#{emp.disable}"/>
</p:column>
</p:dataTable>
</h:form>
And here is the code in the bean:
private List<Student> employeeList = new ArrayList<Student>();
private List<Student> selectedEmployees;
private boolean disable;
#PostConstruct
public void init() {
//add Employees
disable=true;
Student w1 = new Student(111, "AAAA", "ZZZZ", "", disable);
Student w2 = new Student(222, "CCCCC", "ZZZZZ", "OUT", disable);
Student w3 = new Student(222, "BBBBBB", "YYYYYYY", "IN", disable);
employeeList.add(w1);
employeeList.add(w2);
employeeList.add(w3);
}
public void EnableInputText(SelectEvent event) {
for(int i=0;i<=selectedEmployees.size();i++){ //Assuming you have declared as List
for(int j=0;j<=employeeList.size();j++){
if(selectedEmployees.get(i).getId().equals(employeeList.get(j).getId()))
{
employeeList.get(j).setDisable(false);
break;
}
}
}
}
The Student Bean:
public class Student {
private Integer id;
private String name;
private String location;
private String remarks;
private boolean disable;
public Student(Integer id, String name, String location, String remarks, boolean disable){
this.id = id;
this.name = name;
this.location = location;
this.remarks=remarks;
this.disable=disable;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRemarks() {
return remarks;
}
public void setDisable(boolean disable) {
this.disable = disable;
}
public boolean isDisable() {
return disable;
}
And in the Bean, I am facing difficulties in enabling the inputText for entry if the row is ticked. So could you please help.
Now I got the error :
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 if I tick and checkbox
First thing you are using selectionMode="multiple" it means there will be multiple rows with textField enabled next
instead of this :
<h:inputText value="#{emp.remarks}" disabled="#{empBean.enable}" />
write
<h:inputText value="#{emp.remarks}" disabled="#{emp.enable}" />
means declare one variable enable in the bean itself after that:
for(int i=0;i<=selectedEmployees.size();i++){ //Assuming you have declared as List
for(int j=0;j<=empList.size();j++){
if(selectedEmployees.get(i).getId().equals(empList.get(j).getId()){
empList.get(j).setEnable(false);
}
}
}
before to this you can write one for loop and disable all the textField for list for that will work for rowUnselect
Can I use radio button to select a single row then edit some of data on that row then use
commandButton to submit what I edit it in that row. I'm trying to edit username cell for now as test.
this a snap of my code:
Xadmin.xhtml
<h:form id="form" enctype="multipart/form-data">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="DT" value="#{Jadmin.messages}"
var="o"
selection="#{Jadmin.selectedUser}"
rowKey="#{o.id}"
style="margin-bottom:20px">
<f:facet name="header">
Users List
</f:facet>
<p:column selectionMode="single" />
<p:column>
<f:facet name="header">
<h:outputText value="id" />
</f:facet>
<h:outputText value="#{o.id}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="username" />
</f:facet>
<p:inputText value="#{o.username}" />
</p:column>
<f:facet name="footer">
<h:commandButton value="Update" action="#{Jadmin.update}" />
<p:commandButton value="Delete"
action="#{Jadmin.delete}"
ajax="false"
update=":form:msgs"/>
</f:facet>
</p:dataTable>
JadminBeans.java
#ManagedBean(name = "Jadmin")
#SessionScoped
public class JadminBeans implements Serializable {
private static final long serialVersionUID = 1L;
private JadminController selectedUser;
List<JadminController> userslist = new ArrayList<JadminController>();
public List<JadminController> getMessages() {
System.out.println("List<JadminController> getMessages()");
userslist = JadminDAO.getAllUsers();
return userslist;
}
public void delete() {
//System.out.println(usr);
//System.out.println(itemList.remove(item)+"!!");
System.out.println("JadminBeans >> delete() ---------- id= ");
JadminDAO.deleteUser(selectedUser);
}
public JadminController getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(JadminController selectedUser) {
this.selectedUser = selectedUser;
}
public void update() {
//o=(JadminBeans) objct;
JadminDAO.updateUser(selectedUser);
}
}
JadminDAO.java
public static void deleteUser(JadminController user) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("delete from users where id=?");
// Parameters start with 1
preparedStatement.setLong(1, user.getId());
preparedStatement.executeUpdate();
System.out.println("JadminDAO >> deleteUser ----------");
} catch (SQLException e) {
System.out.println("JadminDAO >> deleteUser----------- SQLException :(");
e.printStackTrace();
}
}
public static void updateUser(JadminController user) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("update users username=?, password=?, permission=? where username=?");
// Parameters start with 1
//System.out.println(new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getPermission());
//preparedStatement.setDate(3, new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.setString(4, user.getUsername());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
JadminController.java
public class JadminController implements Serializable {
private static final long serialVersionUID = 1L;
private String username, password, permission;
private long id;
// Getters and setters.
}
If you use Editable Datatable you don't need any command button to submit what you've edited.
As shown in the same link, inside in datatable is usually used a selectOneMenu instead of radioButton for making choices.
To use input element inside your datatable don't forget to put <f:facet name="output"></f:facet> and <f:facet name="input"></f:facet>
I hope it helps.