I have a pick list component and I have 2 lists, the first has data from my database and the second is a DualListModel and I have a button to transfer between the pick lists, when I transfer data nothing happenes the source in the DualListModel stays empty.
Here is my JSF code:
<p:pickList id="a" value="#{mbInstructor.model}" var="pickQ"
itemLabel="#{pickQ}" itemValue="#{pickQ}">
<o:converter converterId="omnifaces.ListConverter" list="#{mbInstructor.fullList}" />
<p:ajax event="transfer" listener="#{mbInstructor.onTransfer}" update="msg" />
<p:ajax event="select" listener="#{mbInstructor.onSelect}" update="msg" />
<p:ajax event="unselect" listener="#{mbInstructor.onUnselect}" update="msg" />
<p:ajax event="reorder" listener="#{mbInstructor.onReorder}" update="msg" />
</p:pickList>
And here is my methods in the managed bean:
private List<Question> fullList;
private DualListModel<Question> model;
public List<SemesterExamQuestionForm> getAllQuestionForms() {
GeneralFacade facade = new GeneralFacade();
return facade.lstSemesterExamQuestionForm(getCurrentStudySemesterExam());
}
public void onTransfer(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
((Question) item).getQuestionTxt();
}
FacesMessage msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Items Transferred");
msg.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Question> getFullList() {
return fullList;
}
public DualListModel<Question> getModel() {
if(model == null){
model = new DualListModel<>();
}
fullList = getAllCourseQuestions();
model = new DualListModel<>(new ArrayList<>(fullList),new ArrayList<Question>());
return model;
}
public void setModel(DualListModel<Question> model) {
this.model = model;
}
Related
I have a class Document for create a Tree with a list of document objects.
public class Document implements Serializable {
private String name;
private String size;
private List<Field> fields;
public Document(String name, String size, String type) {
this.name = name;
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
}
Also I have a Field class for store relevant information in documents
public class Field implements Serializable {
private int fieldIndex;
private String label;
private String value;
private List<Values> list;
public Field() {
}
public int getFieldIndex() {
return fieldIndex;
}
public void setFieldIndex(int fieldIndex) {
this.fieldIndex = fieldIndex;
}
public Field(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<Values> getList() {
return list;
}
public void setList(List<Values> list) {
this.list = list;
}
}
My ManagedBean create a tree with some documents and store some data for each document. When i select the tree node, it's show a dynamic form with every field and inputs for enter some value.
#ManagedBean(name="treeSelectionView")
#ViewScoped
public class SelectionView implements Serializable {
private TreeNode root1;
private TreeNode selectedNode;
private String email;
private List<Field> fields;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#PostConstruct
public void init() {
TreeNode root = new DefaultTreeNode(new Document("Files", "-", "Folder"), null);
TreeNode documents = new DefaultTreeNode(new Document("Documents", "-", "Folder"), root);
Field f1=new Field();
Field f2=new Field();
Field f3=new Field();
f1.setLabel("email");
f1.setValue("");
f2.setLabel("doc");
f2.setValue("");
f3.setLabel("otro");
f3.setValue("");
List<Field> fields=new ArrayList<Field>();
fields.add(f1);
fields.add(f2);
fields.add(f3);
List<Field> fields1=new ArrayList<Field>();
f1=new Field();
f2=new Field();
f3=new Field();
f1.setLabel("email");
f1.setValue("");
f2.setLabel("doc");
f2.setValue("");
f3.setLabel("otro");
f3.setValue("");
fields1.add(f1);
fields1.add(f2);
fields1.add(f3);
List<Field> fields2=new ArrayList<Field>();
f1=new Field();
f2=new Field();
f3=new Field();
f1.setLabel("email");
f1.setValue("");
f2.setLabel("doc");
f2.setValue("");
f3.setLabel("otro");
f3.setValue("");
fields2.add(f1);
fields2.add(f2);
fields2.add(f3);
//Documents
Document d1= new Document("Expenses.doc", "30 KB", "Word Document");
Document d2=new Document("Resume.doc", "10 KB", "Word Document");
Document d3=new Document("RefDoc.pages", "40 KB", "Pages Document");
d1.setFields(fields);
d2.setFields(fields1);
d3.setFields(fields2);
TreeNode expenses = new DefaultTreeNode("document",d1, documents);
TreeNode resume = new DefaultTreeNode("document", d2, documents);
TreeNode refdoc = new DefaultTreeNode("document",d3 , documents);
documents.setExpanded(true);
root1 = root;
root1.setExpanded(true);
}
public void onNodeDocumentSelect(NodeSelectEvent nodeSelected) {
// fields=((Document)nodeSelected.getTreeNode().getData()).getFields();
fields=((Document)selectedNode.getData()).getFields();
}
public TreeNode getRoot1() {
return root1;
}
public TreeNode getSelectedNode() {
return selectedNode;
}
public void setSelectedNode(TreeNode selectedNode) {
this.selectedNode = selectedNode;
}
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
}
My JSF looks like
<!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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Default title</title>
</h:head>
<h:body>
<h:panelGrid columns="2">
<h:form id="treeForm">
<p:panel id="panel22" header="Documents" style="height:400px">
<p:growl id="msgs" showDetail="true" />
<p:tree value="#{treeSelectionView.root1}" var="doc" selectionMode="single" selection="#{treeSelectionView.selectedNode}" >
<p:ajax process="#this" event="select" update=":myForm:dymanicForm" listener="#{treeSelectionView.onNodeDocumentSelect}" />
<p:treeNode expandedIcon="ui-icon-folder-open" collapsedIcon="ui-icon-folder-collapsed">
<h:outputText value="#{doc.name}"/>
</p:treeNode>
<p:treeNode type="document" icon="ui-icon-document" >
<h:outputText value="#{doc.name}" />
</p:treeNode>
</p:tree>
</p:panel>
</h:form>
<h:form id="myForm">
<p:panel id="panel222" header="Info Doccs" style="height:400px">
<p:panel id="dymanicForm" >
<ui:repeat value="#{treeSelectionView.fields}" var="componentMetadata">
<h:panelGrid columns="3">
<h:outputText value="#{componentMetadata.label}"/>:
<h:inputText id="field" value="#{componentMetadata.value}"
required="true" label="#{componentMetadata.label}"/>
<h:message for="field" style="color:red" /></h:panelGrid>
</ui:repeat>
</p:panel>
<h:commandButton value="Submit" action="result" />
</p:panel>
</h:form>
</h:panelGrid>
</h:body>
</html>
When I press the submit button the values are submitted and store in each field, also the validations are fired. But I really need remove the submit button and validate the form when i lost focus every node. By example if i am in the first node validate the form only when i lost focus , but if the form validation fail i need to stay in this node.
Really I appreciate any help you can give me.
Thanks a lot in advance.
I wanted to realize a similar view, and it took me quite some time to figure out.
The trick is not declaring the selection attribute on <p:tree, but just the selectionMode and manage the selection only with the listener, manually.
This causes the selection to be swapped in INVOKE_APPLICATION phase instead of UPDATE_MODEL_VALUES, preserving the right pane references in value expressions.
Furthermore, validation happens before selection swapping and, if fails, the selection swap is prevented.
I think this is exactly what you are looking for:
<h:form>
<p:layout fullPage="false" stateful="false" style="height:400px">
<p:layoutUnit position="center">
<p:tree id="tree" var="data" nodeVar="node" value="#{testTreeBean.root}"
selectionMode="single" dynamic="true" animate="true" highlight="true"
style="border: 0">
<p:ajax event="select" listener="#{testTreeBean.onSelect}" process="#form"
update="#this #form:details" />
<p:ajax event="expand" process="#this" />
<p:ajax event="collapse" process="#this" />
<p:treeNode expandedIcon="ui-icon-folder-open" collapsedIcon="ui-icon-folder-collapsed">
<p:outputPanel id="node">
<h:outputText value="#{data.someText1} - #{data.someText2}" />
</p:outputPanel>
</p:treeNode>
</p:tree>
</p:layoutUnit>
<p:layoutUnit position="east" size="65%" minSize="150">
<p:outputPanel id="details" style="padding: 1em">
<p:panelGrid columns="3" rendered="#{testTreeBean.data != null}">
<p:outputLabel value="someLabel1" for="#next" />
<p:inputText value="#{testTreeBean.data.someText1}" required="true" />
<p:message for="#previous" />
<p:outputLabel value="someLabel2" for="#next" />
<p:inputText value="#{testTreeBean.data.someText2}" required="true" />
<p:message for="#previous" />
</p:panelGrid>
<h:outputText value="please select a node in the left pane"
rendered="#{testTreeBean.data == null}" />
</p:outputPanel>
</p:layoutUnit>
</p:layout>
</h:form>
the bean:
#javax.faces.bean.ManagedBean
#javax.faces.bean.ViewScoped
public class TestTreeBean implements Serializable
{
private static final long serialVersionUID = 1L;
private TreeNode root;
private TreeNode selected;
// build a dummy tree...
#PostConstruct
public void init()
{
root = new DefaultTreeNode();
for(int i = 0; i < 5; i++)
{
SomeData data = new SomeData("node " + i, String.valueOf(System.currentTimeMillis()));
TreeNode node = new DefaultTreeNode(data, root);
for(int j = 0; j < 5; j++)
{
SomeData subData = new SomeData("subNode " + i + "." + j, String.valueOf(System.currentTimeMillis()));
#SuppressWarnings("unused")
TreeNode subNode = new DefaultTreeNode(subData, node);
}
}
}
// handle selection swap manually
public void onSelect(NodeSelectEvent event)
{
if(selected != null)
{
selected.setSelected(false);
}
selected = event.getTreeNode();
if(selected != null)
{
selected.setSelected(true);
}
}
// shortcut for getting the selected node data
public Object getData()
{
return selected == null ? null : selected.getData();
}
public TreeNode getSelected()
{
return selected;
}
public TreeNode getRoot()
{
return root;
}
}
finally, for completeness, the dummy data class:
public class SomeData implements Serializable
{
private String someText1;
private String someText2;
public SomeData()
{
super();
}
public SomeData(String someText1, String someText2)
{
super();
this.someText1 = someText1;
this.someText2 = someText2;
}
public String getSomeText1()
{
return someText1;
}
public void setSomeText1(String someText1)
{
this.someText1 = someText1;
}
public String getSomeText2()
{
return someText2;
}
public void setSomeText2(String someText2)
{
this.someText2 = someText2;
}
}
Happy gardening :)
I have the CommandLink/CommandButton which is an element of the column in the dataTable. The dataTable is integrated with the lazy model. My code (not exactly my, because this is the primefaces showcase example) works perfect when the number of records in the table is divisible by the page size. For example the page size is 5 and the number of records is 60. But, when the number of records is 61, then when I reach the last record in the table, the action listener for every button is not called. I've tried to change p:commandlink to h:commandbutton/p:commandbuton. I've tried all the stackoverflow tips related to use update="#form" or immediate="true" or disable ajax requests by ajax="false", but the result is the same. For me it looks like a problem with dataTable rendering. Please look at the source code. This example is based on the primefaces showcase, I've added only a new column (this one with the commandlink).
xhtml page:
<h:form id="form">
<p:dataTable styleClass="test-class" id="data" var="car" value="#{tableBean.lazyModel}" scrollable="true" liveScroll="true" scrollRows="5" scrollHeight="200" lazy="true" >
<p:column headerText="Model">
<h:outputText value="#{car.model}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Manufacturer">
<h:outputText value="#{car.manufacturer}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
<p:column headerText="Color">
<p:commandLink value="Test"
actionListener="#{tableBean.buttonListener()}" />
</p:column>
</p:dataTable>
</h:form>
datatable lazy model:
public class MyLazyModel extends LazyDataModel<Car> {
private List<Car> datasource;
public MyLazyModel(List<Car> datasource) {
this.datasource = datasource;
}
#Override
public Car getRowData(String rowKey) {
for(Car car : datasource) {
if(car.getModel().equals(rowKey))
return car;
}
return null;
}
#Override
public Object getRowKey(Car car) {
return car.getModel();
}
#Override
public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
//rowCount
int dataSize = datasource.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return datasource.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return datasource.subList(first, first + (dataSize % pageSize));
}
}
else {
return datasource;
}
}
}
DataTable bean:
#ManagedBean
#ViewScoped
public class TableBean {
private LazyDataModel<Car> lazyModel;
private Car selectedCar;
private List<Car> cars;
public TableBean() {
populateRandomCars(cars, 60);
lazyModel = new MyLazyModel(cars);
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public LazyDataModel<Car> getLazyModel() {
return lazyModel;
}
How would it be possible to retrieve an inputText value foreach row in JSF dataTable, since this data is not an attribute in the object on which we iterate in the loop.
(here 0 as default value). I can't change the Class properties (here Product)
<h:form>
<p:dataTable var="product" value="#{bean.products}">
<p:column headerText="Id">
<h:outputText value="#{product.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{product.name}" />
</p:column>
<p:column headerText="Quantity">
<h:inputText size="3" value="0" />
</p:column>
</p:dataTable>
<h:commandButton value="Submit" action="#{bean.submit}"/>
</h:form>
Bean.class
#ManagedBean
...
public void submit() {
List<Product> products = this.getProducts();
for(Product product : list) {
System.out.println("Product.name : "+ Product.name );
System.out.println("Quantity : "+ ?? );
}
}
Bind it to a Map with Product (or its ID) as key.
E.g.
private List<Product> products;
private Map<Product, Long> quantities;
#EJB
private ProductService productService;
#PostConstruct
public void init() {
products = productService.list();
quantities = new HashMap<>();
}
public void submit() {
for (Product product : products) {
Long quantity = quantities.get(product);
System.out.println("Quantity: " + quantity);
}
}
// Getters (no setters necessary for those two properties)
with
<h:inputText size="3" value="#{bean.quantities[product]}" />
You can use the visitor pattern to get the values. Something like this:
table.visitTree(VisitContext.createVisitContext(faces),
new VisitCallback() {
#Override public VisitResult visit(VisitContext vc, UIComponent component) {
if (component.equals(quantity) && quantity.getValue() != null) {
cart.addItem(
(Product) table.getRowData(),
(Integer) quantity.getValue());
}
return VisitResult.ACCEPT;
}
});
i have a jsf page that update employee table with this code....
i can get the data,but i can't update it with primefaces.and when i debug it,it doesn't do anything. i need help to update the data. thanks
this is my page controller
#ManagedBean(name = "homebean")
#ViewScoped
public class HomeController implements Serializable {
private Employee employee;
private List<Employee> employees;
private EmployeeeDAO employeeeDAO;
public HomeController() {
employeeeDAO = new EmployeeDAOImpl();
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public void editEmployee() throws SQLException {
Employee e = this.getEmployee();
employeeeDAO.update(e);
}
#PostConstruct
private void getListEmployees() {
employees = employeeeDAO.employees(20, 10);
}
}
and this is my DAO
public class EmployeeDAOImpl implements EmployeeeDAO, Serializable {
private PreparedStatement ps;
private ResultSet rs;
#Override
public void add(Employee emp) {
try (Connection c = ConnectionHelper.getConnection()) {
String sql = "UPDATE EMPLOYEES"
+ " SET FIRST_NAME = ?,"
+ " LAST_NAME = ?,"
+ " EMAIL = ? WHERE EMPLOYEE_ID=?";
ps = c.prepareStatement(sql);
ps.setString(1, emp.getFirstname());
ps.setString(2, emp.getLastname());
ps.setString(3, emp.getEmail());
ps.setInt(4, emp.getEmployeeId());
ps.executeUpdate();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} catch (SQLException ex) {
Logger.getLogger(EmployeeDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void update(Employee emp) throws SQLException {
try (Connection c = ConnectionHelper.getConnection()) {
String sql = "UPDATE EMPLOYEES "
+ " SET FIRST_NAME = ?,"
+ " LAST_NAME = ?,"
+ " EMAIL = ? WHERE EMPLOYEE_ID=?";
ps = c.prepareStatement(sql);
ps.setString(1, emp.getFirstname());
ps.setString(2, emp.getLastname());
ps.setString(3, emp.getEmail());
ps.setInt(4, emp.getEmployeeId());
ps.execute();
} catch (SQLException ex) {
Logger.getLogger(EmployeeDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public List<Employee> employees(int size, int lastRow) {
List< Employee> list = null;
try (Connection c = ConnectionHelper.getConnection()) {
String sql = "SELECT ROWNUM NUM,EMP.* FROM EMPLOYEES EMP ORDER BY ROWNUM";
ps = c.prepareStatement(sql);
rs = ps.executeQuery();
list = new ArrayList<Employee>();
while (rs.next()) {
Employee e = new Employee();
e.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
e.setFirstname(rs.getString("FIRST_NAME"));
e.setLastname(rs.getString("LAST_NAME"));
e.setEmail(rs.getString("EMAIL"));
e.setHireDate(rs.getDate("hire_date"));
e.setSalary(rs.getBigDecimal("salary"));
list.add(e);
}
} catch (Exception e) {
}
return list;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Employee getById(String id) {
return null;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and this is the jsf page..
<p:dataTable id="employeetable" value="#{homebean.employees}" var="emp" rows="10" paginator="true"
selection="#{homebean.employee}">
<p:column headerText="First Name">#{emp.firstname}</p:column>
<p:column headerText="First Name">#{emp.lastname}</p:column>
<p:column headerText="First Name"><h:outputText value="#{emp.salary}">
<f:convertNumber type="currency" currencySymbol="$ "/>
</h:outputText></p:column>
<p:column headerText="First Name">#{emp.email}</p:column>
<p:column width="50">
<p:commandButton value="Edit" oncomplete="editdialog.show();"
partialSubmit="true" update="#([id$=display])">
<f:setPropertyActionListener value="#{emp}" target="#{homebean.employee}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<h:form>
<p:dialog widgetVar="editdialog" id="edit" modal="true" appendToBody="true" resizable="false">
<h:panelGrid id="display" columns="2" cellspacing="4">
<h:outputText value="ID"/>
<p:inputText value="#{homebean.employee.employeeId}" disabled="true">
<f:convertNumber type="number"/></p:inputText>
<p:spacer/><p:spacer/>
<h:outputText value="First Name"/>
<h:outputText value="Last Name"/>
<p:inputText value="#{homebean.employee.firstname}"/>
<p:inputText value="#{homebean.employee.lastname}"/>
<h:outputText value="Email"/>
<h:outputText value="Salary"/>
<p:inputText value="#{homebean.employee.email}"/>
</h:panelGrid>
<p:separator/>
<p:commandButton value="save" action="#{homebean.editEmployee()}" partialSubmit="true"
update="#([id$=employeetable])" oncomplete="editdialog.hide();"/>
</p:dialog>
</h:form>
</ui:define>
finally i get the answer....we need to make sure that the property of Employee is correct. and have match datatype with our database...thanks all
I m trying to display data in jsf datable data from the database,ans in a same row i m displaying link for Edit. Now when user will clicked on edit button then it should be inputText from outputText. Here i have done coding for that but i can't change the textbox can u please help me? Thanks in advance.
ShowData.xhtml
<h:dataTable value="#{customerdata.customerList}" var="c"
styleClass="order-table" binding="#{customerdata.dataTable}"
headerClass="order-table-header" border="1" width="100%"
rowClasses="order-table-odd-row,order-table-even-row" rows="3">
<h:column>
<h:selectBooleanCheckbox></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="heder">User ID</f:facet>
<h:inputText value="#{c.cust_id}" size="10" rendered="#{c.editable}"/>
<h:outputLabel value="#{c.cust_id}" rendered="#{not c.editable}" />
</h:column>
<h:column>
<f:facet name="heder">User Name</f:facet>
<h:inputText value="#{c.cust_name}" size="10" rendered="#{c.editable}"/>
<h:outputLabel value="#{c.cust_name}" rendered="#{not c.editable}" />
</h:column>
<h:column>
<h:commandLink value="Update" rendered="#{c.editable}" action="#{customerdata.editAction(c)}" />
<h:commandLink value="Edit" action="#{customerdata.editAction(c)}" rendered="#{not c.editable}"/>
</h:column>
<h:column>
<h:commandLink value="Delete" action="#{customerdata.deleteAction(c)}" />
</h:column>
<!-- Footer Setting -->
<f:facet name="footer">
<h:panelGroup>
<h:commandButton value="prev" action="#{customerdata.pagePrevious}"
disabled="#{customerdata.dataTable.first == 0}" />
<h:commandButton value="next" action="#{customerdata.pageNext}"
disabled="#{customerdata.dataTable.first + customerdata.dataTable.rows
>= customerdata.dataTable.rowCount}" />
</h:panelGroup>
</f:facet>
</h:dataTable>
CustomerData.java
package model;
#ManagedBean(name="customerdata")
public class CustomerData implements Serializable {
private static final long serialVersionUID = 1L;
Connection con;
Statement smt;
HtmlDataTable dataTable;
//Customer cust=new Customer();
public List<Customer> getcustomerList() throws SQLException{
//System.out.println("in getcustomerlist");
List<Customer> list= new ArrayList<Customer>();
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/openid","root","root");
smt = con.createStatement();
String query="select * from jsftable";
ResultSet rs= smt.executeQuery(query);
while(rs.next()){
Customer cust = new Customer();
cust.setCust_id(rs.getInt("cust_id"));
cust.setCust_name(rs.getString("cust_name"));
cust.setHas_attachment(rs.getBoolean("has_attachment"));
System.out.println("in cusotomer data"+cust.isEditable());
//store all data into a List
list.add(cust);
}
}
catch(Exception e){
e.printStackTrace();
}
return list;
}
public void pageFirst() {
dataTable.setFirst(0);
}
public void pagePrevious() {
dataTable.setFirst(dataTable.getFirst() - dataTable.getRows());
System.out.println("Prevoius"+dataTable.getFirst());
}
public void pageNext() {
dataTable.setFirst(dataTable.getFirst() + dataTable.getRows());
System.out.println("Next"+dataTable.getFirst());
}
public void pageLast() {
int count = dataTable.getRowCount();
int rows = dataTable.getRows();
dataTable.setFirst(count - ((count % rows != 0) ? count % rows : rows));
}
public HtmlDataTable getdataTable() {
return dataTable;
}
public void setdataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public void showRow(){
System.out.println(dataTable.getRows());
}
public String deleteAction(Customer customer) throws SQLException{
//list.remove(customer);
//System.out.println(customer.cust_id);
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/openid","root","root");
smt = con.createStatement();
String query="delete from jsftable where cust_id="+customer.cust_id+"";
//ResultSet rs= smt.executeQuery(query);
smt.executeUpdate(query);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
public String editAction(Customer customer) {
//list.remove(customer);
System.out.println(customer.cust_id);
customer.setEditable(true);
return null;
}
}
Customer.java
public class Customer {
int cust_id;
String cust_name;
boolean has_attachment;
boolean editable;
String edit_value;
public String getEdit_value() {
System.out.println("in getter");
return edit_value;
}
public void setEdit_value(String editvalue) {
this.edit_value = editvalue;
}
public boolean isHas_attachment() {
System.out.println("in getter of has_attach");
return has_attachment;
}
public void setHas_attachment(boolean hasAttachment) {
has_attachment = hasAttachment;
}
public int getCust_id() {
System.out.println("in getter of cust_id");
return cust_id;
}
public void setCust_id(int custId) {
cust_id = custId;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String custName) {
cust_name = custName;
}
public boolean isEditable() {
//System.out.println("in isEditable"+editable);
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
//System.out.println("in set editable"+editable);
}
}
To be honest, I wonder how your code works at all. It has several major flaws.
You should start with
giving your managed bean a scope, the #ViewScoped seems the most appropriate (see here)
removing the database access from the getter method. Put it inside an #PostConstruct annotated method in your bean. Getter methods can be called several times during JSF lifecycle. The #PostConstruct method only after bean construction.
closing sql statement and connection when you are done (stmt.close() and con.close())
following bean field and method naming conventions: A private field xxx has a getter getXxx and a setter setXxx (the capitalization is important)
removing datatable binding. It is not necessary here.
I recommend to go through this simple CRUD example by BalusC and adapting it for your functional requirements.
Add id tag for datatable:
<h:dataTable value="#{customerdata.customerList}" var="c" id="customerDT"
styleClass="order-table" binding="#{customerdata.dataTable}"
headerClass="order-table-header" border="1" width="100%"
rowClasses="order-table-odd-row,order-table-even-row" rows="3">
Add in your edit CommandButton update tag:
But why you don't use the inplace component using primefaces? http://www.primefaces.org/showcase-labs/ui/inplace.jsf (need a save button)