<h:commandButton> does not initiate a postback - jsf-2

I am using JSF 2.1.7 and Myfaces CODI 1.0.5 on JBoss AS 7.1.1. My <h:commandButton> is not working. I have read the requirements and have through examples in many blogs all to no avail. My facelets code is as follows
<ui:define name="pagecontent">
<h1 class="title ui-widget-header ui-corner-all">Upload Bulk Contact File</h1>
<div class="entry">
<h:form enctype="multipart/form-data" id="upload">
<p:panel closable="false" collapsed="false" header="Excel Contact Uploader"
id="pnlupload" rendered="true" toggleable="false" visible="true" widgetVar="pnlupload">
<p:growl id="msg" showDetail="true" life="3000" showSummary="true"/>
<p:fileUpload auto="true"
allowTypes="/(\.|\/)(xls)$/"
sizeLimit="1024000"
mode="advanced"
multiple="true" invalidFileMessage="Invalid file type" invalidSizeMessage="File too
large" dragDropSupport="true"
fileUploadListener="#{excelFileController.handleFileUpload}" showButtons="true"
update="msg, tblcontacts" required="false"/>
<p:scrollPanel rendered="true" style="height:200px;">
<p:dataTable draggableColumns="false" editable="false" emptyMessage="No
Contacts Uploaded" id="tblcontacts" rendered="true" rows="8"
selection="#{excelFileController.contactsSelected}"
value="#{excelFileController.contactDataModel}" var="contact" style="width:50pc;">
<p:column selectionMode="multiple" style="width:18px" />
<p:column headerText="File Name">
#{contact.groupName}
</p:column>
<p:column headerText="Number of Contacts">
#{contact.numberofentries}
</p:column>
<p:column>
<h:button outcome="blkedit?faces-redirect=true" rendered="true" value="Edit">
<f:param name="contact" value="#{contact.contactId}"/>
</h:button>
</p:column>
</p:dataTable>
</p:scrollPanel>
<br />
</p:panel>
<h:commandButton value="Delete" id="btndelete"
action="#{excelFileController.removeContact}" type="button" immediate="true"
disabled="false" rendered="true"/>
<h:message for="btndelete" />
</h:form>
</div>
</ui:define>
The code for ExcelFileController is as follows:
#Named
#ViewAccessScoped
public class ExcelFileController implements Serializable, IFileController {
/**
*
*/
private static final long serialVersionUID = -8117258104485487921L;
#Inject
PhoneNumberFormatter formatter;
#Inject
#Authenticated
UserProfile profile;
public PhoneNumberFormatter getFormatter() {
return formatter;
}
public void setFormatter(PhoneNumberFormatter formatter) {
this.formatter = formatter;
}
#EJB
BulkContactDeleter deleter;
#Inject
Logger logger;
#Inject
#CurrentContext
FacesContext context;
#Inject
BulkSMSContactListProducer listProducer;
#Inject
ConfigurationListProducer producer;
private BulkSMSContacts[] contactsSelected;
private BulkContactDataModel contactDataModel;
public BulkSMSContacts[] getContactsSelected() {
return contactsSelected;
}
public void setContactsSelected(BulkSMSContacts[] contactsSelected) {
this.contactsSelected = contactsSelected;
}
public BulkContactDataModel getContactDataModel() {
return contactDataModel;
}
#PostConstruct
public void init() {
logger.log(Level.INFO, "Entering excel file controller");
contactDataModel = new BulkContactDataModel(
listProducer.getBulkSMSContacts());
}
/*
* (non-Javadoc)
*
* #see
* org.jboss.tools.examples.controller.IFileController#handleFileUpload(
* org.primefaces.event.FileUploadEvent)
*/
#Override
public void handleFileUpload(FileUploadEvent event) {
StringBuffer buffer = new StringBuffer();
// create a new file input stream with the input file specified
// at the command line
InputStream fin = null;
try {
fin = event.getFile().getInputstream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = null;
try {
poifs = new POIFSFileSystem(fin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(poifs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int numberofsheets = wb.getNumberOfSheets();
for (int i = 0; i < numberofsheets; i++) {
HSSFSheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING :
if (!cell.getStringCellValue().isEmpty())
buffer.append(formatter.formatPhoneNumber(cell
.getStringCellValue()));
buffer.append(producer.getConfiguration(
SettingsName.SMS_PHONENUMBERDELIMITER
.toString()).getValue());
break;
case Cell.CELL_TYPE_NUMERIC :
if (cell.getNumericCellValue() != 0) {
buffer.append(formatter
.formatPhoneNumber(String.valueOf(cell
.getNumericCellValue())));
buffer.append(producer.getConfiguration(
SettingsName.SMS_PHONENUMBERDELIMITER
.toString()).getValue());
break;
}
default :
break;
}
}
}
}
BulkSMSContacts contacts = new BulkSMSContacts();
contacts.setAccount(profile.getSmsAccount());
int number = formatter.splitPhoneNumbers(buffer.toString()).length;
contacts.setContacts(buffer.toString());
String filenameString = event.getFile().getFileName();
int index = filenameString.indexOf(".");
filenameString = filenameString.substring(0, index);
contacts.setGroupName(filenameString);
contacts.setNumberofentries(number);
try {
deleter.addContact(contacts);
List<BulkSMSContacts> temp = listProducer.getBulkSMSContacts();
contactDataModel.setWrappedData(temp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Success", number
+ " entries processed. Please refresh page to view"));
}
/*
* (non-Javadoc)
*
* #see org.jboss.tools.examples.controller.IFileController#removeContact()
*/
#Override
public String removeContact() {
int contactsdeleted = 0;
if (contactsSelected != null) {
for (BulkSMSContacts contacts : contactsSelected) {
if (contacts != null) {
deleter.deleteContact(contacts);
contactsdeleted += 1;
}
}
List<BulkSMSContacts> temp = listProducer.getBulkSMSContacts();
contactDataModel.setWrappedData(temp);
logger.log(Level.INFO, "Deleted " + contactsdeleted + " Contacts");
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Success", contactsdeleted
+ " entries where deleted successfully"));
} else {
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error",
"No contact file was selected!"));
}
return null;
}
}
All the methods work fine except for the last one "removeContact" where the CommandButton concerned does not even initiate a postback.
How is this caused and how can I solve it?

