I am trying to do some work when the h:commandButton is clicked. I am using jsf 2.2 as I am sending multipart data. I have 3 commandButtons in my form, The first 2 are working fine whereas the 3rd commandButton is not working.
This is my jsf page code:
<h:form id="userSetup" enctype="multipart/form-data" >
<div style=" margin-left: 250px; padding-top: 10px;width: 150px;margin-top: 100px;">
<img id="profile-picture" src="http://www.aspirehire.co.uk/aspirehire-co-uk/_img/profile.svg" height="120" width="120"></img>
<button onclick="addProfilePicture();return false;" class="cff-button" style="margin-top: 10px;margin-left: -10px;white-space: normal;width: 150px;">Add Profile Picture</button>
</div>
<br/><br/>
<h:inputFile id="profilePicture" value="#{uploader.profilePicture}" a:hidden="true" onchange="displayImage(this)">
<f:validator validatorId="imageValidator"></f:validator>
</h:inputFile>
<div class="user-input-div">
<h:messages id="response-message" style="color: red"></h:messages>
<h:inputText id="skills" a:placeholder="Skills" class="cff-inputText " ></h:inputText>
<br/><br/>
<button class="cff-button " style=" white-space: normal" onclick="toggleCertificateInput('#{certificateInput.clientId}',true);return false">Add Certificate</button>
<br/><br/>
<h:panelGroup id="certificate-input" layout="block" binding="#{certificateInput}" a:hidden="true" >
<h:inputText id="certificateName" value="#{uploader.certificateName}" class="cff-inputText" a:required="true" a:placeholder="Certificate Name" binding="#{certificateName}">
<f:validator validatorId="stringValidator"></f:validator>
</h:inputText>
<h:inputText id="certificateLink" value="#{uploader.certificateLink}" class="cff-inputText" a:placeholder="Link" binding="#{certificateLink}">
<f:validator validatorId="urlValidator"></f:validator>
</h:inputText>
<h:commandButton value="Save Certificate" class="cff-button" action="#{uploader.saveCertificate()}" >
<f:ajax execute="certificateName certificateLink response-message" onevent="function hide(data){ if(data.status === 'success'){ toggleCertificateInput('#{certificateInput.clientId}',false) } }" render="userSetup:certificate-output certificateName certificateLink response-message"></f:ajax>
</h:commandButton>
<button class="cff-button" onclick="toggleCertificateInput('#{certificateInput.clientId}',false);return false">Cancel</button>
</h:panelGroup>
<h:panelGroup id="certificate-output-div" binding="#{certificateOutput}">
<h:dataTable var="certificate" id="certificate-output" value="#{uploader.certificates}">
<h:column>
<h:outputText id="certificate-output-name" value="#{certificate.certificateName} " class="certificate-name"></h:outputText>
<h:outputLink id="certificate-output-link" class="cff-link" value=" #{certificate.link}">view certificate</h:outputLink>
<span id="remove" onclick="removeCertificate('#{removeCertificate.clientId}');" class="remove"> ×</span>
<h:commandButton a:hidden="true" binding="#{removeCertificate}" id="removeCertificate" action="#{uploader.removeCertificate(certificate)}" value="Remove" class="cff-button" >
<f:ajax execute=" certificate-output certificate-output-link certificate-output-name " render="userSetup:certificate-output response-message"></f:ajax>
</h:commandButton>
</h:column>
</h:dataTable>
</h:panelGroup>
//This command button is not working
<h:commandButton class="cff-button" action="#{uploader.saveAndContinue()}" value="Save and Continue">
<f:ajax execute="#form"></f:ajax>
</h:commandButton>
</div>
</h:form>
This is my model code:
#ManagedBean(name="uploader")
#ViewScoped
public class userDataUploader {
private String about_Yourself;
private String skills;
private List<Certificates> certificates;
private Part profilePicture;
private String certificateName;
private String certificateLink;
#ManagedProperty(value="#{userData}")
private User userData;
#PostConstruct
public void init(){
certificates = new ArrayList<Certificates>();
}
public List<Certificates> getCertificates() {
return certificates;
}
public void setCertificates(List<Certificates> certificates) {
this.certificates = certificates;
}
public Part getProfilePicture() {
return profilePicture;
}
public void setProfilePicture(Part profilePicture) {
this.profilePicture = profilePicture;
}
public String getAbout_Yourself() {
return about_Yourself;
}
public void setAbout_Yourself(String about_Yourself) {
this.about_Yourself = about_Yourself;
}
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
public User getUserData() {
return userData;
}
public void setUserData(User userData) {
this.userData = userData;
}
public String getCertificateName() {
return certificateName;
}
public void setCertificateName(String certificateName) {
this.certificateName = certificateName;
}
public String getCertificateLink() {
return certificateLink;
}
public void setCertificateLink(String certificateLink) {
this.certificateLink = certificateLink;
}
public void addCertificate(){
out.println("about to add new Certificate");
}
public void removeCertificate(Certificates certificate){
out.println("about to remove certificate " + certificate.getCertificateName() + " " + certificate.getLink() );
certificates.remove(certificate);
out.println(certificates.isEmpty());
}
public void saveCertificate(){
Certificates certificate = new Certificates();
certificate.setCertificateName(certificateName);
out.println(certificateName + "\n" + certificateLink);
certificate.setLink(certificateLink);
certificates.add(certificate);
out.println("new certificate has been added");
certificateName = null;
certificateLink = null;
out.println(certificates.isEmpty());
}
public String saveAndContinue(){
out.println("welcome to save and continue function");
out.println(skills);
boolean result = true;
Uploader uploader = new Uploader(userData,certificates,getSkillsArray(),profilePicture);
String returnString = "success";
out.println("about to save all data");
try {
uploader.saveAllData();
} catch (Exception ex) {
out.println(ex);
result = false;
}
if(!result){
returnString = "false";
}
out.println("return string is " + returnString);
return returnString;
}
private String[] getSkillsArray(){
return skills.split(" ");
}
}
Can somebody please tell me where I am going wrong? ThankYou.
Related
I do not why although I verify everything which is right. Anyone know?
I tried to debug:
- getAsString() return ID (that's right)
- when I submitted - getAsObject() always throw exception because the label values was always passed instead of ID values.
My code as below:
my xhtml file:
<div class="ui-grid-row" style="margin-top: 5px; margin-bottom: 5px;">
<div class="ui-grid-col-2 pdt4">
<p:outputLabel for="txtApprovalScheduler"
value="#{lang['workforce.category.parttimeManagement.approved.scheduler']}"/>
</div>
<div class="ui-grid-col-2">
<p:selectOneMenu value="#{parttimeController.selectedAgentDTO}"
id="txtApprovalScheduler"
filterMatchMode="contains" editable="true"
style="width: 86%;"
required="true"
requiredMessage="#{lang['workforce.category.parttimeManagement.approved.scheduler.missing']}">
<f:converter converterId="agentConverter"/>
<f:selectItem itemValue="" itemLabel="#{lang['wf.common.choose']}"/>
<f:selectItems value="#{parttimeController.agentDTOs}" var="agentItem1"
itemLabel="#{agentItem1.userName}"
itemValue="#{agentItem1}"/>
</p:selectOneMenu>
</div>
<div class="ui-grid-col-2 pdt4">
<p:outputLabel for="txtApprovalRegister"
value="#{lang['workforce.category.parttimeManagement.approved.register']}"/>
</div>
<div class="ui-grid-col-2">
<p:selectOneMenu value="#{parttimeController.selectedAgentDTOForRegister}"
id="txtApprovalRegister" editable="true"
filterMatchMode="contains" style="width: 86%; font-size: 12px !important;"
required="true"
requiredMessage="#{lang['workforce.category.parttimeManagement.approved.register.missing']}">
<f:converter converterId="agentConverter"/>
<f:selectItem itemValue="" itemLabel="#{lang['wf.common.choose']}"/>
<f:selectItems value="#{parttimeController.agentDTOs}" var="item1"
itemLabel="#{item1.userName}"
itemValue="#{item1}"/>
</p:selectOneMenu>
</div>
</div>
My Converter:
#FacesConverter(forClass = AgentDTO.class,value = "agentConverter")
public class AgentConverter implements Converter {
public static List<AgentDTO> listAgentDTOs;
#Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String agentId) {
if (agentId.trim().equals("")) {
return null;
} else {
try {
Long number = Long.parseLong(agentId);
for (AgentDTO a : listAgentDTOs) {
if (a.getAgentId() == number) {
return a;
}
}
} catch (NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid data"));
}
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
if (value == null || value.equals("") || "-1".equals(value)) {
return "";
} else {
String result = String.valueOf(((AgentDTO) value).getAgentId());
return result;
}
}
}
My bean:
#Component
#Scope("view")
#ManagedBean(name = "parttimeController")
public class ParttimeController extends BaseController implements Serializable {
private AgentDTO selectedAgentDTO;
private AgentDTO selectedAgentDTOForRegister;
private List<AgentDTO> agentDTOs;
.... getter/setter and initiallize AgentCenvert.listAgentDTOs
My class:
public class AgentDTO{
private Long agentId;
private String userName;
....getter/setter
}
I found out the reason - I only remove editable attribute in selectOneMenu. So getAsObject() will pass a value instead of a label
i have a jsf page that update employee table with this code....
i can get the data,but i can't update it with primefaces.and when i debug it,it doesn't do anything. i need help to update the data. thanks
this is my page controller
#ManagedBean(name = "homebean")
#ViewScoped
public class HomeController implements Serializable {
private Employee employee;
private List<Employee> employees;
private EmployeeeDAO employeeeDAO;
public HomeController() {
employeeeDAO = new EmployeeDAOImpl();
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public void editEmployee() throws SQLException {
Employee e = this.getEmployee();
employeeeDAO.update(e);
}
#PostConstruct
private void getListEmployees() {
employees = employeeeDAO.employees(20, 10);
}
}
and this is my DAO
public class EmployeeDAOImpl implements EmployeeeDAO, Serializable {
private PreparedStatement ps;
private ResultSet rs;
#Override
public void add(Employee emp) {
try (Connection c = ConnectionHelper.getConnection()) {
String sql = "UPDATE EMPLOYEES"
+ " SET FIRST_NAME = ?,"
+ " LAST_NAME = ?,"
+ " EMAIL = ? WHERE EMPLOYEE_ID=?";
ps = c.prepareStatement(sql);
ps.setString(1, emp.getFirstname());
ps.setString(2, emp.getLastname());
ps.setString(3, emp.getEmail());
ps.setInt(4, emp.getEmployeeId());
ps.executeUpdate();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} catch (SQLException ex) {
Logger.getLogger(EmployeeDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void update(Employee emp) throws SQLException {
try (Connection c = ConnectionHelper.getConnection()) {
String sql = "UPDATE EMPLOYEES "
+ " SET FIRST_NAME = ?,"
+ " LAST_NAME = ?,"
+ " EMAIL = ? WHERE EMPLOYEE_ID=?";
ps = c.prepareStatement(sql);
ps.setString(1, emp.getFirstname());
ps.setString(2, emp.getLastname());
ps.setString(3, emp.getEmail());
ps.setInt(4, emp.getEmployeeId());
ps.execute();
} catch (SQLException ex) {
Logger.getLogger(EmployeeDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public List<Employee> employees(int size, int lastRow) {
List< Employee> list = null;
try (Connection c = ConnectionHelper.getConnection()) {
String sql = "SELECT ROWNUM NUM,EMP.* FROM EMPLOYEES EMP ORDER BY ROWNUM";
ps = c.prepareStatement(sql);
rs = ps.executeQuery();
list = new ArrayList<Employee>();
while (rs.next()) {
Employee e = new Employee();
e.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
e.setFirstname(rs.getString("FIRST_NAME"));
e.setLastname(rs.getString("LAST_NAME"));
e.setEmail(rs.getString("EMAIL"));
e.setHireDate(rs.getDate("hire_date"));
e.setSalary(rs.getBigDecimal("salary"));
list.add(e);
}
} catch (Exception e) {
}
return list;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Employee getById(String id) {
return null;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and this is the jsf page..
<p:dataTable id="employeetable" value="#{homebean.employees}" var="emp" rows="10" paginator="true"
selection="#{homebean.employee}">
<p:column headerText="First Name">#{emp.firstname}</p:column>
<p:column headerText="First Name">#{emp.lastname}</p:column>
<p:column headerText="First Name"><h:outputText value="#{emp.salary}">
<f:convertNumber type="currency" currencySymbol="$ "/>
</h:outputText></p:column>
<p:column headerText="First Name">#{emp.email}</p:column>
<p:column width="50">
<p:commandButton value="Edit" oncomplete="editdialog.show();"
partialSubmit="true" update="#([id$=display])">
<f:setPropertyActionListener value="#{emp}" target="#{homebean.employee}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<h:form>
<p:dialog widgetVar="editdialog" id="edit" modal="true" appendToBody="true" resizable="false">
<h:panelGrid id="display" columns="2" cellspacing="4">
<h:outputText value="ID"/>
<p:inputText value="#{homebean.employee.employeeId}" disabled="true">
<f:convertNumber type="number"/></p:inputText>
<p:spacer/><p:spacer/>
<h:outputText value="First Name"/>
<h:outputText value="Last Name"/>
<p:inputText value="#{homebean.employee.firstname}"/>
<p:inputText value="#{homebean.employee.lastname}"/>
<h:outputText value="Email"/>
<h:outputText value="Salary"/>
<p:inputText value="#{homebean.employee.email}"/>
</h:panelGrid>
<p:separator/>
<p:commandButton value="save" action="#{homebean.editEmployee()}" partialSubmit="true"
update="#([id$=employeetable])" oncomplete="editdialog.hide();"/>
</p:dialog>
</h:form>
</ui:define>
finally i get the answer....we need to make sure that the property of Employee is correct. and have match datatype with our database...thanks all
In JSF2 - I see my datatable reloading each time when i make an ajax call by clicking on each column row. Is there a way to stop loading each time i make an ajax call ? This creates problem by resetting my datatable to default values and i get a wrong value back at managed bean.
<h:inputText size="8" id="startDate"
value="#{contactBean.startDate}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:inputText>
<h:outputText> - </h:outputText>
<h:inputText size="8" id="endDate" value="#{contactBean.endDate}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:inputText>
<h:commandButton value="Filter"
actionListener="#{contactBean.loadAJAXFilterContentList}">
<f:ajax render=":form1:tableContents" />
</h:commandButton>
<h:dataTable id="tableContents"
value="#{contactBean.filterContentList}" var="crs"
binding="#{contactBean.dataTable}" border="1">
<h:column>
<f:facet name="header">
<h:outputText styleClass="contactTableHeader" value="Date/Time" />
</f:facet>
<h:commandLink action="#{contactBean.loadPreviewScreenContents(crs)}">
<h:outputText title="#{crs.dateTime}" value="#{crs.dateTime}">
<f:convertDateTime pattern="MM/dd/yyyy hh:mm a" type="date" />
</h:outputText>
<f:ajax render=":form1:previewScreen" />
</h:commandLink>
</h:column>
</h:dataTable>
<h:panelGrid id="previewScreen">
<h:outputText styleClass="PreviewHeader"
value="Preview of #{contactBean.previewCntDateTime}" />
</h:panelGrid>
So in the above case whenever i click the column it calls the filterContentList() method in my managed bean instead of calling loadPreviewScreenContents(crs) directly.
My bean is RequestScoped. I tried with SessionScope,ViewScope but these 2 scopes retain my previous states like i have other ajax functions in my page and it retains that state. So i cant use Session or ViewScopes in this case.
Is there a solution ?
Bean code:
#ManagedBean(name = "contactBean")
#RequestScoped
public class ContactManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
List<ContactResponseBean> filterContentList = new ArrayList<ContactResponseBean>();
ContactRequestBean contactRequestBean = new ContactRequestBean();
ContactResponseBean crs = new ContactResponseBean();
private String logText;
HtmlDataTable dataTable;
public void setFilterContentList(List<ContactResponseBean> filterContentList) {
this.filterContentList = filterContentList;
}
public void setFilterContentList(List<ContactResponseBean> filterContentList) {
this.filterContentList = filterContentList;
}
public Date getPreviewCntDateTime() {
return previewCntDateTime;
}
public void setPreviewCntDateTime(Date previewCntDateTime) {
this.previewCntDateTime = previewCntDateTime;
}
public String getLogText() {
return logText;
}
public void setLogText(String logText) {
this.logText = logText;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public ContactResponseBean getCrs() {
return crs;
}
public void setCrs(ContactResponseBean crs) {
this.crs = crs;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public void loadAJAXFilterContentList() {
filterButtonAjxFlag = true;
}
public List<ContactResponseBean> getFilterContentList() {
ContactRequestBean contactRequestBean = new ContactRequestBean();
contactRequestBean.setUserId(getUserId());
contactRequestBean.setSummaryType(getSummaryType());
contactRequestBean.setStartDate(getStartDate());
contactRequestBean.setEndDate(getEndDate());
ContactRequestBeanService crbs = new ContactRequestBeanService();
filterContentList = crbs.getFilterContentList(contactRequestBean);
return filterContentList;
}
public void loadPreviewScreenContents(){
crs = (ContactResponseBean) dataTable.getRowData();
setPreviewCntDateTime(crs.getDateTime());
}
}
I've been strugling with an issue I can't find the way to solve it and I can't find anything related on the web.
I'm using Netbeans with Primefaces to develop a JSF web app.
Everything works fine except that sometimes the call to the actionlisteners is being done several times.
For example this is my JSF page with primefaces:
<h:body>
<ui:composition template="home.xhtml">
<ui:define name="content">
<h2>Administración de alertas SMS</h2>
<p:panel id="display">
<p:selectBooleanCheckbox itemLabel="Enviar alertas SMS" value="#{smsConfigBean.alertsEnabled}"/>
<p>
<h:outputText value="Mensaje de Texto: " /><br /><br />
<p:inputTextarea rows="5" cols="50" counterTemplate="{0} caracteres restantes." counter="counter" maxlength="160" value="#{smsConfigBean.smsMessage}" id="smsMessage"/>
<br />
<h:outputText id="counter" />
</p>
<p>
<h:outputText value="Dispositivo de envio SMS: " />
<p:selectOneRadio id="options" value="#{smsConfigBean.usePhone}">
<f:selectItem itemLabel="Modem USB" itemValue="false" />
<f:selectItem itemLabel="Telefono Android" itemValue="true" />
</p:selectOneRadio>
</p>
<br />
<p:tabView id="tabView">
<p:tab id="tab1" title="Modem USB">
<h:panelGrid id="modemGrid" columns="2" cellpadding="4">
<h:outputText value="Puerto: " />
<p:inputText id="port" value="#{smsConfigBean.port}"/>
<h:outputText value="Bit Rate (Opcional): " />
<p:inputText id="bitRate" value="#{smsConfigBean.bitRate}"/>
<h:outputText value="Nombre de modem (Opcional): " />
<p:inputText id="modemName" value="#{smsConfigBean.modemName}"/>
<h:outputText value="PIN: " />
<p:inputText id="pin" value="#{smsConfigBean.modemPin}"/>
<h:outputText value="Centro de Mensajes: " />
<p:inputText id="smsc" value="#{smsConfigBean.SMSC}"/>
</h:panelGrid>
</p:tab>
<p:tab id="tab2" title="Telefono Android">
<h:panelGrid id="phoneGrid" columns="2" cellpadding="4">
<h:outputText value="Path ADB:" />
<p:inputText id="adbPath" value="#{smsConfigBean.adbPath}"/>
<h:outputText value="Directorio de Configuracion:" />
<p:inputText id="configPath" value="#{smsConfigBean.configPath}"/>
<h:outputText value="Modo de conexion " />
<p:selectOneRadio id="connectOptions" value="#{smsConfigBean.useWifi}">
<f:selectItem itemLabel="USB" itemValue="false"/>
<f:selectItem itemLabel="WiFi" itemValue="true" />
</p:selectOneRadio>
<h:outputText value="Direccion IP (Solo para WiFi): " />
<p:inputText id="ipDir" value="#{smsConfigBean.ipDir}"/>
</h:panelGrid>
</p:tab>
</p:tabView>
</p:panel>
<br />
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" action="#{smsConfigBean.saveChanges}" actionListener="#{smsConfigBean.saveChanges}"/>
</ui:define>
</ui:composition>
</h:body>
And this is my backend bean:
package Beans;
import helpers.Global; import javax.faces.bean.ManagedBean; import
javax.faces.bean.SessionScoped;
#ManagedBean #SessionScoped public class SmsConfigBean {
private Boolean alertsEnabled;
private Boolean usePhone;
private Boolean useWifi;
private String port;
private int bitRate;
private String modemName;
private String modemPin;
private String SMSC;
private String adbPath;
private String configPath;
private String ipDir;
private String smsMessage;
public SmsConfigBean() {
alertsEnabled = Global.getAlertsEnabled();
port = Global.getPort();
bitRate = Global.getBitRate();
modemName = Global.getModemName();
modemPin = Global.getModemPin();
SMSC = Global.getSMSC();
usePhone = Global.getUsePhone();
adbPath = Global.getAdbPath();
configPath = Global.getConfigPath();
useWifi = Global.getUseWifi();
ipDir = Global.getIpDir();
smsMessage = Global.getSmsMessage();
}
public Boolean getAlertsEnabled() {
return alertsEnabled;
}
public void setAlertsEnabled(Boolean alertsEnabled) {
this.alertsEnabled = alertsEnabled;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getBitRate() {
return bitRate;
}
public void setBitRate(int bitRate) {
this.bitRate = bitRate;
}
public String getModemName() {
return modemName;
}
public void setModemName(String modemName) {
this.modemName = modemName;
}
public String getModemPin() {
return modemPin;
}
public void setModemPin(String modemPin) {
this.modemPin = modemPin;
}
public String getSMSC() {
return SMSC;
}
public void setSMSC(String SMSC) {
this.SMSC = SMSC;
}
public Boolean getUsePhone() {
return usePhone;
}
public void setUsePhone(Boolean usePhone) {
this.usePhone = usePhone;
}
public String getAdbPath() {
return adbPath;
}
public void setAdbPath(String adbPath) {
this.adbPath = adbPath;
}
public String getConfigPath() {
return configPath;
}
public void setConfigPath(String configPath) {
this.configPath = configPath;
}
public Boolean getUseWifi() {
return useWifi;
}
public void setUseWifi(Boolean useWifi) {
this.useWifi = useWifi;
}
public String getIpDir() {
return ipDir;
}
public void setIpDir(String ipDir) {
this.ipDir = ipDir;
}
public String getSmsMessage() {
return smsMessage;
}
public void setSmsMessage(String smsMessage) {
this.smsMessage = smsMessage;
}
public void saveChanges(){
Global.setSmsMessage(smsMessage);
Global.setIpDir(ipDir);
Global.setUseWifi(useWifi);
Global.setConfigPath(configPath);
Global.setAdbPath(adbPath);
Global.setUsePhone(usePhone);
Global.setSMSC(SMSC);
Global.setModemPin(modemPin);
Global.setModemName(modemName);
Global.setBitRate(bitRate);
Global.setPort(port);
Global.setAlertsEnabled(alertsEnabled);
Global.sendInfoResponseMessage("Cambios guardados con exito");
}
}
The problem is that when saving the changes of this form by hitting the commandButton 'saveSmsAlerts' the call is being made twice. Resulting in the growl message to be shown twice too.
(You won't see the growl component because it was defined in the template)
This happens also in another page that I did for the same app that uploads a file using fileuploader. The file is uploaded 4 times!!
I'm using chrome to test the application and netbeans to develop it.
You should remove one of action or actionListener attribute.
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" action="#{smsConfigBean.saveChanges}"/>
if you remove action attribute you should change the action method signature
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" actionListener="#{smsConfigBean.saveChanges}"/>
Like this
public void saveChanges(ActionEvent e){
...
}
here is the difference between action and actionListener
Differences between action and actionListener
i am new to JSF.
i have a problem with tag my .jsp page is like this:
<h:form id="form1">
<t:inputHidden id="primaryKey"
value="#{EditConfigurationBean.primaryKey}" forceId="true" />
<t:inputHidden id="beanName"
value="#{EditConfigurationBean.beanName}" forceId="true" />
<t:dataTable id="datatable" value="#{EditConfigurationBean.config}" rowIndexVar="rowIndex" var="rowvar"
rowClasses="standardTable_Row1,standardTable_Row2"
columnClasses="standardTable_Column1,standardTable_Column2,standardTable_Column3">
<h:column>
<f:facet name="header">
<h:panelGroup>
<f:verbatim>
<object width="0px" height="0px"></object>
</f:verbatim>
<h:outputText
value="Entry Name" />
</h:panelGroup>
</f:facet>
<h:outputLabel value="#{rowvar.bean.name}"></h:outputLabel>
</h:column>
<t:column>
<f:facet name="header">
<h:panelGroup>
<f:verbatim>
<object width="0px" height="0px"></object>
</f:verbatim>
<h:outputText
value="Entry Value" />
</h:panelGroup>
</f:facet>
<h:inputText styleClass="inputText" value="#{rowvar.value}"></h:inputText>
</t:column>
</t:dataTable>
<t:htmlTag value="div" styleClass="commandBar">
<h:commandButton onmouseover="over(this)" onmouseout="out(this)" action="#{EditConfigurationBean.back}" id="navigation" immediate="true" value="back" styleClass="commandButton" />
<h:commandButton onmouseover="over(this)" onmouseout="out(this)" action="#{EditConfigurationBean.update}" value="Update" styleClass="commandButton" />
</t:htmlTag>
</h:form>
and my backbean code is:
public class ConfigurationEditBean{
public String getInit(){
try {
config = loadConfig();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (config != null)
this.entriesCount =this.config.size();
return "";
}
private int primaryKey;
private java.lang.String beanName;
private int entriesCount;
private List<ConfigurationFullEntry> config;
public int getEntriesCount() {
return entriesCount;
}
public void setEntriesCount(int entriesCount) {
this.entriesCount = entriesCount;
}
public void setConfig(List<ConfigurationFullEntry> config) {
this.config = config;
}
public int getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(int primaryKey) {
this.primaryKey = primaryKey;
}
public java.lang.String getBeanName() {
return beanName;
}
public void setBeanName(java.lang.String beanName) {
this.beanName = beanName;
}
private List<ConfigurationFullEntry> loadConfig() throws Exception{
List<ConfigurationFullEntry> entriesList = new ArrayList<ConfigurationFullEntry>();
//do load from DB
return entriesList;
}
public List<ConfigurationFullEntry> getConfig() {
return config;
}
public String update(){
return "";
}
public String back(){
return "";
}
}
the problem is that page display correctly but when i am change value of one
tags and submit the form, corresponding setXXX of backbean is not called.
also when i have tried an inputtext tag outside of
wha's wrong about my codes?
thanks in advance
Update: this is my generated HTML no nested form exist within it.:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="http://localhost:7001"><title>My JSF 'ConfigurationEditor.jsp' starting page</title></head><body><form id="j_id_id2" name="j_id_id2" method="post" action="/HealthMonitorConsole/ConfigurationEditor.jsf" enctype="application/x-www-form-urlencoded"><input type="hidden" id="primaryKey" name="primaryKey" value="0"><input type="hidden" id="beanName" name="beanName" value="com.pardis.healthMonitor.dm.service.ServiceBean"> <table><thead><tr><th scope="col">Name</th><th scope="col">Value</th></tr></thead><tbody id="j_id_id2:j_id_id5:tbody_element"><tr><td>Server</td><td><input id="j_id_id2:j_id_id5:0:j_id_id13" name="j_id_id2:j_id_id5:0:j_id_id13" type="text" value=""></td></tr><tr><td>arash</td><td><input id="j_id_id2:j_id_id5:1:j_id_id13" name="j_id_id2:j_id_id5:1:j_id_id13" type="text" value=""></td></tr></tbody></table><br>
<input id="j_id_id2:j_id_id14" name="j_id_id2:j_id_id14" type="submit" value="Save" onclick="if(typeof window.getScrolling!='undefined'){oamSetHiddenInput('j_id_id2','autoScroll',getScrolling());}"> <input type="hidden" name="autoScroll"> <input type="hidden" name="j_id_id2_SUBMIT" value="1"><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="8EgC7hvJoXWgMHaUZxk5rx66APlnNueyP32ajDxbvc/i5akMf2jX5SQ5BLInRDoWgWvcMUADuXlYwCWVxYrNWghZBdlolM+1zLfQTh4aUm4="></form>
<script type="text/javascript"><!--
function getScrolling()
{
var x = 0; var y = 0;if (self.pageXOffset || self.pageYOffset)
{
x = self.pageXOffset;
y = self.pageYOffset;
}
else if ((document.documentElement && document.documentElement.scrollLeft)||(document.documentElement && document.documentElement.scrollTop))
{
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
else if (document.body)
{
x = document.body.scrollLeft;
y = document.body.scrollTop;
}
return x + "," + y;
}
//--></script>
</body></html>
i am writing every thing like tutorial examples but it does not work!
You need to ensure that exactly the same datamodel is preserved during the apply request values phase of the form submit as it was during the render response phase of the initial page display. A normal place is to do the preloading is the constructor of the backing bean.
public class Bean {
private List<Item> items;
public Bean() {
items = itemDAO.list();
}
// ...
}
An alternative is to put the bean in the session scope, but this has more impact on user experience.
Since you're using Tomahawk, you can also just set the preserveDataModel attribute of the t:dataTable to true like so:
<t:dataTable preserveDataModel="true">
This will store the datamodel in the view's component tree (which in turn is stored in the session scope) so that exactly the same datamodel is available in the subsequent request.
See also:
Using Datatables