JSF adding textfields dynamically on click of a button - jsf

I have written the following code so that I can have a single textfield followed by a add button and a save button at the bottom.
I want the first textfield and add button to be fixed, but whenever a user cicks on add button, a text field gets added below the present textfield and the add button and save button goes down.
I have the following piece of code, but it doesnt seem to working.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Dashboard | BlueWhale Admin</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="../css/text.css" media="screen" />
<link rel="stylesheet" type="text/css" href="../css/grid.css" media="screen" />
<link rel="stylesheet" type="text/css" href="../css/layout.css" media="screen" />
<link rel="stylesheet" type="text/css" href="../css/nav.css" media="screen" />
</h:head>
<body>
<h:form>
<hr/>
<h:dataTable id="newsinputs" value="#{newsAlerts.values}" var="item" cellspacing="10">
<h:column>
<h:outputLabel value="#{item.label}" />
</h:column>
<h:column>
<h:inputText value="#{item.news}" size="100" /><br/>
</h:column>
</h:dataTable>
<h:commandButton styleClass="btn btn-blue" action="#{newsAlerts.add()}" value="Add"></h:commandButton>
<hr/>
<h:commandButton styleClass="btn btn-blue" action="#{newsAlerts.submit}" value="Save" />
</h:form>
</body>
</html>
The bean class is as follows
package com.kc.aop.bean;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.kc.aop.VO.NewsVO;
#ManagedBean(name = "newsAlerts")
#ViewScoped
public class News
{
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
NewsVO newsVO = new NewsVO();
newsVO.setLabel("News "+ this.values.size()+1);
getValues().add(newsVO);
}
public String submit() {
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getLabel());
}
return null;
// save values in database
}
public List<NewsVO> getValues() {
return values;
}
public void setValues(List<NewsVO> values) {
this.values = values;
}
public String add()
{
NewsVO newsVO = new NewsVO();
newsVO.setLabel("News "+ this.values.size()+1);
this.values.add(newsVO);
return "success";
}
}

You're returning non-null/void from action method:
public String add() {
// ...
return "success";
}
A non-null/void outcome creates a new view scope. You need to return null or void instead to keep the same view.
public String add() {
// ...
return null;
}
or
public void add() {
// ...
}
There's absolutely no need to change it by an action listener as suggested by the other answer. It serves a completely different purpose.
See also:
Recommended JSF 2.0 CRUD frameworks

You need to use actionListener or at least modify action to return void or null in your <h:commandButton /> since you stay in the same view. By using action with a return value, the ViewScope is broken and recreated.
View code :
<h:commandButton styleClass="btn btn-blue" actionListener="#{newsAlerts.add}" value="Add" />
<hr/>
<h:commandButton styleClass="btn btn-blue" actionListener="#{newsAlerts.submit}" value="Save" />
Bean code :
public void add(ActionEvent event)
{
NewsVO newsVO = new NewsVO();
newsVO.setLabel("News "+ this.values.size()+1);
this.values.add(newsVO);
}
public void submit(ActionEvent event)
{
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getLabel());
}
}
More info :
Action vs ActionListener

Related

How to submit JSF ajax with inputs from multiple forms?

Due to UI layout issue, I have to separate inputs into multiple form. How to submit JSF ajax with inputs from multiple forms?
Based on sample code below, how to get form1 input1 value when click on the Ajax Call button in form2?
Weblogic 12.2 Java 8 Servlet 3.1 JSF 2.2 CDI 1.1 EJB 3.2
JSF Page
<!DOCTYPE HTML>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions">
<h:head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Ajax Test</title>
</h:head>
<h:body>
<ui:debug hotkey="x" />
<h:messages id="msg" />
<fieldset>
<legend>Form 1</legend>
<h:form
id="form1"
method="get">
<h:inputText
id="input1"
value="#{ajaxTestBean.input1}" />
<h:commandButton
value="Standard call"
action="#{ajaxTestBean.call}" />
</h:form>
</fieldset>
<fieldset>
<legend>Form 2</legend>
<h:form
id="form2"
method="get">
<h:inputText
id="input2"
value="#{ajaxTestBean.input2}" />
<h:commandButton value="Ajax Call">
<f:ajax
execute="form1:input1 form2:input2"
render="msg form1:input1 form2:input2"
listener="#{ajaxTestBean.callAjax}" />
</h:commandButton>
</h:form>
</fieldset>
</h:body>
</html>
Java Class
package dev;
import javax.faces.event.AjaxBehaviorEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
#javax.inject.Named("ajaxTestBean")
#javax.faces.view.ViewScoped
public class AjaxTestBean implements java.io.Serializable {
static final long serialVersionUID = 1L;
static final Logger logger = LogManager.getLogger();
String input1;
String input2;
public AjaxTestBean() {
}
public void call() {
logger.traceEntry();
logger.debug("input1: {}", this.input1);
logger.debug("input2: {}", this.input2);
logger.traceExit();
}
public void callAjax(AjaxBehaviorEvent event) {
logger.traceEntry();
logger.debug("input1: {}", this.input1);
logger.debug("input2: {}", this.input2);
logger.traceExit();
}
public String getInput1() {
return input1;
}
public void setInput1(String input1) {
this.input1 = input1;
}
public String getInput2() {
return input2;
}
public void setInput2(String input2) {
this.input2 = input2;
}
}

