I am developing an application using jsf2.0, richfaces 4.0, tomcat 6.0. On a page I am trying to delete a row . But when I click the delete icon, sometimes popup panel does not appear and when it is shown , nothing happens on clicking the delete button.
Following is my .xhtml file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:composition template="template.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="meetingId" required="true" value="#{meetingBean.selectedMeetId}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h3>List of Employees in selected meeting</h3>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<c:if test="#{! empty meetingBean.selectedMeeting}">
<c:set target="#{flash}" property="selectedMeeting"
value="#{meetingBean.selectedMeeting}" />
</c:if>
<c:if test="#{! empty flash.selectedMeeting}">
<c:set target="#{meetingBean}" property="selectedMeeting"
value="#{flash.selectedMeeting}" />
</c:if>
<rich:extendedDataTable value="#{meetingBean.selectedMeeting.employees}" var="empMeet" border="1" id="table">
<rich:column>
<f:facet name="header">Employee Id</f:facet>
#{empMeet.empId}
</rich:column>
<rich:column>
<f:facet name="header"> Employee Name</f:facet>
#{empMeet.firstName} #{empMeet.lastName}
</rich:column>
<rich:column>
<a4j:commandLink execute="#this" render="#none" oncomplete="#{rich:component('confirmPanel')}.show();">
<h:graphicImage value="/images/icons/delete.gif" alt="delete" />
<a4j:param value="#{empMeet.empId}" assignTo="#{meetingBean.deleteEmpId}" />
</a4j:commandLink>
</rich:column>
</rich:extendedDataTable>
<a4j:jsFunction name="removeEmp" action="#{meetingBean.deleteEmployee}" render="table" execute="#this"
oncomplete="#{rich:component('confirmPanel')}.hide();" >
</a4j:jsFunction>
<rich:popupPanel id="statPane" autosized="true">
<h:graphicImage value="/images/ai.gif" />
Please wait...
</rich:popupPanel>
<rich:popupPanel id="confirmPanel" autosized="true" >
Are you sure you want to delete the row?
<a4j:commandButton value="Cancel" onclick="#{rich:component('confirmPane')}.hide(); return false;" />
<a4j:commandButton value="Delete" onclick="removeEmp(); return false;" />
</rich:popupPanel>
<h:commandButton action="addEmpMeeting" value="Invite More Employees" />
</h:form>
</ui:define>
</ui:composition>
</html>
Following is my bean class:
package com.drishti.apps.mommanager.meeting;
/**
* this class represents a meeting object
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.richfaces.component.SortOrder;
import com.drishti.apps.mommanager.employee.AbstractBacking;
import com.drishti.apps.mommanager.employee.EmployeeEntity;
import com.drishti.apps.mommanager.employee.EmployeeService;
#ManagedBean
public class MeetingBean extends AbstractBacking {
#ManagedProperty(value = "#{requestScope}")
private Map<String, Object> requestMap;
private int meetingId;
private Date meetingTime;
private String agenda;
private String result;
public String[] empIdsInMeeting;
private List<EmployeeEntity> employees = new ArrayList<EmployeeEntity>();
private Integer selectedMeetId;
private MeetingEntity selectedMeeting;
private String selectedAgenda;
private int deleteEmpId;
private EmployeeEntity deletableEmployee;
/**
* this method is used to load a meeting object when it is being updated
*
* #param cse
*/
public void loadMeeting(ComponentSystemEvent cse) {
if (null == getSelectedMeeting()) {
Integer meetId = getSelectedMeetId();
if (meetId == null) {
meetId = (Integer)getFlash().get("selectedMeetId");
}
if (meetId == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
MeetingEntity meet = MeetingService.getCurrentInstance().getMeetingForId(meetId);
if (meet == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
getFlash().put("selectedMeeting", meet);
getSelectedMeeting();
}
}
}
}
/**
* this method updates a meeting object
*
* #return
*/
public void updateMeeting() {
//String result = null;
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.updateMeeting(meeting);
getFlash().clear();
//result = "meetUpdated";
//return result;
}
/**
* this method adds a meeting object to database
*
* #return
*/
public void addMeeting() {
MeetingEntity meeting = (MeetingEntity)getRequestMap().get("meetingEntity");
MeetingService.getCurrentInstance().addMeeting(meeting);
//return "successMeeting";
}
/**
* this method is used to delete a meeting
*/
public void deleteMeeting(){
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.deleteMeeting(meeting);
getFlash().clear();
}
/**
* returns data model containing all meetings present in database
*
* #return
*/
public DataModel<MeetingEntity> getMeetingList() {
DataModel<MeetingEntity> meetingList = new ListDataModel<MeetingEntity>(MeetingService.getCurrentInstance()
.getMeetings());
return meetingList;
}
/**
* returns list containing agenda of all meetings
*
* #return
*/
public ArrayList<String> getAgendaList() {
ArrayList<String> agendaList = new ArrayList<String>();
agendaList.add(getSelectedMeeting().getAgenda());
return agendaList;
}
/**
* this method is used to get a list of employee names for employees who are not invited to a particular meeting
*/
public List<String> getEmpNameIdList() {
List<EmployeeEntity> employeeList = new ArrayList<EmployeeEntity>(EmployeeService.getCurrentInstance()
.getEmployeeList());
List<String> uninvitedEmpList = new ArrayList<String>();
ListIterator<EmployeeEntity> empIter = employeeList.listIterator();
ArrayList<Integer> idList = new ArrayList<Integer>();
while (empIter.hasNext()) {
idList.add(empIter.next().getEmpId());
}
MeetingEntity meeting = getSelectedMeeting();
List<EmployeeEntity> employees = meeting.getEmployees();
if(employees!=null){
ListIterator<EmployeeEntity> invitedIter = employees.listIterator();
ArrayList<Integer> invitedIds = new ArrayList<Integer>();
while (invitedIter.hasNext()) {
invitedIds.add(invitedIter.next().getEmpId());
}
idList.removeAll(invitedIds);
}
EmployeeEntity emp;
ListIterator<Integer> idIter = idList.listIterator();
while (idIter.hasNext()) {
int id = idIter.next();
emp = EmployeeService.getCurrentInstance().getEmployeeForId(id);
uninvitedEmpList.add(emp.getFirstName() + " " + emp.getLastName() + " (" + emp.getEmpId() + ")");
}
return uninvitedEmpList;
}
/**
* this method adds employees to a meeting
* #return
*/
public String addEmpToMeeting() {
MeetingEntity meeting = MeetingService.getCurrentInstance().getMeetingFromAgenda(
getSelectedMeeting().getAgenda());
for (int i = 0; i < empIdsInMeeting.length; i++) {
String id = null;
id = empIdsInMeeting[i].substring(empIdsInMeeting[i].lastIndexOf("(") + 1,
empIdsInMeeting[i].lastIndexOf(")"));
int empId = Integer.parseInt(id);
meeting.getEmployees().add(EmployeeService.getCurrentInstance().getEmployeeForId(empId));
}
MeetingService.getCurrentInstance().addMeeting(meeting);
return "empAddedToMeeting";
}
/**
* this method removes employee from a meeting
* #return
*/
public void deleteEmployee(){
List<EmployeeEntity>inviteEmployees=getSelectedMeeting().getEmployees();
EmployeeEntity emp=getDeletableEmployee();
inviteEmployees.remove(emp);
}
public Integer getSelectedMeetId() {
return selectedMeetId;
}
public void setSelectedMeetId(Integer selectedMeetId) {
this.selectedMeetId = selectedMeetId;
setSelectedMeeting(MeetingService.getCurrentInstance().getMeetingForId(selectedMeetId));
}
public MeetingEntity getSelectedMeeting() {
return selectedMeeting;
}
public void setSelectedMeeting(MeetingEntity selectedMeeting) {
this.selectedMeeting = selectedMeeting;
}
public Map<String, Object> getRequestMap() {
return requestMap;
}
public void setRequestMap(Map<String, Object> requestMap) {
this.requestMap = requestMap;
}
public Date getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(Date meetingTime) {
this.meetingTime = meetingTime;
}
public String getAgenda() {
return agenda;
}
public void setAgenda(String agenda) {
this.agenda = agenda;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public int getMeetingId() {
return this.meetingId;
}
public List<EmployeeEntity> getEmployees() {
return employees;
}
public String[] getEmpIdsInMeeting() {
return empIdsInMeeting;
}
public void setEmpIdsInMeeting(String[] empIdsInMeeting) {
this.empIdsInMeeting = empIdsInMeeting;
}
public void setEmployees(List<EmployeeEntity> employees) {
this.employees = employees;
}
public String getSelectedAgenda() {
return selectedAgenda;
}
public void setSelectedAgenda(String selectedAgenda) {
this.selectedAgenda = selectedAgenda;
}
public void setTimeOrder(SortOrder timeOrder) {
this.timeOrder = timeOrder;
}
public int getDeleteEmpId() {
return deleteEmpId;
}
public void setDeleteEmpId(int deleteEmpId) {
this.deleteEmpId = deleteEmpId;
setDeletableEmployee(EmployeeService.getCurrentInstance().getEmployeeForId(deleteEmpId));
}
public EmployeeEntity getDeletableEmployee() {
return deletableEmployee;
}
public void setDeletableEmployee(EmployeeEntity deletableEmployee) {
this.deletableEmployee = deletableEmployee;
}
}
Please help .
The problem is probably related to JSF overriding your custom onclick.
The work-around would be to use onmousedown instead of onclick, with the potential caveat described here:
http://blogs.oracle.com/jtb/entry/jsf_h_commandlink_and_onclick
i had the same problem few days ago, changing the return to true may work for you.
Related
I'm using WildFly 9.0 and IntelliJ 14 Ultimate
I can add items to the cart- and they can be viewed using a PrimeFaces data table on ViewCart.xhtml
There is a button to delete each cart item- which works.
Faces-config has been edited to return back to the ViewCart.xhtml page when the button is clicked; which seems to be the case.
The PROBEM: Cart is still showing the original list, before the item was deleted.
If I go to the product catalogue and return back to ViewCart.xhtml, the executed changes are reflected in the cart. Please can someone help?
Here is the ViewCart.xhtml page
<body>
<h:outputText value="Cart List"
style="font-family: Verdana, Helvetica, sans-serif;font-size: 18px; font-weight: 900;" />
<h:form name="ViewProductsManagedBean">
<p:dataTable id="cartTable" var="cartList"
value="#{ViewProductsManagedBean.cart}" <p:column>
<f:facet name="header">
<h:outputText value="Delete Cart Item "
style="font-family: Verdana, Helvetica, sans-serif;font-size: 16px;" />
</f:facet>
<h:commandButton action="#{ViewProductsManagedBean.removeItemFromCart(cartList.itemcode)}"> </h:commandButton>
</p:column>
</f:facet>
</p:dataTable>
</h:form>
</body>
</html>
now the managed bean:
#ManagedBean(name="ViewProductsManagedBean")
#RequestScoped
public class ViewProductsManagedBean {
public String removeItemFromCart(String itemCode){
return cartFunctions.removeItemFromCart(itemCode);
}
}
The facade that "talks" to the business logic
#Stateful
#SessionScoped
public class CartFacade {
public String removeItemFromCart(String itemCode){
return cartBean.removeItemFromCart(itemCode);
}
}
The cart been looks like follows:
#Stateful
#Local(ShoppingCartLocal.class)
#Remote(ShoppingCart.class)
#SessionScoped
public class ShoppingCartBean implements ShoppingCartLocal, ShoppingCart {
public String removeItemFromCart(String itemCode){
for(Orderitem ord:cartItems){
if(itemCode.equals(ord.getItemcode())){
cartItems.remove(ord);
System.out.println("Item removed " + itemCode);
}
}
return "ViewCart";
}
here is the full cart bean
package com.shop.cart;
/**
* Created by LalinPethiyagoda on 30/07/2015.
*/
#Stateful
#Local(ShoppingCartLocal.class)
#Remote(ShoppingCart.class)
#SessionScoped
public class ShoppingCartBean implements ShoppingCartLocal, ShoppingCart {
#PersistenceContext(unitName ="Shop")
private EntityManager cartEntityManager;
private CustomerManager customerManagerBean;
private CopyOnWriteArrayList<Orderitem> cartItems = new CopyOnWriteArrayList<>();
private List<Orderitem> cartItemsReturn = new ArrayList<>();
public void setCartItems(CopyOnWriteArrayList<Orderitem> cartItems) {
this.cartItems = cartItems;
}
private CustomerEntity customer;
public ShoppingCartBean(){}
#Override
public List<Orderitem> getCartItemsReturn() {
return cartItemsReturn;
}
public void setCartItemsReturn(List<Orderitem> cartItemsReturn) {
this.cartItemsReturn = cartItemsReturn;
}
#Override
public boolean addCartItem(ProductEntity product, int quantityPurchased){
com.shop.entity.Orderitem basketItem=new Orderitem();
Locale currentLocale = new Locale("en", "GB");
double subTotal;
// check for duplicate entry.
for (Orderitem itemsIntheCart : cartItems) {
if (itemsIntheCart.getItemcode().equals(product.getItemcode())) {
return false;
}
}
basketItem.setItemcode(product.getItemcode());
basketItem.setItemdescription(product.getItemdescription());
basketItem.setUnitprice(product.getUnitprice());
basketItem.setQuantitypurchased(quantityPurchased);
subTotal = quantityPurchased * basketItem.getUnitprice();
Double currencyAmount = new Double(subTotal);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
currencyFormatter.format(currencyAmount);
basketItem.setSubtotal(currencyAmount);
cartItems.add(basketItem);
return true;
}
public String removeItemFromCart(String itemCode){
for(Orderitem ord:cartItems){
if(itemCode.equals(ord.getItemcode())){
cartItems.remove(ord);
System.out.println("Item removed " + itemCode);
}
}
return "ViewCart";
}
#Override
public CopyOnWriteArrayList<Orderitem> viewCartItems(){
return this.cartItems;
}
#Override
public CopyOnWriteArrayList<Orderitem> getCartItems(){
CopyOnWriteArrayList<Orderitem> cartItemList = this.cartItems;
for(Orderitem x:cartItemList){
System.out.println(x.getItemdescription());
}
return cartItemList;
}
public CustomerEntity getCustomer() {
return customer;
}
public void setCustomer(CustomerEntity customer) {
this.customer = customer;
}
public void removeCartItem(int itemCode){
System.out.println("hello");
}
#Override
public double getTotal(){
double total=0;
for(Orderitem bItem:getCartItems()){
total = total + bItem.getSubtotal();
}
return total;
}
#PreDestroy
public void exit(){
persistCartItems();
stopSession();
}
#Override
public void persistCartItems() {
// TODO Auto-generated method stub
}
#Remove
public void stopSession(){
System.out.println("saved- all done - object detached from object pool");
}
public void assignCartToCustomer(){
customer = customerManagerBean.getVerifiedCustomer();
}
public CustomerEntity getCustomerAssociatedWithTheCart(){
return this.customer;
}
#Remove
public void remove() {
cartItems = null;
}
#Override
public void incrementQuantity() {
}
#Override
public void decrementQuantity() {
}
}
My web application not loading data when I implements model driven in action class. It works fine when remove modeldriven.
action class :
package action;
import action.UserBean;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import service.OrganisationBo;
import model.AtDivision;
import model.AtOrganisation;
public class OraganisationAction extends ActionSupport implements ModelDriven<UserBean> {
private String uname;
private String passwd;
private String sidx;
// Search Field
private String searchField;
// The Search String
private String searchString;
// he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
private String searchOper;
// Your Total Pages
private Integer total = 0;
//Your result List
private List<UserBean> gridModel;
//get how many rows we want to have into the grid - rowNum attribute in the grid
private Integer rows = 0;
//Get the requested page. By default grid sets this to 1.
private Integer page = 0;
// sorting order - asc or desc
private String sord;
private boolean loadonce = false;
// All Record
private Integer records = 0;
private String includepage;
private List<UserBean> myList;
private String oper;
private String id;
private String contact;
private String country;
UserBean ubs = new UserBean();
private AtOrganisation org = new AtOrganisation();
private AtDivision div = new AtDivision();
private List<AtOrganisation> orglist = new ArrayList<AtOrganisation>();
OrganisationBo orgBo;
private String aoId;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getSidx() {
return sidx;
}
public void setSidx(String sidx) {
this.sidx = sidx;
}
public String getSearchField() {
return searchField;
}
public void setSearchField(String searchField) {
this.searchField = searchField;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchOper() {
return searchOper;
}
public void setSearchOper(String searchOper) {
this.searchOper = searchOper;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<UserBean> getGridModel() {
return gridModel;
}
public void setGridModel(List<UserBean> gridModel) {
this.gridModel = gridModel;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public String getSord() {
return sord;
}
public void setSord(String sord) {
this.sord = sord;
}
public boolean isLoadonce() {
return loadonce;
}
public void setLoadonce(boolean loadonce) {
this.loadonce = loadonce;
}
public Integer getRecords() {
return records;
}
public void setRecords(Integer records) {
this.records = records;
}
public String getIncludepage() {
return includepage;
}
public void setIncludepage(String includepage) {
this.includepage = includepage;
}
public List<UserBean> getMyList() {
return myList;
}
public void setMyList(List<UserBean> myList) {
this.myList = myList;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public List<AtOrganisation> getOrglist() {
return orglist;
}
public void setOrglist(List<AtOrganisation> orglist) {
this.orglist = orglist;
}
public String getAoId() {
return aoId;
}
public void setAoId(String aoId) {
this.aoId = aoId;
}
public void setOrgBo(OrganisationBo orgBo) {
this.orgBo = orgBo;
}
public AtDivision getDiv() {
return div;
}
public void setDiv(AtDivision div) {
this.div = div;
}
public AtOrganisation getOrg() {
return org;
}
public void setOrg(AtOrganisation org) {
this.org = org;
}
public String execute() throws Exception {
myList = DAO.buildList();
setRecords(DAO.count());
int to = (getRows() * getPage());
int from = to - getRows();
if (to > getRecords()) {
to = getRecords();
}
if (loadonce) {
setGridModel(myList);
} else {
if (searchString != null && searchOper != null && !searchString.equals("") && !searchOper.equals("")) {
System.out.println("Searching within Database");
if (searchOper.equalsIgnoreCase("cn")) {
// setGridModel(DAO.findbyName(searchString));
}
} else {
System.out.println("Not Searching Anywhere");
//setGridModel(DAO.find(from, to));
System.out.println("dili 4444");
setGridModel(myList);
}
}
total = (int) Math.ceil((double) getRecords() / (double) getRows());
System.out.println("tot " + total);
System.out.println(gridModel.size());
return SUCCESS;
}
#Override
public UserBean getModel() {
return ubs;
}
}
Struts.xml :
<package name="default" extends="struts-default,json-default">
<action name="gridaction" class="action.OraganisationAction" >
<result name="success" type="json"/>
</action>
</package>
</struts>
index.jsp :
<%--
Document : index
Created on : 15 Nov, 2011, 11:45:45 PM
Author : XCoder
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<%#taglib prefix="sj" uri="/struts-jquery-tags" %>
<%#taglib prefix="sjg" uri="/struts-jquery-grid-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<sj:head jquerytheme="start" jqueryui="true"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<s:url id="remoteurl" action="gridaction"/>
<sjg:grid
id="sjgrid"
caption="Grid Model"
dataType="json"
href="%{remoteurl}"
pager="true"
rowList="10,20,100"
rowNum="5"
navigator="true"
width="999"
navigatorSearchOptions="{sopt:['eq','ne','lt','gt']}"
navigatorAddOptions="{height:280,reloadAfterSubmit:true}"
navigatorEditOptions="{height:280,reloadAfterSubmit:false}"
navigatorEdit="false"
navigatorView="false"
navigatorDelete="true"
navigatorDeleteOptions="{height:280,reloadAfterSubmit:true}"
gridModel="gridModel"
editurl="%{editurl}"
editinline="true"
onSelectRowTopics="rowselect"
>
<sjg:gridColumn name="iduser" formatter="integer" title="iduser" key="true" hidden="true"/>
<sjg:gridColumn name="uname" title="Username" editable="true" align="center"
editrules="{required:true}"
/>
<sjg:gridColumn name="passwd" title="Password" editable="true" align="center"
editrules="{required:true}"
/>
<sjg:gridColumn name="country" title="Country" editable="true" align="center"
edittype="select"
editoptions="{dataUrl:'%{selecturl}'}"
/>
<sjg:gridColumn name="contact" title="Contact No" editable="true" align="center"
editrules="{required:true,number:true,integer:true}"
/>
</sjg:grid>
</body>
</html>
cant we implement model driven with jqgrid or my code is wrong?
EDIT:
Just figure out that modeldriven work fine with old lib set
struts2-convention-plugin-2.1.8,
struts2-core-2.1.8.1,
struts2-jquery-grid-plugin-2.5.0,
struts2-jquery-plugin-2.5.0,
struts2-json-plugin-2.1.8,
xwork-core-2.1.6.
But when I update project into new version of struts grid is not fill with data. New lib set is as follows :
struts2-convention-plugin-2.3.16,
struts2-core-2.3.16,
struts2-jquery-grid-plugin-3.7.1,
struts2-jquery-plugin-3.7.0 ,
struts2-json-plugin-2.3.16.3
xwork-core-2.3.16.
Anyone knows what happening here?
i want to create dynamic textbox in jsf2 in datatable having textboxes based on clicking add row button. Iam a newbie for jsf programming.Can someone tell me a basic example for dynamic for generation . I have read ui:repeatand c:foreach but i need some practical example.
For your sample,
xhtml code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
<h:form id="form1">
<h:commandButton value="Add new Row" actionListener="#{myBean.addNewEmployee}"/>
<h:dataTable value="#{myBean.employeeList}" var="emp">
<h:column>
<f:facet name="header">
Employee Id
</f:facet>
#{emp.empId}
</h:column>
<h:column>
<h:inputText value="#{emp.empName}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
jsf manged bean
#ManagedBean
#ViewScoped
public class MyBean implements Serializable {
List<Employee> employeeList;
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public void addNewEmployee(ActionEvent event) {
employeeList.add(new Employee(employeeList.size(), null));
}
#PostConstruct
public void init() {
employeeList = new ArrayList<Employee>();
employeeList.add(new Employee(1, "Emp1"));
employeeList.add(new Employee(2, "Emp2"));
}
public MyBean() {
}
}
Employee Class(You can use your entity class)
public class Employee {
Integer empId;
String empName;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Employee(Integer empId, String empName) {
this.empId = empId;
this.empName = empName;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Employee other = (Employee) obj;
if (this.empId != other.empId && (this.empId == null || !this.empId.equals(other.empId))) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 41 * hash + (this.empId != null ? this.empId.hashCode() : 0);
return hash;
}
}
You can directly use above code. And also I suggest to use PrimeFaces component for advanced manipulations
I'm trying execute the DataTable example avaiable on Primefaces Showcase. All functions works but when i select a row, the value of the selected row isn't displayed on my <p:dialog>.
I've already checked all alternatives and nothing works. Could someone help me?
I'm using Primefaces 3.3 and glassfish 3.0.1. Here goes my code:
dataTableComplex.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<body>
<h:form id="form">
<p:dataTable var="car" value="#{tableBean.cars}" rowKey="#{car.model}" paginator="true" rows="10"
selection="#{tableBean.selectedCar}" selectionMode="single" id="carsTable">
<p:ajax event="rowSelect" update=":form:display" oncomplete="carDialog.show()" />
<f:facet name="header">
List of Cars
</f:facet>
<p:column headerText="Model" sortBy="#{car.model}" filterBy="#{car.model}" id="model">
#{car.model}
</p:column>
<p:column headerText="Year" sortBy="#{car.year}" filterBy="#{car.year}" id="year">
#{car.year}
</p:column>
<p:column headerText="Manufacturer" sortBy="#{car.manufacturer}" filterBy="#{car.manufacturer}" id="manufacturer">
#{car.manufacturer}
</p:column>
<p:column headerText="Color" sortBy="#{car.color}" filterBy="#{car.color}" id="color">
#{car.color}"
</p:column>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="carDialog" resizable="false"
width="200" showEffect="explode" hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Model:" />
<h:outputText value="#{tableBean.selectedCar.model}" id="model"/>
<h:outputText value="Year:" />
<h:outputText value="#{tableBean.selectedCar.year}" id="year"/>
<h:outputText value="Manufacturer:" />
<h:outputText value="#{tableBean.selectedCar.manufacturer}" id="manufacturer"/>
<h:outputText value="Color:" />
<h:outputText value="#{tableBean.selectedCar.color}" id="color"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
TableBean.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ViewScoped
#ManagedBean(name = "tableBean")
#SessionScoped
public class TableBean implements Serializable {
private final static String[] colors;
private final static String[] manufacturers;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
private List<Car> cars;
private Car selectedCar;
private Car[] selectedCars;
public TableBean() {
cars = new ArrayList<Car>();
populateRandomCars(cars, 50);
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
private void populateRandomCars(List<Car> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
public List<Car> getCars() {
return cars;
}
}
Car.java
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "car")
#SessionScoped
public class Car implements Serializable {
private String model;
private int year;
private String manufacturer;
private String color;
private int price;
public Car(){
}
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public Car(String model, int year, String manufacturer, String color, int price) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Car))
return false;
Car compare = (Car) obj;
return compare.model.equals(this.model);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + model.hashCode();
}
#Override
public String toString() {
return "Car{" + "model=" + model + ", year=" + year + ", manufacturer=" + manufacturer + ", color=" + color + ", price=" + price + '}';
}
}
Edited: to solve this problem just add #ViewScoped on TableBean.java.
Your TableBean should be ViewScoped.
Add #ViewScoped on top of TableBean or configure it using faces-config.xml file.
You are using the example from the Showcase Labs, which is running on PrimeFaces version 3.4 (still in development at time of posting).
Since you are using PrimeFaces 3.3, you should be using the examples from the common Showcase.
Remember that the Labs version of the Showcase is always running on the still-on-development versions, while the common Showcase is always on the lastest final release.
You can always see what version is running behind the Showcase by checking the bottom of the page.
Since class Car is just a common class, not a manage bean, You don't need the declaration:
#ManagedBean(name = "car")
#SessionScoped
I am working on a project where Administrator selects a movie from a list. Then the data of the movie are displayed in inputTexts, so the admin can change it and onblur with ajax updates the database.
I created a bean in order to select the right data and display them in the inputTexts.
Thats ok. Now, I dont know how to allow the inputText to refer to the second bean where i have the update queries..
UPDATED
The Select Bean.
package Beans;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Select {
Connection con;
Statement statement;
String query;
private List perInfoAll = new ArrayList();
public List getperInfoAll() {
int i = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "Bill", "1989");
statement = con.createStatement();
query = "SELECT NAME,SURNAME FROM AJAX";
ResultSet resultset = statement.executeQuery(query);
while (resultset.next()) {
perInfoAll.add(i, new Select.perInfo(resultset.getString(1), resultset.getString(2)));
i++;
}
} catch (Exception e) {
System.out.println("Error Data : " + e.getMessage());
}
return perInfoAll;
}
public class perInfo {
String NAME;
String SURNAME;
public perInfo(String NAME, String SURNAME) {
this.NAME = NAME;
this.SURNAME = SURNAME;
}
public String getNAME() {
return NAME;
}
public String getSURNAME() {
return SURNAME;
}
}
}
The Update Bean
package Beans;
import java.sql.*;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Update {
Statement statement;
Connection con;
String query1;
String query2;
ResultSet resultset1;
ResultSet resultset2;
String NewName;
String NewSurname;
public void setNewSurname(String NewSurname) {
this.NewSurname = NewSurname;
}
public void setNewName(String NewName) {
this.NewName = NewName;
}
public String getNewSurname() {
return NewSurname;
}
public String getNewName() {
return NewName;
}
public void DatabaseConnection(String NewName) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query1 = "UPDATE AJAX SET NAME = ('" + NewName + "')";
resultset1 = statement.executeQuery(query1);
resultset1.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit() {
DatabaseConnection(NewName);
return "ok";
}
public void DatabaseConnection1(String NewSurname) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query2 = "UPDATE AJAX SET SURNAME = ('" + NewSurname + "')";
resultset2 = statement.executeQuery(query2);
resultset2.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit1() {
DatabaseConnection1(NewSurname);
return "ok";
}
}
The index.xhtml
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" type="text/css" href="my.css" />
</h:head>
<h:body>
<h:form>
<h:inputText value="#{update.newName}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit}" />
</h:inputText>
<h:inputText value="#{update.newSurname}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit1}" />
</h:inputText>
</h:form>
</h:body>
So i want in index.xhtml to get the values from the select bean and when updated the value will sent to update bean
You should do something like this...
assign the inputText to a variable name in the bean class as -
private String myData;
//getters and setters.
public void updateData(ActionEvent e)
{
//put your query here to update to the database.
}
and in your web file do like this -
<h:inputText value="#{bean.myData}">
<a4j:support event="onblur" actionListener="#{bean.updateData}"/>
</h:inputText>
Show your list as you were showing, and after onblur it will directly update this value to the database by calling a function described above.
Hope it clears your doubt.