Removing Item from JPA OneToManyList before Persisting - java

This is about a JSF + JPA application.
Bill and BillItem are two entities with Bilateral OneToMany relationship with cascadeType=all in a JPA application.
When the use clicks a new Bill, a new Bill object is create. User then fill properties of a BillItem like name and quantity and click the Add to Bill button, so that BillItem is added to the list of BillItems in the Bill Object. User interface is updated with Datatable linked to the bill.billItems.
After adding one or more billItems to the Bill, the user click the settle button where the bill object is persisted.
The issue is that it is not possible to remove billItem from the list. Always the first item is removed. How can I get the required billItem from the list ?
Code of Bill Entity
#Entity
public class Bill implements Serializable {
#OneToMany(mappedBy = "bill", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
List<BillItem> billItems = new ArrayList<>();
...
..
}
Code for BillItem Entity
#Entity
public class BillItem implements Serializable {
#ManyToOne
Bill bill;
....
...
#Override
public boolean equals(Object object) {
if (!(object instanceof BillItem)) {
return false;
}
BillItem other = (BillItem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
}
Code for JSF Managed Bean
#Named
#SessionScoped
public class SaleController implements Serializable {
private BilledBill bill;
BillItem billItem;
public void removeItem(){
if(removingItem==null){
UtilityController.addErrorMessage("Select one to remove");
return;
}
getBill().getBillItems().remove(removingItem);
}
public String newSaleBill() {
fillAvailableStocks();
listBillsToSettle();
clearBill();
clearBillItem();
printPreview = false;
bill = null;
return "sale";
}
public void settle() {
....
saveBill();
UtilityController.addSuccessMessage("Successfully Billed");
}
public void addItem() {
......
getBill().getBillItems().add(billItem);
calTotal();
clearBillItem();
}
public void saveBill() {
bill.setBillType(BillType.SaleToCustomer);
getBill().setInstitution(getSessionController().getInstitution());
getBill().setDepartment(getSessionController().getDepartment());
getBill().setStaff(getSessionController().getLoggedUser().getStaff());
getBill().setDeptId(getBillNumberBean().departmentBillNumberGenerator(getSessionController().getDepartment(), BillType.SaleToCustomer, BillNumberSuffix.SB));
getBill().setInsId(getBillNumberBean().institutionBillNumberGenerator(getSessionController().getInstitution(), BillType.SaleToCustomer, BillNumberSuffix.SB));
getBill().setRepId(getBillNumberBean().institutionBillNumberGenerator(getSessionController().getLoggedUser().getStaff(), BillType.SaleToCustomer, BillNumberSuffix.SB));
getBill().setToInstitution(getSessionController().getInstitution());
getBill().setToDepartment(getSessionController().getDepartment());
getBill().setCreatedAt(new Date());
getBill().setBillDate(Calendar.getInstance().getTime());
getBill().setCreater(getSessionController().getLoggedUser());
getBillFacade().create(getBill());
}
public BilledBill getBill() {
if (bill == null) {
bill = new BilledBill();
getBillFacade().create(bill);
}
return bill;
}
public BillItem getBillItem() {
if (billItem == null) {
billItem = new BillItem();
}
return billItem;
}
public void setBillItem(BillItem BillItem) {
this.billItem = BillItem;
}
public BillItem getRemovingItem() {
return removingItem;
}
public void setRemovingItem(BillItem removingItem) {
this.removingItem = removingItem;
}
}
JSF Page
<h:panelGrid columns="5">
<h:outputLabel value="Select Item"/>
<h:outputLabel value="Qty (kg)"/>
<h:outputLabel value="Rate"/>
<h:outputLabel value="Value"/>
<h:outputLabel value=""/>
<p:selectOneMenu id="acItem" converter="stockCon" value="#{saleController.billItem.stock}" var="vt" >
<f:selectItems value="#{saleController.availableStock}" var="ast" itemValue="#{ast}" itemLabel="#{ast.itemBatch.item.name}" ></f:selectItems>
<p:column >
<h:outputLabel value="#{vt.itemBatch.item.name}" ></h:outputLabel>
</p:column>
<p:column >
<h:outputLabel value="#{vt.stock}" ></h:outputLabel>
</p:column>
</p:selectOneMenu>
<p:inputText id="txtQty" value="#{saleController.billItem.qty}" styleClass="normalNoBox" >
<f:ajax event="blur" execute="acItem txtQty " render="" listener="#{saleController.calValueFromRate()}"></f:ajax>
</p:inputText>
<p:inputText id="txtRate" value="#{saleController.billItem.netRate}" styleClass="normalNoBox" >
<f:ajax event="blur" execute="acItem txtQty txtRate" render="lblVal" listener="#{saleController.calValueFromRate()}" ></f:ajax>
</p:inputText>
<h:outputLabel id="lblVal" value="#{saleController.billItem.netValue}" styleClass="normalNoBox" ></h:outputLabel>
<p:commandButton value="Add Item" action="#{saleController.addItem}" ajax="false" />
</h:panelGrid>
<p:panelGrid columns="2">
</p:panelGrid>
</h:panelGrid>
<p:dataTable var="ph" value="#{saleController.bill.billItems}" id="itemList">
<f:facet name="header">
<h:outputLabel value="Sale Items" ></h:outputLabel>
</f:facet>
<p:column headerText="Item Name" style="width:30%">
<h:outputLabel id="item" value="#{ph.item.name}" >
</h:outputLabel>
</p:column>
<p:column headerText="Qty (kg)" style="width:20%">
<h:outputLabel id="qty" value="#{ph.qty}" >
</h:outputLabel>
</p:column>
<p:column headerText="Rate" style="width:20%">
<h:outputLabel id="itemRate" value="#{ph.grossRate}" >
</h:outputLabel>
</p:column>
<p:column headerText="Value" style="width:20%">
<h:outputLabel id="itemVal" value="#{ph.grossValue}" >
</h:outputLabel>
</p:column>
<p:column headerText="Remove" style="width:20%">
<h:commandButton value="Remove" action="#{saleController.removeItem()}" >
<f:setPropertyActionListener target="#{saleController.removingItem}" value="#{ph}" ></f:setPropertyActionListener>
</h:commandButton>
</p:column>
</p:dataTable>
</p:panel>

Related

Primefaces SelectCheckboxMenu null value

I'm trying to get selected values from a selectCheckboxMenu, but all I'm getting is null in the console. It doesn't work with selectOneMenu too. Here's my jsf form:
<h:form id="mmaster">
<p:dataTable
value="#{devicesBean.devices}"
var="dev"
widgetVar="dt"
border="1"
paginator="true"
paginatorPosition="top"
rows="10"
>
<f:facet name="header">Devices</f:facet>
<p:column headerText="UDN" sortBy="#{dev.deviceUDN}" filterBy="#{dev.deviceUDN}" filterMatchMode="contains" emptyMessage="No Devices Found">
<h:outputText value="#{dev.deviceUDN}" />
</p:column>
<p:column headerText="FriendlyName" sortBy="#{dev.deviceFriendlyName}" filterBy="#{dev.deviceFriendlyName}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceFriendlyName}" />
</p:column>
<p:column headerText="Model" sortBy="#{dev.deviceModel}" filterBy="#{dev.deviceModel}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceModel}" />
</p:column>
<p:column headerText="Manufacturer" sortBy="#{dev.deviceManufacturer}" filterBy="#{dev.deviceManufacturer}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceManufacturer}" />
</p:column>
<p:column headerText="Type" sortBy="#{dev.deviceType}" filterBy="#{dev.deviceType}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceType}" />
</p:column>
<p:column headerText="Actions">
<p:selectCheckboxMenu value="#{devicesBean.selectAnnotations}">
<f:selectItems value="#{devicesBean.annotations}" />
</p:selectCheckboxMenu>
</p:column>
<p:column>
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#this">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
I wonder if there is a problem in the bean's scope, And this is my managed bean:
#ManagedBean
public class DevicesBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<Device> devices;
private List<String> annotations;
private List<String> selectAnnotations = new ArrayList<String>();
private Device device;
#EJB
IOntoProcessor iop;
#EJB
IDevicesDao idd;
public DevicesBean() {
}
#PostConstruct
public void init() {
setDevices(idd.getAllDevices());
setAnnotations(iop.getAllAnnotations());
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
public List<String> getAnnotations() {
return annotations;
}
public void setAnnotations(List<String> annotations) {
this.annotations = annotations;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public List<String> getSelectAnnotations() {
return selectAnnotations;
}
public void setSelectAnnotations(List<String> selectAnnotations) {
this.selectAnnotations = selectAnnotations;
}
public void doSave() {
System.out.println(selectAnnotations);
System.out.println(device);
selectAnnotations = new ArrayList<String>();
}
}
You are trying to submit the form through the Button with value Annotate, which has been specified to process itself only:
This will only process the button and its associated form parameters, and no other element within the form.
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#this">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
Either remove the process="#this", or replace it with process="#form"
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#form">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
Two, declare your managed bean scope: Either #RequestScope or #SessionScoped will work fine.

primefaces row deleting from database

I'm trying to delete row in primefaces datatable from database. It's working fine in datatable, but after refreshing project the row value show up.I'm using http://www.mkyong.com/jsf2/how-to-delete-row-in-jsf-datatable/ example. Can anybody help?
index.xhtml
<p:growl id="messages" showDetail="true"/>
<p:dataTable var="u" value="#{logonTest.userList}" id="carList" editable="true">
<f:facet name="header">
In-Cell Editing
</f:facet>
<p:ajax event="rowEdit" listener="#{tableBean.onEdit}" update=":form:messages" />
<p:ajax event="rowEditCancel" listener="#{tableBean.onCancel}" update=":form:messages" />
<p:column headerText="Name" style="width:30%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.name}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Surname" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.surname}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.surname}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Username" style="width:24%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.username}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.username}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Description" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.description}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.description}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:6%">
<p:rowEditor />
<h:commandLink value="Delete" action="#{logonTest.deleteAction(u)}" />
</p:column>
</p:dataTable>
</h:form>
LogonTest.java
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
public String deleteAction(User user) {
userList.remove(user);
return null;
}
}
that because you remove it from the arraylist only not from the database
use em.remove(user)
Your delete action is only removing it from the scoped variable.
public String deleteAction(User user) {
userList.remove(user);
return null;
}
You need to also remove it from the database, via the entity manager. em.remove(object)
Try the following code with EntityManager using remove method.
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
public String deleteAction(User user) {
EntityManager em = emf.createEntityManager();
em.remove(user);
userList.remove(user);
return null;
}
}

