How to use jsf to edit some data in a database - mysql

i have an app that displays some data entered in a databse, this should allow a user to delete or edit this information, so far i have managed to get it to delete, but i am wondering, what is the best method for editting the data, what i would like if possible is to click on an edit button on a page already populated with the data and this to take the user to a webpage that has only that selected records pre populating textboxs and then allow the user to edit these, how would i do this ?
this is how i am deleting a row from the database
<p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
User ID
</f:facet>
#{u.userID}
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
#{u.name}
</p:column>
<p:column>
<f:facet name="header">
Email
</f:facet>
#{u.email}
</p:column>
<p:column>
<f:facet name="header">
Address
</f:facet>
#{u.address}
</p:column>
<p:column>
<f:facet name="header">
Created Date
</f:facet>
#{u.created_date}
</p:column>
<p:column>
<f:facet name="header">
Delete
</f:facet>
<h:commandButton value="Delete" action="#{user.delete(u.userID)}" />
</p:column>
<p:column>
<f:facet name="header">
Edit
</f:facet>
<h:commandButton value="Edit" action="{user.delete(u.userID)}" />
</p:column>
</p:dataTable>
and this is the backing bean allowing me to delete
public void delete(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "DELETE FROM user1 WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row deleted successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks
EDIT
i have figured out how to update the data, my question is now simply, how do i get the data from a row and populate a new page with input boxes with the selected data Or even better would be to edit the data live in the table, is this possilbe

instead of taking the user to a second page to edit the data, you can make use of primfaces DataTable - Row Editing see this
http://www.primefaces.org/showcase/ui/datatableRowEditing.jsf

send user object only with editdata method
<h:commandButton value="Edit" action="{user.editData(u)}" />
then you can use prepared statement with update like shown below
String sql = "UPDATE user1 set name = '"+name+"', email = '"+ email +"', address = '"+address+"' WHERE userId=" + userID;
I will suggest try hibernate.

Related

How to Persist Rows after Reordering p:dataTable rows in backing bean

I am using Primefaces Datatable to show the data, i have used draggablerows and trying to save/persist the reordering of the rows in the backing bean
with
I can get the from and to indexes from the event. But, I was not able to persist the row reordering:
<p:dataTable value="#{EmployeeHandler.model.employees}" var="employee" draggableRows="true">
<p:ajax event="rowReorder" listener="#{EmployeeHandler.onRowReorder}"/>
<p:column>
<h:outputText value="#{employee.id}"/
</p:column>
<p:column>
<h:outputText value="#{employee.firstName}"/
</p:column>
<p:column>
<h:outputText value="#{employee.lastName}"/
</p:column>
</p:dataTable>
I tried
public void onRowReorder(ReorderEvent event) {
List<Employee> employees = model.getEmployees (new order in the employees list);
fromIndex = event.getFromIndex();
toIndex = event.getToIndex();
// swapping indexes
Collections.swap(employees, fromIndex, toIndex);
}

How to set null value selectone menu jsf

I am using PrimeFaces 5.1 , I have a field Cumulative indicator which is a select drop down wit Y/N/select, when I update the value to Y/N the edit/update is happening fine, but when I chose select as the drop down value it does not update it to null. I am able to set the value to null from the backend. When I chose select as the drop down value it should update to null instead it shows the previous value(Y/N) that is saved in the database. The below is my code xhtml, java bean and the update query. Please advice why its not updating the value to null value.
I tried putting the drop down value itemValue="#{null}" but that didn't work as mentioned in this post How to save Null value with selectone dropdown
Below is my xhtml:
<p:column headerText="Cumulative Indicator" width="60">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#
{AcctRefRecord.cumIndicator}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{AcctRefRecord.cumIndicator}"
label="Cumulative Indicator">
<f:selectItem
itemLabel="--Select--" itemValue="" />
<f:selectItem
itemValue="Y" />
<f:selectItem
itemValue="N" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:dataTable id="dtable" var="AcctRefRecord"value="#
{AcctRefMBean.
AcctRefRecords}" editable="true"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink}
{PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}
{RowsPerPageDropdown}" >
<p:ajax event="rowEdit" listener="#
{AcctRefMBean.onRowEdit}" update=":dtableform:msgs" resetValues="true"/>
<p:ajax event="rowEditCancel" listener="#
{AcctRefMBean.onRowCancel}" update=":dtableform:msgs"/>
Below is my javaBean:
//retrive the record/row of type
AcctRefTo on which edit even occurred
AcctRefTo to = (AcctRefTo)
event.getObject();
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
facesContext.getExternalContext().getSession(false);
String userId = (String)
session.getAttribute(WebAppConstants.CURRENT_USER_ID);
if (userId == null) {
userId = WebAppConstants.DEFAULT_CURRENT_USER_ID;
}
to.setUpdatedByUserID(userId);
updateRecord(to);
FacesMessage msg = new FacesMessage("Reference Data Updated for Account#"
+ to.getAcctNbr());
FacesContext.getCurrentInstance
().addMessage("null", msg);
}
/**
* #param to
* updates the given to in DB accordingly
*/
public void updateRecord(AcctRefTo to) {
jetSessionFacadebean.updateAccntRef(to);
}
Below is my updateQuery:
<key><value>updateAcctgRef</value></key>
<value>
update acct_ref set
cd_val=?,
dt_eff_end=?,
ind_bal=?,
ind_bal_acct_type=?,
ind_cum=?,
ind_net=?,
ind_net__bal_type=?,
ind__rcn=?,
ind_b=?,
nbr_gl_acct_yeb_offst=?,
nbr_gl_acct_net_unam_bal=?,
cd_fee_cat_type=?,
id_lst_updt=?,