You need to remove type="button" from the <h:commandButton>. It should have been type="submit", which is the default already.
The type="button" makes it an <input type="button"> instead of <input type="submit"> which is only useful for client side handlers which you usually attach using onclick and so on.

Related

Alternate single and multiple selection with p:dataTable

Need some help to know if my solution is valid or not.
I have a primefaces datatable with single row selection, and I need to add a multiple selection checkbox column... My idea is to switch selection mode clicking on one button, that switch the selection mode from single to multiple and vice versa....
<pf:dataTable
value="${bean.notifications}"
var="notif"
selection="#{bean.isMultiple() ? consulterCorbeilleBean.selectedNotifs : consulterCorbeilleBean.selectedNotif}"
selectionMode="#{not bean.isMultiple() ? 'single' : ''}"
rowKey="${notification.cle.idNotification}">
<pf:ajax event="rowSelect" disabled="${bean.isMultiple()}"
listener="${bean.function()}" update=":table:notificationTable"
oncomplete="stopPropagationClick()" />
<pf:column selectionMode="multiple" rendered="#{bean.isMultiple()}"/>
</pf:dataTable>
I have a problem with the selection binding. I have this error :
Illegal Syntax for Set Operation:
javax.el.PropertyNotWritableException: /index.xhtml #114,50
selection="#{bean.isMultiple() ? bean.selectedNotifs :
bean.selectedNotif}"
Any idea to workaround ? I use Primefaces 3.2.
Best Regards and thanks for your help :)
You can't use dynamic setter values on the selection.
I would rethink the design if i were you, but if you really need both single and multiple selection options on the same table, you could use 2 datatables and render only 1 of them at a time, and switch between them with a button click.
If you really need it, then you can try this work example
View
<h:form id="form">
<p:growl id="msgs" showDetail="true" for="basicDT" />
<p:inputSwitch value="#{dtSelectionView.multiple}">
<p:ajax listener="#{dtSelectionView.addMessage}" update="basicDT, msgs" />
</p:inputSwitch>
<p:dataTable
id="basicDT"
var="car"
value="#{dtSelectionView.cars1}"
rowStyleClass="#{dtSelectionView.checkSelection(car)? 'ui-state-highlight':''}"
>
<f:facet name="header">
DoubleSelect
</f:facet>
<p:column style="width:32px">
<p:commandButton update="basicDT,:form:msgs,:form:carDetail,:form:multiCarDetail" icon="ui-icon-check" actionListener="#{dtSelectionView.addSelection(car)}" />
</p:column>
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
<p:dialog header="Car Info" widgetVar="carDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" closeOnEscape="true">
<p:outputPanel id="carDetail" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty dtSelectionView.selectedCar}" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{dtSelectionView.selectedCar.id}" />
<h:outputText value="Year" />
<h:outputText value="#{dtSelectionView.selectedCar.year}" />
<h:outputText value="Color:" />
<h:outputText value="#{dtSelectionView.selectedCar.color}" style="color:#{dtSelectionView.selectedCar.color}"/>
<h:outputText value="Price" />
<h:outputText value="$#{dtSelectionView.selectedCar.price}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<p:dialog header="Selected Cars" widgetVar="multiCarDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" width="200">
<p:outputPanel id="multiCarDetail" style="text-align:center;">
<ui:repeat value="#{dtSelectionView.selectedCars}" var="car">
<h:outputText value="#{car.id} - #{car.brand}" style="display:block"/>
</ui:repeat>
</p:outputPanel>
</p:dialog>
</h:form>
Model
import java.io.Serializable;
public class Car implements Serializable{
private String Id;
private String Brand;
private int Year;
private String Color;
private int Price;
private boolean SoldState;
public Car(String id, String brand, int year, String color, int price,
boolean soldState) {
super();
Id = id;
Brand = brand;
Year = year;
Color = color;
Price = price;
SoldState = soldState;
}
#Override
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof Car)) return false;
Car other = (Car) o;
if(! this.Id.equals(other.Id)) return false;
if(! this.Brand.equals(other.Brand)) return false;
if(this.Year != other.Year) return false;
if(! this.Color.equals(other.Color)) return false;
if(this.Price != other.Price) return false;
if(this.SoldState != other.SoldState) return false;
return true;
}
#Override
public int hashCode(){
return (int) Id.hashCode() *
Brand.hashCode() *
Year *
Color.hashCode() *
Price *
(SoldState ? 31 : 32)
;
}
/** getters/setters */
}
Bean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean(name="dtSelectionView")
#ViewScoped
public class SelectionView implements Serializable {
private List<Car> cars1;
private Car selectedCar;
private List<Car> selectedCars;
private boolean multiple= false;
#ManagedProperty("#{carService}")
private CarService service;
#PostConstruct
public void init() {
cars1 = service.createCars(10);/** random generated List. See PF showcase, datatable examples*/
selectedCars = new ArrayList<Car>();
}
public boolean checkSelection(Car car){
if(isMultiple())
return selectedCars.contains(car) ? true : false;
else
return car.equals(selectedCar) ? true : false;
}
public void addSelection(Car car){
String summary = "Car was ";
if(isMultiple())
if(selectedCars.contains(car)){
selectedCars.remove(car);
summary += "removed from list.";
}
else{
selectedCars.add(car);
summary += "added to list.";
RequestContext.getCurrentInstance().execute("PF('multiCarDialog').show();");
}
else
if(car.equals(selectedCar)){
selectedCar = null;
summary += "unselected.";
}
else{
selectedCar = car;
summary += "selected.";
RequestContext.getCurrentInstance().execute("PF('carDialog').show();");
}
FacesContext.getCurrentInstance().addMessage("basicDT", new FacesMessage(summary));
}
public void setService(CarService service) {
this.service = service;
}
public Car getSelectedCar() {
return selectedCar;
}
public List<Car> getSelectedCars() {
return selectedCars;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void addMessage() {
selectedCar = null;
selectedCars = new ArrayList<Car>();
String summary = multiple ? "Checked" : "Unchecked";
FacesContext.getCurrentInstance().addMessage("basicDT", new FacesMessage(summary));
}
public List<Car> getCars1() {
return cars1;
}
public void setCars1(List<Car> cars1) {
this.cars1 = cars1;
}
public CarService getService() {
return service;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
Hope You'll in right direction.

Primefaces datatable dynamic selection not working

In my application I need to decide selection mode dynamically either 'single' or 'multiple' for datatable (I'm using primefaces 5.0) and depends on that selection assigned. Below are the el expressions i have binded.
XHTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:head>
<title>Primefaces Data Table</title>
<script type="text/javascript" src="Test.js"/>
</h:head>
<h:body>
<h:form id="form">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="T" var="car" widgetVar="T_wv" value="#{ECTestScreen.cars}" selectionMode="#{ECTestScreen.selectionMode}" selection="#{ECTestScreen.selectionMode ne 'multiple'? ECTestScreen.selectedCar :ECTestScreen.selectedCars}" rowKey="#{car.id}" paginator="true" rows="5" paginatorAlwaysVisible="true">
<f:facet name="header">
Row Selection on Click
</f:facet>
<p:column headerText="Car Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<p:inputTextarea id="ta" rows="10" cols="30" style="height: 22px; overflow:auto;" value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:inputText value="#{car.color}" onmouseup="onCellFocus1(event, $(this).parent(), [{name: 'screenletId', value: 'T'}, {name: 'rowIndex', value: '5'}, {name: 'colName', value: 'Color'}]);"/>
</p:column>
<p:ajax event="rowSelect" listener="#{ECTestScreen.onRowSelect}" update=":form:msgs" />
</p:dataTable>
<p:commandButton value="Update Table" actionListener="#{ECTestScreen.onButtonClick}"/>
</h:form>
</h:body>
</html>
Java code:
#ManagedBean(name = "ECTestScreen")
#ViewScoped
public class ECTestScreen implements Serializable {
private static final long serialVersionUID = -855625904411046273L;
private List<String> products = new ArrayList<>();
private List<Integer> rowList = new ArrayList<>();
private List<Car> cars = new ArrayList<>();
private Car selectedCar ;
private List<Car> selectedCars = new ArrayList<>();
private String selectionMode="multiple";
public List<Integer> getRowList() {
return rowList;
}
public void setRowList(List<Integer> rowList) {
this.rowList = rowList;
}
public List<String> getProducts() {
return products;
}
public void setProducts(List<String> products) {
this.products = products;
}
public List<Car> getCars() {
for(int j=1; j<10;j++){
this.cars.add(new Car(j, (2000+j), "Merc-"+j, "Black-"+j));
}
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public List<Car> getSelectedCars() {
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("form");
return selectedCars;
}
public void setSelectedCars(List<Car> selectedCars) {
this.selectedCars = selectedCars;
}
public String onButtonClick(){
for(int i=1; i<6; i++){
rowList.add(i);
}
for(int j=1; j<4;j++){
products.add("td="+j);
}
for(int j=1; j<10;j++){
cars.add(new Car(j, (2000+j), "Merc-"+j, "Black-"+j));
}
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("form");
return "";
}
public String getSelectionMode(){
return selectionMode;
}
public void setSelectionMode(String selectionMode){
selectionMode="multiple";
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Car Selected: ", ((Car) event.getObject()).getBrand());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected: ", ((Car) event.getObject()).getBrand());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
Now the problem is if i assign selectionMode to either single or multiple through el or hardcoding and for selection if i point to only one function(either #{ECTestScreen.selectedCar} or #{ECTestScreen.selectedCars)) it works fine. But using above code if i decide selection mode dynamically either single or multiple depends on that if i add selection through above el the data table selection is not working means when selecting the row the setter is not at all called. and of course pagination also not working. it always stays in first page.
actually in case of single selection expects a single object where as in multiple selection list/array of objects...how to club these two..
Please help..
Primefaces version 5.0
I don't really know why you would make that distinction, since a multiselection dataTable should also cover the single selection requirements.
But if you insist, then i would probably make 2 dataTables - one single and one multiple selection and make them "rendered" based on a boolean.
selectedCars must be an array, not a List. The showcase presents example with a List, but it's not working that way.

Not Able to Save/Update details from richfaces popup panel

I am working on richfaces4,
when i am trying to edit details from a popup panel,i am not able to save/update the edited details into my database.can anybody help me to solve this.
My XHTML Page is as follows:
<!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:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:t="http://myfaces.apache.org/tomahawk">
<h:head>
</h:head>
<h:body>
<h:form id="dboperatorform">
<t:saveState value="#{dBOperator.empList}"></t:saveState>
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<t:saveState value="#{dBOperator.employee}"></t:saveState>
<rich:panel style="width:1345px">
<f:facet name="header">
<h:outputText value="Search Panel" />
</f:facet>
<h:panelGrid id="searchPanel" columns="6">
<h:column>
<h:outputLabel value="First Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.first_Name}" />
</h:column>
<h:column>
<h:outputLabel value="Last Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.last_name}" />
</h:column>
<h:column>
<a4j:commandButton value="Search" action="#{dBOperator.search}"
render="richtable">
</a4j:commandButton>
</h:column>
<h:column>
</h:column>
</h:panelGrid>
</rich:panel>
<br />
<a4j:commandButton value="Add" action="#{dBOperator.editdetails}"
execute="#this" style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="false"></f:setPropertyActionListener>
</a4j:commandButton>
<p></p>
<rich:dataTable value="#{dBOperator.employees}" var="emp"
id="richtable" cellpadding="0" cellspacing="0" style="width:1349px"
reRender="richtable" iterationStatusVar="it"
noDataLabel="No Records Found!" rows="5">
<rich:column>
<f:facet name="header">#</f:facet>
<h:outputText value="#{it.index}" />
</rich:column>
<rich:column>
<f:facet name="header">
<a4j:commandLink value="First Name"
action="#{dBOperator.sortByFirstName}" render="richtable"></a4j:commandLink>
</f:facet>
<h:outputText value="#{emp.first_Name}" />
</rich:column>
<rich:column>
<f:facet name="header">Last Name</f:facet>
<h:outputText value="#{emp.last_name}" />
</rich:column>
<rich:column>
<f:facet name="header">Edit</f:facet>
<a4j:commandButton image="images/edit.png"
action="#{dBOperator.editdetails}" execute="#this"
style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}"
value="#{it.index}"></f:setPropertyActionListener>
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="true"></f:setPropertyActionListener>
</a4j:commandButton>
</rich:column>
<f:facet name="footer">
<rich:dataScroller for="richtable" align="right"
status="ajaxProcessIcon" renderIfSinglePage="false" fastStep="5"
fastControls="auto" />
</f:facet>
</rich:dataTable>
<rich:popupPanel id="popup1" minHeight="300"
minWidth="300">
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<f:facet name="header">
<h:outputText value="Simple popup panel" />
</f:facet>
<f:facet name="controls">
<h:outputLink
onclick="#{rich:component('popup1')}.hide(); return false;"
reRender="richtable">X</h:outputLink>
</f:facet>
<rich:toolbar itemSeparator="line" width="100%" id="qawq">
<rich:toolbarGroup location="left">
<h:outputText
value="#{dBOperator.edit?'Employee Edit':'Employee Add'}" />
</rich:toolbarGroup>
</rich:toolbar>
<h:panelGrid id="CancelGrid" columns="2" width="100%">
<rich:column width="30%" style="border:none;">
<h:outputText value="First Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.first_Name}"
style="width:100%" id="abbr" />
</rich:column>
<rich:column width="30%" style="border:none;">
<h:outputText value="Last Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.last_name}"
style="width:100%" id="abbr1" />
</rich:column>
</h:panelGrid>
<a4j:commandButton value="#{dBOperator.edit?'Edit':'Save'}"
action="#{dBOperator.savedetails}"
oncomplete="#{rich:component('popup1')}.hide();"
onclick="validateFields();"></a4j:commandButton>
</rich:popupPanel>
<script type="text/javascript">
function validateFields() {
alert('came inside validateFields');
var fn=document.getElementById('dboperatorform:abbr');
alert('fn '+fn.value);
var ln=document.getElementById('dboperatorform:abbr1');
alert('ln '+ln.value);
}
</script>
</h:form>
</h:body>
</html>
My Bean Class is as follows
package com.richfaces.db;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.management.MBeanServer;
import javax.swing.SortOrder;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.comparator.NameComparator;
import com.comparator.NameCompartor1;
import com.richfaces.Employee;
public class DBOperator {
String id;
String first_Name;
String last_name;
String fName;
String lName;
Employee employee;
int rowNum;
boolean edit;
Boolean search=Boolean.FALSE;
Boolean status = Boolean.FALSE;
List<Employee> list = new ArrayList<Employee>();
List<Employee> empList = new ArrayList<Employee>();
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public List<Employee> getEmployees() {
System.out.println("hghhghhhhh");
String sql2="";
Query query = null;
String sql1 = "from Employee as emp where id is not null ";
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
sess.beginTransaction();
if(status==false && search==false) {
System.out.println("Normal Query +++++++++++++++++++++++ " + sql1);
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==true) {
System.out.println("came inside when search and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==false && search==true) {
System.out.println("came inside when search is true and status is false");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==false) {
System.out.println("came inside when search is false and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}
list = query.list();
/*if (status) {
Collections.sort(list, new NameComparator());
} else {
Collections.sort(list, new NameCompartor1());
}*/
System.out.println(list.size());
this.empList = list;
return list;
}
public String createCriteriaQuery(String query) {
StringBuffer sb = new StringBuffer(query);
if (getFirst_Name() != null && !(getFirst_Name().equals(""))) {
sb.append(" and emp.first_Name='" + first_Name + "'");
}
if (getLast_name() != null && !(getLast_name().equals(""))) {
sb.append(" and emp.last_name='" + last_name + "'");
}
if(this.status) {
sb.append(" order by emp.first_Name desc");
}else {
sb.append(" order by emp.first_Name");
}
System.out.println(sb.toString());
return sb.toString();
}
public void editdetails() {
if (edit) {
System.out.println("rownum is " + rowNum);
System.out.println(empList.size());
employee = (Employee) empList.get((rowNum));
System.out.println(employee.getFirst_Name() + "\t"
+ employee.getLast_name() + "\t" + employee.getId());
System.out.println("end of edit details method");
} else {
employee = new Employee();
}
}
public List<Employee> getEmpList() {
return empList;
}
public void setEmpList(List<Employee> empList) {
this.empList = empList;
}
public void savedetails() {
System.out.println("came into savedetails");
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
if(this.edit) {
System.out.println("EMPLOYEE DETAILS in IF "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
System.out.println("came inside if when edit is true");
sess.update(employee);
}else {
System.out.println("came inside else when edit is false");
System.out.println("EMPLOYEE DETAILS in ELSE "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
sess.save(employee);
}
}
public void search() {
System.out.println("came into search method");
search = true;
}
public void refreshData(ActionEvent ae) {
System.out.println("came into refreshdata");
getEmployees();
}
public void sortByFirstName() {
System.out.println("came inside sortByFirstName");
if (!status) {
status = Boolean.TRUE;
} else {
status = Boolean.FALSE;
}
//status=Boolean.TRUE;
getEmployees();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
My Entity class is as follows:
package com.richfaces;
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String id;
String first_Name;
String last_name;
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
System.out.println("came inside setter method of firstname");
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
System.out.println("came inside setter method of lastname");
this.last_name = last_name;
}
}
if your exact problem is not seeing #{dBOperator.savedetails} action triggered:
i couldn't figure out the root cause yet, but this problem should be fixed by adding modal="true" to the rich:popupPanel attributes and moving validateFields() function into the popup panel. i faced this problem many times and saw it working properly on different popup components, including this one.

jsf2 template component with parameter

I have a jsf template page. In this template i would like to use component with parameter. Actually i would like to iterate over collection. This collection should be determined by parameters from particular page. Parameter name is selectedMenu. How can i use this in my bean?
<div id="notes">
selectedMenu: #{selectedMenu}
<h:form>
<h:inputHidden value="#{notatkaController.searchForm.kategoria}">
<f:param value="#{selectedMenu}" />
</h:inputHidden>
<ui:repeat value="#{notatkaController.items}" var="item" varStatus="iter">
<f:param value="#{selectedMenu}" />
<p class="q-title"><strong><h:outputText value="#{item.ntaData}" /></strong></p>
<p class="answer"><h:outputText value="#{item.ntaDane}" escape="false" /></p>
</ui:repeat>
<span>Moje notatki</span>
<textarea>Tu wpisz treść swojej notatki</textarea>
<span>[+] dodaj notatkę</span>
</h:form>
</div>
My bean:
#ManagedBean(name = "notatkaController")
#ViewScoped
public class NotatkaController extends AbstractController<Notatka> implements Serializable {
#EJB
private pl.alfaprojekt.model.session.NotatkaFacade ejbFacade;
private NotatkaSearchForm searchForm;
public DataModel getItems() {
if (items == null)
items = getPagination().createPageDataModel();
return items;
}
public PaginationHelper getPagination() {
if (pagination == null) {
if (paginationSize == null)
paginationSize = 10;
pagination = new PaginationHelper(paginationSize) {
#Override
public int getItemsCount() {
return getFacade().countByParam(getSearchForm());
}
#Override
public DataModel createPageDataModel() {
if (rapId == null)
return new ListDataModel(getFacade().findRangeByParam(getSearchForm(), new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
else {
Long uzyId = SessionUtil.getUser().getUzyId();
return new ListDataModel(convertToRaportWierszList(getFacade().findRangeByParam(getSearchForm(), new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}), uzyId));
}
}
};
}
return pagination;
}
}
I am not sure I understood the question but the question I answer is this:
I want to dynamically display something. I want to tell it what to display when the page gets accessed.
View:
You could then use the following:
<f:event listener="#{myBean.myMethod}" type="preRenderView" />
Bean:
public void myMethod(ComponentSystemEvent event){
//your logic here
}
With parameter:
<f:metadata>
<f:event listener="#{myBean.myMethod}" type="preRenderView" id="fevent"/>
<f:attribute name="myParam" value="#{mySecondBean.param)" />
</f:metadata>
And
public void myMethod(ComponentSystemEvent event){
String id = (String) event.getComponent().getAttributes().get("myParam");
}

selectOneMenu validation error

I implemented code that allows me to display a dropdown which depends on another. Everything works fine except when I try to retrieve and display the value of the two fields, it raises the following error:
form:parcours : erreur : de validation. la valeur est incrorrecte
in english :
form:parcours : validation error. value is not valid
I am using JSF 2.0, EJB 3.0, JPA 2.0 and PrimeFaces 3.2.
View:
<h:form id="form" >
<!-- <p:growl id="msgs" showDetail="true"/> -->
<h:messages globalOnly="true"/>
<p:growl id="msgs" showDetail="true" />
<p:panel header="Double Combo" style="margin-bottom:10px;">
<h:panelGrid columns="2" cellpadding="5">
<p:selectOneMenu id="countries" value="#{plansEtude.selectedDep}">
<f:selectItem itemLabel="Select Country" itemValue="" />
<f:selectItems value="#{plansEtude.depList}" var="c" itemLabel="#{c.nomDepFr}" itemValue="#{c.id}"/>
<p:ajax update="parcours,parcoursTab"
listener="#{plansEtude.handleDepChange}" />
</p:selectOneMenu>
<p:selectOneMenu id="parcours" value="#{plansEtude.selectedParcours}" >
<f:convertNumber maxFractionDigits="0"/>
<f:selectItem itemLabel="Select City" itemValue="" />
<f:selectItems value="#{plansEtude.parcoursList}" var="ct" itemLabel="#{ct.designParcours}" itemValue="#{ct.id}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
<p:commandButton value="Submit" update="msgs" actionListener="#{plansEtude.displayLocation}" id="btnSubmit"/>
</p:panel>
Controller :
#EJB
private DepartementFacade departementFacade;
#EJB
private ParcoursFacade parcoursFacade;
private List<Departement> depList;
private List<Parcours> parcoursList;
private Integer selectedDep;
private Integer selectedParcours;
public PlansEtude() {
}
public DepartementFacade getDepartementFacade() {
return departementFacade;
}
public void setDepartementFacade(DepartementFacade departementFacade) {
this.departementFacade = departementFacade;
}
public ParcoursFacade getParcoursFacade() {
return parcoursFacade;
}
public void setParcoursFacade(ParcoursFacade parcoursFacade) {
this.parcoursFacade = parcoursFacade;
}
public List<Departement> getDepList() {
depList = getDepartementFacade().findAll();
return depList;
}
public void setDepList(List<Departement> depList) {
this.depList = depList;
}
public List<Parcours> getParcoursList() {
return parcoursList;
}
public void setParcoursList(List<Parcours> parcoursList) {
this.parcoursList = parcoursList;
}
public Integer getSelectedDep() {
return selectedDep;
}
public void setSelectedDep(Integer selectedDep) {
this.selectedDep = selectedDep;
}
public Integer getSelectedParcours() {
return selectedParcours;
}
public void setSelectedParcours(Integer selectedParcours) {
this.selectedParcours = selectedParcours;
}
public void handleDepChange(){
if(selectedDep !=null && !selectedDep.equals(""))
parcoursList = parcoursFacade.findParcoursInDep(selectedDep);
else
parcoursList = new ArrayList<Parcours>();
}
public void handleParcoursChange(){
}
public void displayLocation() {
String monMessage="Departement :" + selectedDep + ", Parcours : " + selectedParcours;
FacesMessage msg = new FacesMessage("Selected", monMessage);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
parcoursFacade :
public List<Parcours> findParcoursInDep(Integer dep){
Query query = em.createNamedQuery("Parcours.findParcoursInDep");
query.setParameter("dep", dep);
return (List<Parcours>)query.getResultList();
}
Named query :
#NamedQuery(name = "Parcours.findParcoursInDep", query = "SELECT p FROM Parcours p WHERE p.departementid.id = :dep"),
Remove the <f:convertNumber maxFractionDigits="0"/> from your parcours dropdown. It makes no sense. It would only convert the number to BigDecimal while you need an Integer.
Another possible cause is that the #{plansEtude.parcoursList} has incompatibly changed during the form submit because the managed bean is request scoped. You need to make sure that the managed bean is placed in at least the view scope, so that the parcoursList is preserved for the submit.

Resources