SelectItemsConverter Omnifaces preselected object value?

I have a problem, well when I save my object to the DB it works fine, but when i want to retrieve it from the DB doesn't work, I'm using selectItemsConverter by Omnifaces
I have my Object "Modelo" which has two other objects inside, which are "Marca" and "Gama"
These are my Java entities (the toString() is for Omnifaces):
Modelo:
private Marca marca;
private Gama gama;
getters and setters...
#Override
public String toString() {
return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
}
Marca:
getters and setters...
#Override
public String toString() {
return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
}
Gama:
getters and setters...
#Override
public String toString() {
return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
}
Well and this is my managedBean
ModeloBean
#ManagedBean
#ViewScoped
public class ModeloBean {
private Modelo modelo = new Modelo();
getters and setters ...
//This is for call the DB to retrieve the value, and works fine, but i cant show the preselected value to the xhtml
public void leer(Modelo mo) throws Exception {
ModeloDAO dao = new ModeloDAO();
try {
this.init();
this.modelo = dao.leer(mo);
} catch (Exception e) {
throw e;
} finally {
dao = null;
}
}
This is my xhtml Page
I have a dialog which I used it for save and update an object
<p:dialog id="dlgDatos" widgetVar="wdlgDatos" modal="true" appendToBody="true" header="#{modeloBean.accion}" draggable="false" resizable="false">
<h:form>
<h:panelGrid columns="2">
<p:outputLabel value="Marca" />
<p:selectOneMenu value="#{modeloBean.modelo.marca}" converter="omnifaces.SelectItemsConverter" filter="true" filterMatchMode="startsWith" required="true">
<f:selectItem itemLabel="Seleccione" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{marcaBean.lstMarcasVigentes}" var="marca" itemLabel="#{marca.nombre}" itemValue="#{marca}" />
</p:selectOneMenu>
<p:outputLabel value="Gama" />
<p:selectOneMenu value="#{modeloBean.modelo.gama}" converter="omnifaces.SelectItemsConverter" filter="true" filterMatchMode="startsWith" required="true">
<f:selectItem itemLabel="Seleccione" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{gamaBean.lstGamasVigentes}" var="gama" itemLabel="#{gama.nombre}" itemValue="#{gama}" />
</p:selectOneMenu>
<p:outputLabel for="txtNombre" value="Modelo" />
<p:column>
<p:inputTextarea id="txtNombre" value="#{modeloBean.modelo.nombre}" />
<p:watermark for="txtNombre" value="Para registrar varios modelos, sepárelos por comas (,)" />
</p:column>
<p:outputLabel value="Vigencia" rendered="#{modeloBean.accion eq 'Modificar'}"/>
<p:selectBooleanCheckbox value="#{modeloBean.modelo.vigencia}" rendered="#{modeloBean.accion eq 'Modificar'}"/>
<p:commandButton value="#{modeloBean.accion}" actionListener="#{modeloBean.operar()}" oncomplete="PF('wdlgDatos').hide(); PF('wdtLista').clearFilters();" update=":frmLista:dtLista, :msj"/>
<p:commandButton value="Cancelar" immediate="true" onclick="PF('wdlgDatos').hide();"/>
</h:panelGrid>
</h:form>
</p:dialog>
The selectOneMenu works fine for save, but for update only retrieve me the Strings value and not the preselected value of my comboBoxes
This is the dialog which only retrieve the String value of "105" cause is a String and my boolean value for the checkbox "Vigencia" but not my comboBoxes values. Where am I wrong?
I solved it adding this to my entites (hashCode and equals)
#Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + this.codigo;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Modelo other = (Modelo) obj;
if (this.codigo != other.codigo) {
return false;
}
return true;
}