Primefaces Get Input Value

i have a little problem. I have want to get the value from my inputarea i am tipping in, but it doesnt update properly. the String value is always null.
xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Pragma" content="No-cache" />
<meta http-equiv="Cache-Control"
content="no-store,No-cache,must-revalidate,post-check=0,pre-check=0,max-age=0" />
<meta http-equiv="Expires" content="-1" />
<link type="text/css" rel="stylesheet"
href="#{request.contextPath}/resources/css/styles.css" />
<link rel="shortcut icon" href="#{resource['Icon.png']}"
type="image/x-icon" />
<title>#{msg['title.index']}</title>
</h:head>
<h:body style="background:#f5f5f5;">
<h:form>
<p:commandButton value="#{bean.button}"
style="margin-left:10px;margin-top:10px;" />
<p:inputTextarea value="#{bean.text}" autoResize="true"
placeholder="#{msg['label.placeholder']}" rows="3" cols="90"
style="margin-top:250px;margin-left:5px;">
</p:inputTextarea>
</h:form>
</h:body>
</html>
Bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "bean")
#SessionScoped
public class Controller {
private String text;
private String button = "Click";
public String getText() {
System.out.println(text);
return text;
}
public void setText(String text) {
this.text = text;
}
public String getButton() {
return button;
}
public void setButton(String button) {
this.button = button;
}
}
It doesnt seem like he cant find my bean, because the value i gave the button is shown correctly in the browser. But teh input doesnt work.
I have worked with jsf already and i never had problems with passing values through the bean. Another project of me is using the same method like here and it works. But in this case my inputs doesnt go to the bean. Help please.
You have to submit your form for the bean to take the value. Else the form is never sent.
So add an action to your command button which is the method that is gonna be called when the button is pressed.
<p:commandButton value="#{bean.button}"
style="margin-left:10px;margin-top:10px;" action="#{bean.submit}" />
Write in your bean
public void submit(){}
your method can contain anything you want.
There are nice jsf tutorial here those are the ones I used to start (I didn't finish though).

Boolean checkbox status update in ManagedBean

I have two Boolean type check box in my jsf page from which second check box is made disabled depending upon the first check box status and for first time page loading both the check box are unchecked. I am updating the second check box disable status through script when first check box is checked.Then i am selecting second check box.
But the problem is when i am submitting my page only first check box status is getting updated. This is my Managed Bean
#ManagedBean(name = "checkBoxTest")
#SessionScoped
public class CheckBoxTest {
private boolean check1;
private boolean check2;
public boolean isCheck1() {
return check1;
}
public void setCheck1(boolean check1) {
this.check1 = check1;
}
public boolean isCheck2() {
return check2;
}
public void setCheck2(boolean check2) {
this.check2 = check2;
}
public String update(){
boolean status = this.isCheck1();
boolean status2 = this.isCheck2();
return "checkboxExample.xhtml";
}
}
This is my jsf page
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>JSF tutorial</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/myFunction.js">
</script>
</h:head>
<h:body>
<h2>CheckBox Example</h2>
<h:form id="form">
<h:outputLabel value="First Check"/>
<h:selectBooleanCheckbox name="check1" id="check1" value="# {checkBoxTest.check1}" onclick="changeCheckBox2Status()"> </h:selectBooleanCheckbox>
<h:outputLabel value="Second Check"/>
<h:selectBooleanCheckbox name="check2" id="check2" value="#{checkBoxTest.check2}" disabled="#{checkBoxTest.check1?false:true}"> </h:selectBooleanCheckbox>
<h:commandButton action="#{checkBoxTest.update()}" value="Submit2">
</h:commandButton>
</h:form>
</h:body>
</html>
My script is given below
function changeCheckBox2Status(){
var checkBox1Status = document.getElementById("form:check1");
if(checkBox1Status.checked){
document.getElementById("form:check2").disabled=false;
}
}
Did you try something like:
public void setCheck1(boolean check1) {
this.check1 = check1;
this.check2 = !this.check2;
}
and similarly for the other.

how to force refresh of my screen in JSF

in my JSF2 app I have ​​screens composed with :
Header
Body
In the header I have a combo list. At each change in value in the combo list I have an Ajax request that updates the data in the Body. So far everything is working properly. Now the home screen's structure should be change when the value of combo list change. To do this I have :
1 ManagedBean HomeBean that manage the home
1 ManagedBean HeaderBean that manage the header
2 object HomeScreen1.java and HomeScreen2.java that allows me to valued data from each screen
2 services HomeScreen1Loader.java and HomeScreen2Loader.java that manage loading of each type of screen
1 template home.xhtml
2 fichier home1.xhtml et home2.xhtml
When I log in to the application, I get the good page corresponding (Element type 1 => home page 1). But when I select a type 2 item, the actionListener methode is execute, ManagedBean's data was updated (for type 2 screen) , but the page does not updated. What do you do ?
HeaderBean.java :
package com.omb.view;
import java.io.Serializable;
import java.util.List;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.omb.exception.TechnicalException;
import com.omb.view.util.Constants;
import com.omb.view.util.FacesUtils;
#Controller
#Scope("session")
public class HeaderBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Log logger = LogFactory.getLog(HeaderBean.class);
private List<SelectItem> elementsDisplayed;
public void initComboList() throws FunctionnalException {
// init the combo list
}
public void elementChangeListener(ValueChangeEvent event) {
if (event.getNewValue() != null) {
// Do traitement....
ContextBean contextBean = (ContextBean) FacesUtils.getObjectInSession(ContextBean.CONTEXT_BEAN_NAME);
AbstractBean currentBean = (AbstractBean) FacesUtils.getObjectInSession(contextBean
.getCurrentBeanInSession());
try {
currentBean.refresh();
} catch (TechnicalException e) {
logger.error(e.getMessage(), e);
}
}
}
public String disconnect() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "/login.xhtml?faces-redirect=true";
}
public List<SelectItem> getElementsDisplayed() {
return elementsDisplayed;
}
public void setElementsDisplayed(List<SelectItem> elementsDisplayed) {
this.elementsDisplayed = elementsDisplayed;
}
}
ContextBean.java :
package com.omb.view;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.omb.view.util.Constants;
#Controller
#Scope("session")
public class ContextBean {
public final static String CONTEXT_BEAN_NAME = "contextBean";
private String templateHomeName;
private boolean defaultHome;
public String getTemplateHomeName() {
return this.templateHomeName;
}
public void setTemplateHomeName(String templateHomeName) {
this.templateHomeName = templateHomeName;
}
public boolean isDefaultHome() {
return this.defaultHome;
}
public void setDefaultHome(boolean defaultHome) {
this.defaultHome = defaultHome;
}
}
HomeBean.java :
package com.omb.view.home;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.omb.exception.FunctionnalException;
import com.omb.exception.TechnicalException;
import com.omb.view.AbstractBean;
import com.omb.view.util.Constants;
#Controller
#Scope("session")
public class HomeBean extends AbstractBean {
private static final Log logger = LogFactory.getLog(HomeBean.class);
public static final String HOME_1_NAME = "home1.xhtml";
public static final String HOME_2_NAME = "home2.xhtml";
#Autowired
private HomeScreen1 homeScreen1;
#Autowired
private HomeScreen2 homeScreen2;
#SuppressWarnings({"unchecked", "rawtypes"})
public String display() throws TechnicalException, FunctionnalException {
ContextBean context = (ContextBean) FacesUtils.getObjectInSession(ContextBean.CONTEXT_BEAN_NAME);
if (!isInitialized()) {
if (defaultHomeScreen == null) {
defaultHomeScreen = new DefaultHomeScreen();
}
if (eurHomeScreen == null) {
eurHomeScreen = new EurHomeScreen();
}
AbstractHomeScreenLoader loader = HomeScreenLoaderFactory.getLoader(getTypeElement());
if (Constants.CODE_TYPE_1.equals(getTypeElement()) {
loader.load(homeScreen1);
context.setTemplateHomeName(HOME_1_NAME);
} else {
loader.load(homeScreen2);
context.setTemplateHomeName(HOME_2_NAME);
}
setInitialized(true);
} else if (!upToDate) {
refresh();
}
return "home";
}
#SuppressWarnings({"unchecked", "rawtypes"})
public void refresh() throws TechnicalException {
upToDate = true;
AbstractHomeScreenLoader loader = HomeScreenLoaderFactory.getLoader(getTypeElement());
if (Constants.CODE_TYPE_1.equals(userContext.getCurrentHotelCountryId())) {
loader.refresh(homeScreen1);
} else {
loader.refresh(homeScreen2);
}
}
public HomeScreen1 getHomeScreen1() {
return this.homeScreen1;
}
public void setHomeScreen1(HomeScreen1 homeScreen1) {
this.homeScreen1 = homeScreen1;
}
public HomeScreen2 getHomeScreen2() {
return this.homeScreen2;
}
public void setHomeScreen2(HomeScreen2 homeScreen2) {
this.homeScreen2 = homeScreen2;
}
}
layout.xhtml main template of the application :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:ice="http://www.icesoft.com/icefaces/component">
<h:head>
<title><ui:insert name="title">OMB</ui:insert></title>
<ice:outputStyle href="/xmlhttp/css/xp/xp.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet"
href="#{facesContext.externalContext.requestContextPath}/resources/css/style.css" />
</h:head>
<h:body>
<h:panelGroup id="page" styleClass="mainMaster" layout="block">
<h:panelGroup id="header" styleClass="header" layout="block">
<ui:insert name="header">
<ui:include
src="/pages/layer/header/#{contextBean.templateHeaderName}" />
</ui:insert>
</h:panelGroup>
<h:panelGroup id="headerMenu" styleClass="menu" layout="block">
<ui:insert name="buttons">
<ui:include
src="/pages/layer/menu/#{contextBean.templateMenuButtonName}" />
</ui:insert>
</h:panelGroup>
<h:panelGroup id="main" styleClass="mainContent" layout="block">
<h:panelGroup id="content" styleClass="content" layout="block">
<ui:insert name="content" />
</h:panelGroup>
</h:panelGroup>
<h:panelGroup id="footer" styleClass="footer" layout="block">
<ui:insert name="footer">
<ui:include src="/pages/layer/footer/footer.xhtml" />
</ui:insert>
</h:panelGroup>
</h:panelGroup>
</h:body>
</html>
header.xhtml, page which manage the combo list:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
<ui:composition>
<ice:form id="headerForm" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:ace="http://www.icefaces.org/icefaces/components"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:panelGroup styleClass="logo" layout="block">
<ice:graphicImage styleClass="imgLogoHR"
value="#{facesContext.externalContext.requestContextPath}/resources/images/common/logo/Logo.png" />
<h:panelGroup styleClass="loginArea" layout="block">
<h:panelGroup styleClass="area" layout="block">
<h:panelGroup styleClass="comboHotel" layout="block">
<ace:simpleSelectOneMenu id="selectCurrentElement"
value="#{headerBean.currentElementDisplayed}"
valueChangeListener="#{headerBean.elementChangeListener}"
labelPosition="left" indicatorPosition="left" required="false"
rendered="#{not empty headerBean.elementsDisplayed}">
<f:selectItems value="#{headerBean.elementsDisplayed}" />
<ace:ajax execute="#this" render="#all" />
</ace:simpleSelectOneMenu>
</h:panelGroup>
</h:panelGroup>
</h:panelGroup>
</h:panelGroup>
</ice:form>
</ui:composition>
</body>
</html>
home.xhtml main template of home page and component should be refresh:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:ace="http://www.icefaces.org/icefaces/components">
<h:body>
<ui:composition template="/pages/layer/layout.xhtml">
<ui:define name="content">
<ui:include
src="/pages/home/#{contextBean.templateHomeName}" />
</ui:define>
</ui:composition>
</h:body>
</html>
I found the solution, the problem came to the ManagedBean ContextBean's templateHomeName attribute that was not properly valued. I added in loader.load(homeScreen1) and refresh and everything it's ok. I should upgrade my JSF version : 2.1.0-b11 to 2.1.26 because I had an error when refresh.

p:remoteCommand destroys #ViewScoped managed bean

I am having trouble adding a p:remoteCommand to a form. It looks something like:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xmlns:util="http://java.sun.com/jsf/composite/components/util"
xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Reset Test</title>
<link type="text/css" rel="stylesheet" href="/treetable-sscce/css/example.css" />
<h:outputScript library="primefaces" name="jquery/jquery.js"/>
</h:head>
<div class="box">
<h2>Box</h2>
<h:panelGroup id="mypanel">
Headline: <h:outputText value="#{resetBean.headline}" />
<br/>
Message : <h:outputText value="#{resetBean.message}" />
<br/>
</h:panelGroup>
</div>
<div class="box">
<h2>Form</h2>
<h:form id="myform" acceptcharset="utf-8">
<p:growl id="growl" showDetail="true" sticky="false" severity="info, warn" />
<!-- register custom validate event -->
<f:event listener="#{resetBean.validateForm}" type="postValidate" />
<p:remoteCommand name="resetByEscape" action="#{resetBean.resetAction}"
immediate="true" update=":myform :mypanel" />
<h:outputLabel for="headline">Meldungsüberschrift</h:outputLabel>
<h:inputText id="headline" value="#{resetBean.headline}" />
<br/>
<h:outputLabel for="message">Meldungsüberschrift</h:outputLabel>
<h:inputTextarea id="message" value="#{resetBean.message}" />
<br/>
<h:commandButton action="#{resetBean.resetAction}"
value="Reset" immediate="true" onclick="resetForm()"/>
<h:commandButton action="#{resetBean.submitAction}" value="Submit" immediate="false"/>
</h:form>
</div>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var resetForm = function()
{
$("[id$='headline']").val(null)
$("[id$='message']").val(null)
}
var escapePressed = function()
{
resetForm();
resetByEscape();
}
$(document).keyup(function(e) {if (e.keyCode == 27) escapePressed();});
//--><!]]>
</script>
</html>
Here is the bean code:
package de.example.beans;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.validator.ValidatorException;
import org.apache.log4j.Logger;
#ViewScoped
#ManagedBean
public class ResetBean implements Serializable
{
private static final long serialVersionUID = 7282752623428425109L;
private static final Logger log = Logger.getLogger(ResetBean.class);
protected String headline = null;
protected String message = null;
public ResetBean() {
log.error("ResetBean");
}
#PostConstruct
public void postConstruct() {
log.error("postConstruct");
}
#PreDestroy
public void preDestroy() {
log.error("preDestroy");
}
public void resetAction() {
log.error("resetAction");
headline = null;
message = null;
}
public void submitAction() {
log.error("submitAction headline="+headline+" message="+message);
}
public void validateForm(ComponentSystemEvent event) throws ValidatorException {
log.error("validateForm");
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Both the h:command button and the p:remoteCommand execute the same action in the same fashion. The difference is, that the h:command button responds to a mouse click, while the ESC key triggers the p:remoteCommand via javascript on using ESC key.
The problem is, that the route via p:remoteCommand seems to destroy the backing bean somehow (the bean is #ViewScoped). The #PreDestroy annotated method is never called, however: the next action on the page after using the p:remoteCommand forces the component to be created from scratch! Default constructor and #PostConstruct are called. Naturally some important parameters are missing now and the whole view gets shot to hell.
Any idea what is happening? Why the difference between p:remoteCommmand and h:commandButton in this instance? Any chance of working around the problem?
I could reproduce the problem. In my case and maybe the same case here (question provides only 'sample' code, not real one) it was caused by nested forms template->page.
If you have a ui:composition template or something similar to that, at the end of the generated HTML on client side it may creates nested forms like this:
<h:form>
...
<h:form>
...
</h:form>
...
</h:form>
which is invalid HTML code.
Remove unnecessary forms or reorganize code and test again. It should not call #postConstruct method when p:remoteCommand is called through JavaScript

Resources