PrimeFaces <p:cellEditor> not changing value of variable

I've done some research and haven't been able to find anything that directly addresses the problem I've been having.
I have a DataTable column that is editable (by cell) and I have the ability to click on the cell, enter a new number in the cell editor box, but when I hit the cell editor closes but does not save the new value (same thing happens if you just click off and don't hit enter).
Here is the Code Snippet
<h:form>
<c:forEach items="#{extensionsBean.getPhases()}" var="phase">
<p:fieldset legend="#{phase.getPhaseName()}">
<p:dataTable value="#{extensionsBean.getActivities(phase)}" var="activity" editable="true" editMode="cell">
<p:column>
<f:facet name="header">
<h:outputText value="Actual Hours"/>
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{activity.getEstimateDetail().actualHours}"/>
</f:facet>
<f:facet name="input">
<h:inputText value="#{activity.getEstimateDetail().actualHours}" />
</f:facet>
</p:cellEditor>
//the rest of the closing tags are present
Any suggestions would be great! For the record, I have basically the exact same setup in a different xhtml page and I'm able to edit each of the cells without a problem. Not sure what's causing this one to bug out on me.
Add Ajax event cellEdit and store the values
Add ajax event celledit and where do you want save the value you can save it.
Code is below in my project
Xhtml page(Primefaces):
<p:dataTable var="my" value="#{java.custom_info}" editMode="cell" editable="true" style="font-size: 12px">
<p:ajax event="cellEdit" listener="#{java.custom_detail}"/>
<p:column style="background: white">
<h:outputText value="First Name"/>
</p:column>
<p:column style="background: white">
<p:cellEditor>
<f:facet name="output"> <h:outputText value="#{my.first}"/> </f:facet>
<f:facet name="input"><p:inputText value="#{my.first}" placeholder="Enter First Name" style="width:93%"/></f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
Java Class
public void custom_detail(CellEditEvent event){
String old_str = (String) event.getOldValue();
String first_name = (String) event.getNewValue();
System.out.println("update method reached..."+first_name);
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
Query db = new Query();
Customer bean = new Customer();
if(session!=null){
if(((String)session.getAttribute("login"))!=null){
Calendar currentDate=Calendar.getInstance();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datenow=format.format(currentDate.getTime());
session.setAttribute("firstname", first_name);
session.setAttribute("modified_date",datenow);
bean.setFirst(first_name);
bean.setUsrid((String)session.getAttribute("user"));
bean.setUsr_modified(datenow);
db.update_personalinfo(bean);
}
}
}

Primefaces ActionListener not fired if h:inputHidden in the datatable

I am using Primefaces 5.1 and have this strange behaviour.
If in my dataTable I have h:inputHidden then mymethod() is not fired.
The method is fired if I remove it.
<p:dataTable id="tablerisorse" value="#{myBean.resources}" var="resource"
rowStyleClass="#{(rowIndex mod 2) eq 0 ? 'oddRow' : 'evenRow'}"
rowIndexVar="rowIndex"
emptyMessage="Empty" headerClass="header">
<p:column>
<h:inputHidden id="id_user" value="#{resource.user}"/>
<f:facet name="header">
<h:outputText value="Surname"/>
</f:facet>
<h:outputText value="#{resource.surname}" />
</p:column>
<p:column>
<p:commandLink id="linkdet" actionListener="#{myBean.mymethod}" ajax="false"onstart="progressbar()" oncomplete="hideprogressbar()">
<p:graphicImage value="images/res.png" style="{border: 0}"></p:graphicImage>
</p:commandLink>
</p:column>
</p:dataTable>
the method is:
public void impegnirisorsa(ActionEvent ae) {
// TODO Auto-generated method stub
HtmlInputHidden uicid_user = (HtmlInputHidden) ae.getComponent().findComponent("id_user");
String id_user = ""+uicid_user .getValue();
System.out.println("id_user"+id_user);
}
I wonder what the problem could be and which workarounds could I use.

how to get the database values by using hibernate and how to display that values in a primefaces dataTable?

Here i have some doubts.If you know the answer please post here.
How to get the list of values into database table by using hibernate?
How to display that values into primefaces dataTable?
Here i am posting what i am trying .see below
<p:dataTable id="users" value="#{user.listUsers}" var="user"
sortBy="user.id" rows="10" style="width: 30%">
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:outputText value="#{user.id}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.name}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Surname" />
</f:facet>
<h:outputText value="#{user.surName}" />
</p:column>
</p:dataTable>
Here i am finding the answer how to display a table values into primefaces dataTable.
Here i am placing what i am trying code.
<p:dataTable value="#{actions.messages}" var="act">
<p:column style="width:10%;text-align:left" filterBy="#{act.id}" >
<f:facet name="header">
<h:outputText value="ID" id="id" />
</f:facet>
<h:outputText value="#{act.id}" />
</p:column>
<p:column style="width:20%;text-align:left"
sortBy="#{act.action}">
<f:facet name="header">
<h:outputText value="Customer" id="customer" />
</f:facet>
<h:outputText value="#{act.action}" />
</p:column>
<p:column style="width:40%;text-align:left"
sortBy="#{act.scheduled}">
<f:facet name="header">
<h:outputText value="Date" />
</f:facet>
<h:outputText value="#{act.scheduled}" />
</p:column>
<p:column style="width:30%;text-align:left"
sortBy="#{act.status}">
<f:facet name="header">
<h:outputText value="Action" />
</f:facet>
<h:outputText value="#{act.status}" />
</p:column>
</p:dataTable>
Here is the hibernate dao class name called ActionsDao
public class ActionsDao {
public Session session;
public ArrayList<Actions> getActions() {
session = Util.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
try {
#SuppressWarnings("unchecked")
ArrayList<Actions> actionsList = (ArrayList<Actions>) session
.createQuery("from Actions").list();
tx.commit();
boolean found = false;
for (Actions actions : actionsList) {
Actions action = new Actions();
action.setId(actions.getId());
action.setAction(actions.getAction());
action.setActual(actions.getActual());
action.setAssignedBy(actions.getAssignedBy());
action.setAssignedTo(actions.getAssignedTo());
action.setScheduled(actions.getScheduled());
action.setOutcome(actions.getOutcome());
action.setStatus(actions.getStatus());
actionsList.contains(action);
found = true;
}
if (found) {
return actionsList;
} else {
return null;
}
} catch (Exception e) {
System.out.println("Error In getActions() -->" + e.getMessage());
return (null);
} finally {
session.close();
}
}
}
Here is the bean class i am developing name called Actions.
#ManagedBean(name = "actions", eager = true)
#SessionScoped
public class Actions implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String action;
private String assignedTo;
private String assignedBy;
private Date scheduled;
private Date actual;
private String outcome;
private String status;
//write here setter & getter methods of the above properties
public ArrayList<Actions> getMessages() {
ActionsDao dao = new ActionsDao();
return dao.getActions();
}
}
you can use the annotations or hbm file that yours choice to map the bean class.
Here i am using only mapping file why because, first i am trying to create annotations but it raised some problems that jar files are some problem.your using the correct jar files that not a problem you can continue the annotations otherwise hbm file is best.