Row selection with multiple p:dataTable

In the following scenario, where I have several dataTables that I build iterating over a ui:repeat tag, I have experienced that row listener returns null for selected elements that are not in the first table.
In order to understand the model object, I have several menus, and each of them contains several areas.
Any help will be much appreciated.
xhtml below:
<ui:repeat value="#{someBean.menus}" var="menu">
<p:dataTable var="area" value="#{menu.areas}"
rowKey="#{area.id}" selection="#{menu.area}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{someBean.rowSelected}" />
<f:facet name="header">#{menu.name}</f:facet>
<p:column>
<f:facet name="header"></f:facet>
<h:outputText value="#{area.id}" />
</p:column>
<p:column>
<f:facet name="header">Area name</f:facet>
<h:outputText value="#{area.name}" />
</p:column>
</p:dataTable>
</ui:repeat>
ListDataModel java implementation:
public class Areas extends ListDataModel<Area> implements SelectableDataModel<Area>, Serializable {
private static final long serialVersionUID = -9102592194300556930L;
public Areas() {
}
public Areas(List<Area> data) {
super(data);
}
#Override
public Area getRowData(String rowKey) {
#SuppressWarnings("unchecked")
List<Area> areas = (List<Area>)getWrappedData();
for (Area area : areas) {
if (String.valueOf(area.getId()).equals(rowKey)) {
return area;
}
}
return null;
}
#Override
public Object getRowKey(Area area) {
return area.getId();
}
}
public class Menus extends ListDataModel<Menu> implements SelectableDataModel<Menu>, Serializable {
private static final long serialVersionUID = -4079772686830676202L;
public Menus() {
}
public Menus(List<Menu> data) {
super(data);
}
#Override
public Menu getRowData(String rowKey) {
#SuppressWarnings("unchecked")
List<Menu> menus = (List<Menu>)getWrappedData();
for (Menu menu : menus) {
if (String.valueOf(menu.getId()).equals(rowKey)) {
return menu;
}
}
return null;
}
#Override
public Object getRowKey(Menu menu) {
return menu.getId();
}
}
...in the bean someBean
public void rowSelected(SelectEvent event) {
Area selectedArea = (Area)event.getObject(); //This, is null for other tables except the first
System.out.println("SELECTED AREA:" + selectedArea);
//...
}
I am glad to show you the solution: replace ui:repeat with another p:dataTable !!!
<p:dataTable value="#{someBean.menus}" var="menu">
<p:column>
<p:dataTable var="area" value="#{menu.areas}"
rowKey="#{area.id}" selection="#{menu.area}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{someBean.rowSelected}" />
<f:facet name="header">#{menu.name}</f:facet>
<p:column>
<f:facet name="header"></f:facet>
<h:outputText value="#{area.id}" />
</p:column>
<p:column>
<f:facet name="header">Area name</f:facet>
<h:outputText value="#{area.name}" />
</p:column>
</p:dataTable>
</column>
</p:dataTable>

Submit Listener Method in the BackBean is not getting invoked

My result tables/images will be displayed in the same page. But the submit button is not invoked. I have two drop downs on which the values of the other two drop downs are dependent. If I am writting immediate="true" the method is invoked but only two values are set with whom I have associated processValueChange action the other selected values are not updated in the bean.
The jsp page is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://www.ibm.com/jsf/html_extended" prefix="hx"%>
<%#taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%#taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%#taglib
uri="http://www.ibm.com/jsf/BrowserFramework" prefix="odc"%>
<html>
<head>
<script language="javascript" src="Validation.js"></script>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<title>SLA DASHBOARD</title>
</head>
<f:view>
<body>
<hx:scriptCollector id="scriptCollector1">
<div id="mDiv" class="pStyle">
<h:form styleClass="form" id="LoginForm" ><br>
<br>
<div id="Header" class="hStyle">
<h:outputText value= "WELCOME TO SLA DASHBOARD" />
</div>
<br><br>
<div id="fDiv" >
<fieldset class="fStyle">
<legend style="text-align: left;padding: 6px; font-weight:bold; font-size: 14">PLEASE MAKE YOUR SELECTION</legend><br>
<h:outputText value="BU"/>
<h:selectOneMenu id="slaBU" value="#{LoginForm.slaPeriod}"
onchange="this.form.submit();" valueChangeListener="#{LoginForm.processBUChange}">
<f:selectItems value="#{LoginForm.buList}" />
</h:selectOneMenu>
<h:outputText>Application</h:outputText>
<h:selectOneMenu id="slaApplication" style="width:160px" value="#{LoginForm.slaApp}" required="true">
<f:selectItems value="#{LoginForm.appList}" />
</h:selectOneMenu>
<h:outputText>Period</h:outputText>
<h:selectOneMenu id="slaPeriod" value="#{LoginForm.slaPeriod}" onchange="this.form.submit()"
valueChangeListener="#{LoginForm.processPeriodChange}" >
<f:selectItems value="#{LoginForm.periodList}" />
</h:selectOneMenu>
<h:selectOneMenu id="slaPeriod1" style="width:100px"
value="#{LoginForm.slaPeriod1}" required="true">
<f:selectItems value="#{LoginForm.periodList1}" />
</h:selectOneMenu>
<h:selectOneMenu id="slaPeriod2" value="#{LoginForm.slaPeriod2}" required="true">
<f:selectItems value="#{LoginForm.periodList2}" />
</h:selectOneMenu>
<h:outputText value="SLA Group" />
<h:selectOneMenu id="slaGroup" value="#{LoginForm.slaGroup}" required="true">
<f:selectItems value="#{LoginForm.groupList}" />
</h:selectOneMenu>
<h:outputText>View</h:outputText>
<h:selectOneMenu id="slaView" value="#{LoginForm.slaView}" required="true">
<f:selectItems value="#{LoginForm.viewList}" />
</h:selectOneMenu>
<h:commandButton id="submitButton" value="Submit"
type="submit"
style="width:60px;" action="#{LoginForm.processSubmit}"
/>
<br>
<br>
</fieldset>
</div><br><br><br>
<div id="tDiv" >
<h:dataTable id="bTable" value="#{LoginForm.BT}" var="BillingTable"
style="font-weight: bold; text-align: center;" bgcolor="#D4D7FE"
border="4" cellpadding="1" width="60%"
rendered="#{LoginForm.btDisplay}">
<f:facet name="header">
<h:outputText value="Billing Report" style="font-weight: bold"/>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Buisness Unit" />
</f:facet>
<h:outputText value="#{BillingTable.buName}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Completion Date" />
</f:facet>
<h:outputText value="#{BillingTable.completionDate}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Target Date" />
</f:facet>
<h:outputText value="#{BillingTable.targetDate}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Billing Cycle" />
</f:facet>
<h:outputText value="#{BillingTable.billingCyle}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Status" />
</f:facet>
<h:outputText value="#{BillingTable.status}"></h:outputText>
</h:column>
</h:dataTable>
<br>
<h:dataTable id="uTable" value="#{LoginForm.UT}" var="UptimeTable"
style="text-align: center" bgcolor="#D4D7FE"
border="4" cellpadding="1" width="60%" rendered="#{LoginForm.utDisplay}">
<f:facet name="header">
<h:outputText value="Uptime Report" style="font-style: normal; font-weight: bold"/>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Application Name" style="width:60px" />
</f:facet>
<h:outputText value="#{UptimeTable.applicationName}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Application Class" />
</f:facet>
<h:outputText value="#{UptimeTable.applicationClass}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Availability-Actual" />
</f:facet>
<h:outputText value="#{UptimeTable.actual}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Availability-Target" />
</f:facet>
<h:outputText value="#{UptimeTable.target}"></h:outputText>
</h:column>
</h:dataTable>
<br>
<h:dataTable id="tTable" value="#{LoginForm.TT}" var="TATTable"
style="font-weight: bold; text-align: center" bgcolor="#D4D7FE"
border="4" cellpadding="1" width="60%"
rendered="#{LoginForm.ttDisplay}">
<f:facet name="header">
<h:outputText value="Turn Around Time Report" />
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Application Name" />
</f:facet>
<h:outputText value="#{TATTable.applicationName}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Application Class" />
</f:facet>
<h:outputText value="#{TATTable.applicationClass}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="TAT Average" />
</f:facet>
<h:outputText value="#{TATTable.tatAverage}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="TAT Target" />
</f:facet>
<h:outputText value="#{TATTable.tatTarget}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Request Count" />
</f:facet>
<h:outputText value="#{TATTable.reqCount}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Request Type" />
</f:facet>
<h:outputText value="#{TATTable.reqType}"></h:outputText>
</h:column>
</h:dataTable>
</div>
<br>
<h:graphicImage styleClass="graphicImage" id="reportImage" alt="Sorry records not found !!"
value="#{LoginForm.imageLocation}" width="700" height="250" rendered="#{LoginForm.viewImage}">
</h:graphicImage><br>
<h3><h:outputText value="Sorry records not found !!" rendered="#{LoginForm.notFoundMsg}"/></h3>
</h:form>
</div>
</hx:scriptCollector></body>
</f:view>
</html>
My backing bean Login Form is as follows:
package sla.dashboard.form;
import sla.dashboard.Search.SearchManager;
import sla.dashboard.drop_down_components.*;
import sla.dashboard.datatables.*;
import java.util.*;
import javax.faces.context.FacesContext;
import javax.faces.event.*;
import javax.faces.model.*;
public class LoginForm implements ValueChangeListener,ActionListener
{
private String slaBU=null,slaPeriod1=null,slaPeriod2=null,slaGroup=null,
periodType=null,periodSelected=null,slaView=null,period=null,
imageResult=null,imageLocation=null;
private int slaPeriod,slaApp;
Boolean btDisplay,utDisplay,ttDisplay,viewImage,notFoundMsg;
//Table Lists
List <BillingTable> BT;
List <UptimeTable> UT;
List <TATTable> TT;
DropDownComponents ddC;
List<SelectItem> buList;
List<SelectItem> periodList;
List<SelectItem> periodList1;
List<SelectItem> periodList2;
List<SelectItem> groupList;
List<SelectItem> appList;
List<SelectItem> viewList;
ArrayList<String> result= new ArrayList<String>();
public LoginForm()
{
ddC=new DropDownComponents();
buList=ddC.getBuList();
this.reset();
BT=new ArrayList<BillingTable>();
UT=new ArrayList<UptimeTable>();
TT=new ArrayList<TATTable>();
System.out.println("\n Back Bean Object Instantiated");
}
public int getSlaApp() {
return slaApp;
}
public Boolean getBtDisplay() {
return btDisplay;
}
public void setBtDisplay(Boolean btDisplay) {
this.btDisplay = btDisplay;
}
public Boolean getUtDisplay() {
return utDisplay;
}
public void setUtDisplay(Boolean utDisplay) {
this.utDisplay = utDisplay;
}
public Boolean getTtDisplay() {
return ttDisplay;
}
public void setTtDisplay(Boolean ttDisplay) {
this.ttDisplay = ttDisplay;
}
public void setSlaApp(int slaApp) {
this.slaApp = slaApp;
}
public int getSlaPeriod() {
return slaPeriod;
}
public void setSlaPeriod(int slaPeriod) {
this.slaPeriod = slaPeriod;
}
public String getPeriod() {
return period;
}
public void setPeriod(String period)
{
this.period = period;
}
public List<SelectItem> getViewList() {
return viewList;
}
public void setViewList(List<SelectItem> viewList) {
this.viewList = viewList;
}
public List<SelectItem> getPeriodList() {
return periodList;
}
public void setPeriodList(List<SelectItem> periodList) {
this.periodList = periodList;
}
public List<SelectItem> getBuList()
{
return buList;
}
public String getPeriodType() {
System.out.println("Inside getPeriodType " + periodType);
return periodType;
}
public void setPeriodType(String periodType) {
System.out.println("Inside setPeriodType "+ periodType);
this.periodType = periodType;
}
public void setBuList(List<SelectItem> buList) {
this.buList = buList;
}
public String getSlaBU() {
return slaBU;
}
public void setSlaBU(String slaBU)
{
this.slaBU = slaBU;
}
public String getSlaPeriod1()
{
return slaPeriod1;
}
public void setSlaPeriod1(String slaPeriod1) {
this.slaPeriod1 = slaPeriod1;
}
public String getSlaPeriod2() {
return slaPeriod2;
}
public void setSlaPeriod2(String slaPeriod2) {
this.slaPeriod2 = slaPeriod2;
}
public String getPeriodSelected() {
return periodSelected;
}
public void setPeriodSelected(String periodSelected) {
this.periodSelected = periodSelected;
}
public List<SelectItem> getPeriodList1() {
return periodList1;
}
public void setPeriodList1(List<SelectItem> periodList1) {
this.periodList1 = periodList1;
}
public List<SelectItem> getPeriodList2() {
return periodList2;
}
public void setPeriodList2(List<SelectItem> periodList2) {
this.periodList2 = periodList2;
}
public String getSlaGroup() {
return slaGroup;
}
public void setSlaGroup(String slaGroup) {
this.slaGroup = slaGroup;
}
public List<SelectItem> getGroupList() {
return groupList;
}
public void setGroupList(List<SelectItem> groupList) {
this.groupList = groupList;
}
public List<SelectItem> getAppList() {
return appList;
}
public void setAppList(List<SelectItem> appList) {
this.appList = appList;
}
public String getSlaView() {
return slaView;
}
public void setSlaView(String slaView) {
this.slaView = slaView;
}
//ValueChangeListener
public void processValueChange(ValueChangeEvent arg0) throws AbortProcessingException
{}
public void processPeriodChange(ValueChangeEvent arg0) throws AbortProcessingException
{
this.setSlaPeriod(Integer.parseInt(arg0.getNewValue().toString()));
this.setPeriodList1(ddC.getPeriodList1(Integer.parseInt(arg0.getNewValue().toString())));
System.out.println("Period Changed Value : "+this.getSlaPeriod());
FacesContext.getCurrentInstance().renderResponse();
}
public void processBUChange(ValueChangeEvent arg0) throws AbortProcessingException
{
this.setSlaBU(arg0.getNewValue().toString());
this.setAppList(ddC.getAppList(Integer.parseInt(arg0.getNewValue().toString())));
System.out.println("\n BU Slected : " + this.getSlaBU());
FacesContext.getCurrentInstance().renderResponse();
}
public void processAction(ActionEvent arg0) throws AbortProcessingException
{}
public List<BillingTable> getBT() {
return BT;
}
public void setBT(List<BillingTable> bt) {
BT = bt;
}
public List<UptimeTable> getUT() {
return UT;
}
public void setUT(List<UptimeTable> ut) {
UT = ut;
}
public List<TATTable> getTT() {
return TT;
}
public void setTT(List<TATTable> tt) {
TT = tt;
}
public void setImageLocation(String imageLocation) {
this.imageLocation = imageLocation;
}
public String getImageLocation() {
return imageLocation;
}
String getLabel(String index,List<SelectItem> lst)
{
return(lst.get(Integer.parseInt(index)).getLabel());
}
public Boolean getViewImage() {
return viewImage;
}
public void setViewImage(Boolean viewImage) {
this.viewImage = viewImage;
}
public void setImageResult(String imageResult) {
this.imageResult = imageResult;
}
public String getImageResult() {
return imageResult;
}
public Boolean getNotFoundMsg() {
return notFoundMsg;
}
public void setNotFoundMsg(Boolean notFoundMsg) {
this.notFoundMsg = notFoundMsg;
}
public void reset()
{
slaPeriod=0;
slaApp=0;
slaBU="0";
slaPeriod1="0";
slaPeriod2="0";
slaGroup="0";
slaView="0";
periodList=ddC.getPeriodList();
periodList1=ddC.getPeriodList1(slaPeriod);
periodList2=ddC.getPeriodList2();
groupList=ddC.getSlaGroupList();
appList=ddC.getAppList(slaApp);
viewList=ddC.getViewList();
this.setViewImage(false);
this.setUtDisplay(false);
this.setTtDisplay(false);
this.setBtDisplay(false);
this.setNotFoundMsg(false);
}
public String processSubmit()
{
System.out.println("Inside Process Submit ");
System.out.println(this.getSlaBU()+this.getSlaApp()+this.getSlaPeriod()+this.getSlaPeriod1()+
this.getSlaPeriod2()+this.getSlaGroup()+this.getSlaView());
this.setViewImage(false);
this.setUtDisplay(false);
this.setTtDisplay(false);
this.setBtDisplay(false);
this.setNotFoundMsg(false);
/*slaPeriod=1;
slaApp=0;
slaBU="1";
slaPeriod1="1";
slaPeriod2="2";
slaGroup="2";
slaView="1";*/
if(this.slaGroup=="1" && slaView=="1")
{
BT=new SearchManager().searchBillingTable
(slaBU,periodList.get(slaPeriod).getLabel(),
this.getSlaPeriod1(),getLabel(slaPeriod2,
periodList2),getLabel(slaGroup,groupList));
if(BT.size()!=0)
this.setBtDisplay(true);
else
this.setNotFoundMsg(true);
}
else
{
if(this.slaGroup=="2" && slaView=="1")
{
UT=new SearchManager().searchUptimeTable
(slaBU,periodList.get(slaPeriod).getLabel(),
this.getSlaPeriod1(),getLabel(slaPeriod2,
periodList2),getLabel(slaGroup,groupList));
if(UT.size()!=0)
this.setUtDisplay(true);
else
this.setNotFoundMsg(true);
}
else
{
if(this.slaGroup=="3" && slaView=="1")
{
TT=new SearchManager().searchTATTable(slaBU,periodList.get(slaPeriod).getLabel(),
this.getSlaPeriod1(),getLabel(slaPeriod2,
periodList2),getLabel(slaGroup,groupList));
if(TT.size()!=0)
this.setTtDisplay(true);
else
this.setNotFoundMsg(true);
}
else
{
if(slaView=="2")
{
imageResult=new SearchManager().searchImage(slaBU,
periodList.get(slaPeriod).getLabel(), slaPeriod1,
slaPeriod2,getLabel(slaGroup,groupList),slaView);
this.setImageLocation(imageResult);
this.setViewImage(true);
}
else
{
this.setNotFoundMsg(true);
}
}
}
}
return("Success");
}
}
How to submit the form properly?
When a form is not being submitted, sometimes it may happen from a mistaken usage of JSF component.
I see that you are using
<h:selectOneMenu id="slaView" value="#{LoginForm.slaView}" required="true">
<f:selectItems value="#{LoginForm.viewList}" />
</h:selectOneMenu>
which comes from:
viewList=ddC.getViewList();
and the selected item goes into a String value.
can you please write the code of getViewList ?
If the items are declared of int,String - than the problem is that slaView should be of type int.
You're calling FacesContext.getCurrentInstance().renderResponse(); inside a valueChangeListener method whenever a dropdown value changes. This will cause the remaining phases of the JSF lifecycle being skipped until the render response phase. Since the valueChangeListener method is invoked during validations phase, the update model values and invoke action phases are skipped. And guess what, the submit button is to be invoked during invoke action phase, but this is been skipped!
Anyway, creating dynamic dependent dropdown menus wherein the data is fully to be retrieved from the server side without any help of advanced JavaScript and Ajax is a real pain. You've to take a lot of things into account with regard to skipping validation of other fields and retaining submitted values of other fields. So also in JSF. Long story short, here's an article which describes how to do it properly: Populate child menu's.

Categories

Resources