JSF: invoking a javascript after a successful creation - jsf

my current code.
<h:form>
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:panelGrid columns="2">
// some form input stuff here..
</h:panelGrid>
<h:commandButton class="register-btn" action="#{accountController.create}" value="#{bundle.Register}">
<f:ajax event="action" execute="#form" render="messagePanel"/>
</h:commandButton>
</h:form>
messagePanel is where the validation errors displays.
create() method
public String create() {
try {
getFacadeUser().create(currentUser);
FacesContext.getCurrentInstance().getExternalContext().redirect("/index.xhtml");
return null;
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
is it possible to invoke a javascript after a successful creation? currently my create form is a pop up modal, what i want is to just hide the modal after a successful creation rather than redirecting to a page.
i'm using JSF 2.1

With standard JSF (read: no component libraries or utility libraries such as PrimeFaces or OmniFaces which have ways to make this easier), your best bet is to conditionally render <script> element.
<h:panelGroup id="script">
<h:outputScript rendered="#{not empty accountController.currentUser.id}">
alert('User successfully created!');
</h:outputScript>
</h:panelGroup>
Reference it in <f:ajax ... render="script">.

You can create a component binding for your dialog in your managed bean and hide the dialog from your function using that binding. I think the type of object which represents your component binding is framework specific (although all of them probably extend UIComponent), so you need to specify what JSF implementation you are using for a full solution. I implemented this very use case in ADF for example.
This is an example from ADF:
<af:popup id="sample" binding="#{viewScope.myBean.myPopup}">
and in the managed bean:
RichPopup myPopup;
...
public void onSave() {
//save user
myPopup.hide();
}

Related

PostConstruct methos called again with richfaces 4.2 , works fine with myfaces

I am seeing different behaviors of and in a page containing multiple forms.
Here is my backing bean:
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class MultiFormBean
{
String inputText1 = "";
String inputText2 = "";
#PostConstruct
public void initializeBean(){
System.out.println("PostConstruct Called ------------------");
}
public String getInputText1()
{
return inputText1;
}
public void setInputText1(String inputText1)
{
this.inputText1 = inputText1;
}
public String getInputText2()
{
return inputText2;
}
public void setInputText2(String inputText2)
{
this.inputText2 = inputText2;
}
public void doSubmit1() {
inputText2 = inputText1;
}
public void doSubmit2() {
inputText1 = inputText2;
}
}
When i use the following xhtml , clicking Submit1 and Submit2 any number of times won't call #PostConstruct more than once:
<h:body>
<h:form id="firstForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget1"/>
<h:inputText id="first_input" value="#{multiFormBean.inputText1}"/>
<h:commandButton id="click1" action="#{multiFormBean.doSubmit1}" value="submit1" type="submit"
onclick="javascript:jsf.ajax.request(this, event, {execute:'firstForm', render:'renderTarget1 secondForm'}); return false;">
</h:commandButton>
</h:form>
<h:form id="secondForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget2"/>
<h:inputText id="second_input" value="#{multiFormBean.inputText2}"/>
<h:commandButton id="click2" action="#{multiFormBean.doSubmit2}" value="submit2" type="submit"
onclick="javascript:jsf.ajax.request(this, event, {execute:'secondForm', render:'renderTarget2 firstForm'}); return false;">
</h:commandButton>
</h:form>
</h:body>
But the following xhtml would call #PostConstruct more than once:
<h:body>
<h:form id="firstForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget1"/>
<h:inputText id="first_input" value="#{multiFormBean.inputText1}"/>
<a4j:commandButton id="click1" action="#{multiFormBean.doSubmit1}" value="submit1" type="submit" execute="#form" render="renderTarget1,secondForm"/>
</h:form>
<h:form id="secondForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget2"/>
<h:inputText id="second_input" value="#{multiFormBean.inputText2}"/>
<a4j:commandButton id="click2" action="#{multiFormBean.doSubmit2}" value="submit2" type="submit" execute="#form" render="renderTarget2,firstForm"/>
</h:form>
</h:body>
Please can anyone help me use the <a4j:commandButton> instead of <h:commandButton>
Also i see that i cannot call the method doSubmit2() with a4j commandButton
I think that problem here is in bug inside JSF2 and Richfaces4. From 4 version Richfaces started using JSF embedded ajax capabilities. And There is a bug with using multiple forms on page with ajax requests. The problem there that richfaces renders special hidden input with the id of currently rendered view state. This id is changed when new view is rendered. And it is also submitted with every request to show that it belongs to some specific view. So when you have multiple forms on the same page after first ajax request the view state is getting the wrong place and it can be not submitted again second time. Sometimes behavior looks like very very wierd with no logical description.
PostConstruct is called twice because server thinks that two requests belong to different views(view state is not sumbitted) and as far as bean is view scoped it is created twice. After clicking aroung ajax can completelly stop working with this because server woukd not recognize the view(probably what you see when you can not click second submit button).
In the first place I recommend you to use latest available version of JSF and Richfaces. This bug (and many more) may be already fixed there.

h:inputText not working with a4j:commandLink

myBean is in request scope.
<h:form id="indexFormID">
<a4j:outputPanel ajaxRendered="true" layout="block">
<h:inputText id="inputForHD" value="#{myBean.inputParam}"></h:inputText>
<a4j:commandLink value="Submit" action="#{myBean.myMethod}" reRender="renderSuccess" process="indexFormID:inputForHD"></a4j:commandLink>
</a4j:outputPanel>
<h:panelGroup id="renderSuccess">
<h:panelGroup rendered="#{myBean.someBoolean}">
//Some other JSF components go here
</h:panelGroup>
</h:panelGroup>
</h:form>
MyBean class definition:
private String inputParam;
//Getters and setters are there
public String myMethod()
{
log.debug("~ Value of inputParam" +this.getInputParam()); //This is printing null value for inputParam
//when commandLink is clicked
return null;
}
Why my inputParam is not getting set with the input parameters?
Ok I found few issues with your approach:
<h:inputText id="inputForHD" value="#{myBean.inputParam}"></h:inputText>
You are already mapping the inputParam attribute with this bean, why have a new Id "inputForHD"
Use the inputParam itself, if you want to use inputForHD, you can pick the same from request Parameter map like.
String inputForHD = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("indexFormID:inputForHD");
Also as I mentioned previously wrap the output panel inside the and a4j panel e.g.
<h:panelGroup id="renderSuccess">
<h:panelGroup rendered="#{helloWorld.someBoolean}">
//Some other JSF components go here
<h:inputText id="inputForHDasdasd" value="#{helloWorld.inputParam}"></h:inputText>
</h:panelGroup>
</h:panelGroup>
This is working fine, let know if any issues.

JSF 2.0, messages not displayed inside a dataTable

I have a form with a dataTable which has various columns having links and outputTexts. There is one input field which is evaluated through an ajax request . A custom validator makes sure that only integers are added to the field. The form is below.
<form>
<h:dataTable var="item" value="#{listItems.model}" id="adminlistItems">
//other columns having commandLinks and outputTexts
<h:column>
<f:facet name="header" >
<h:outputText value="Quantity"/>
</f:facet>
<f:ajax listener="#{listItems.AddQuantityAction}">
<div style="padding:5px;float:left">
<h:inputText label="changeQuantity" id="addquantity" value="#{item.additionalQuantity}" maxlength="4" size="3">
<f:validator validatorId="integerValidator"/>
</h:inputText>
<h:outputText value=" "/>
<h:commandButton value="AddQuantity" />
<h:message for="addquantity"/>
</div>
</f:ajax>
</h:column>
</h:dataTable>
</h:form>
The code for the bean is :
#ViewScoped
#ManagedBean
public class ListItems implements Serializable {
//...
public String AddQuantityAction(){
//...
boolean result = //some action
FacesContext context=FacesContext.getCurrentInstance();
UIComponent component=UIComponent.getCurrentComponent(context);
String clientID=component.getClientId(context);
if (result) {
FacesMessage message = new FacesMessage("Quantity added successfully");
FacesContext.getCurrentInstance().addMessage(clientID, message);
} else {
FacesMessage message = new FacesMessage("Quantity not added.Processing error");
FacesContext.getCurrentInstance().addMessage(clientID, message);
}
return "adminListItems";
}
}
The custom validator throws a validator exception which is not displayed. And the listener also has code for messages which too are not displayed. I have read several similar questions and this sounds a common question too. But even if i am missing something obvious,i am in need of a third eye to see what i dont.
The execute and render of <f:ajax> defaults to #this. So only the currently active component will be processed and refreshed. When you press the button, this won't send the input value nor refresh the message component.
Fix it accordingly:
<f:ajax execute="addquantity" render="addquantity_message" listener="#{listItems.AddQuantityAction}">
...
<h:message id="addquantity_message" for="addquantity"/>
...
</f:ajax>
By the way, why don't you just use the builtin javax.faces.Integer converter instead of that validator?
<h:inputText ... converter="javax.faces.Integer">
Further, the return value of ajax listener methods should be void. It's totally ignored in any way. Also, method names should start with lowercase. See also Java naming conventions.
Update as per the comment, that didn't seem to work out well with regard to validation. The listener is invoked 2 times because essentially 2 ajax requests are been sent, one for the input and one for the command. I suggest to move the listener method to the <h:commandButton action>.
<f:ajax execute="addquantity" render="addquantity_message">
...
<h:commandButton action="#{listItems.AddQuantityAction}" />
<h:message id="addquantity_message" for="addquantity"/>
</f:ajax>
You'll only fix the obtained client ID to be the input ID, not the button ID.

Why is the getter called so many times by the rendered attribute?

Related to a previous example, i tried to monitor my get/set methods on the server (when they are called, and how often). So, my actual been look such :
#ManagedBean(name="selector")
#RequestScoped
public class Selector {
#ManagedProperty(value="#{param.profilePage}")
private String profilePage;
public String getProfilePage() {
if(profilePage==null || profilePage.trim().isEmpty()) {
this.profilePage="main";
}
System.out.println("GET "+profilePage);
return profilePage;
}
public void setProfilePage(String profilePage) {
this.profilePage=profilePage;
System.out.println("SET "+profilePage);
}
}
and the only page who can call this method (it only calls the get method on rendered) is :
<!DOCTYPE html>
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:panelGroup layout="block" id="profileContent">
<h:panelGroup rendered="#{selector.profilePage=='main'}">
// nothing at the moment
</h:panelGroup>
</h:panelGroup>
</ui:composition>
my stupor when i see the server log, and i see :
SET null
GET main
GET main
GET main
GET main
GET main
GET main
GET main
What? It call seven times the getProfilePage() method? (and also 1 time setProfilePage())
I would like to know why this behaviour :)
Thanks
ADDED AN EXAMPLE
Bean
#ManagedBean(name="selector")
#RequestScoped
public class Selector {
#ManagedProperty(value="#{param.profilePage}")
private String profilePage;
#PostConstruct
public void init() {
if(profilePage==null || profilePage.trim().isEmpty()) {
this.profilePage="main";
}
}
public String getProfilePage() { return profilePage; }
public void setProfilePage(String profilePage) { this.profilePage=profilePage; }
}
profile.xhtml
<h:panelGroup layout="block" id="profileContent">
<h:panelGroup layout="block" styleClass="content_title">
Profilo Utente
</h:panelGroup>
<h:panelGroup rendered="#{selector.profilePage=='main'}">
<ui:include src="/profile/profile_main.xhtml" />
</h:panelGroup>
<h:panelGroup rendered="#{selector.profilePage=='edit'}">
<ui:include src="/profile/profile_edit.xhtml" />
</h:panelGroup>
</h:panelGroup>
// profile_main.xhtml
<h:form id="formProfileMain" prependId="false">
<h:panelGroup layout="block" styleClass="content_span">
<h:outputScript name="jsf.js" library="javax.faces" target="head" />
<h:panelGroup layout="block" styleClass="profilo_3">
<h:commandButton value="EDIT">
<f:setPropertyActionListener target="#{selector.profilePage}" value="edit" />
<f:ajax event="action" render=":profileContent"/>
</h:commandButton>
</h:panelGroup>
</h:panelGroup>
</h:form>
// profile_edit.xhtml
<h:form id="formProfileEdit" prependId="false">
<h:panelGroup layout="block" styleClass="content_span">
<h:outputScript name="jsf.js" library="javax.faces" target="head" />
<h:panelGroup layout="block" styleClass="profilo_3">
<h:commandButton value="Edit">
<f:setPropertyActionListener target="#{selector.profilePage}" value="editProfile" />
<f:ajax event="action" render=":profileContent"/>
</h:commandButton>
<h:commandButton value="Back">
<f:setPropertyActionListener target="#{selector.profilePage}" value="main" />
<f:ajax event="action" render=":profileContent"/>
</h:commandButton>
</h:panelGroup>
</h:panelGroup>
</h:form>
In this example, i call the profile_main (as default); After (for example) I call profile_edit (by clicking on EDIT); After, I return to profile_main by clicking Back. Now, if i want to reload profile_edit (EDIT), i need to click many times on that command button. Why?
EL (Expression Language, those #{} things) won't cache the result of the calls or so. It just accesses the data straight in the bean. This does normally not harm if the getter just returns the data.
The setter call is done by #ManagedProperty. It basically does the following:
selector.setProfilePage(request.getParameter("profilePage"));
The getter calls are all done by rendered="#{selector.profilePage == 'some'}" during the render response phase. When it evaluates false the first time, in UIComponent#encodeAll(), then no more calls will be done. When it evaluates true, then it will be re-evaluated six more times in the following sequence:
UIComponent#encodeBegin() - Locates renderer for the begin of component.
Renderer#encodeBegin() - Renders begin of component.
UIComponent#encodeChildren() - Locates renderer for children of component.
Renderer#encodeChildren() - Renders children of component.
UIComponent#encodeEnd() - Locates renderer for end of component.
Renderer#encodeEnd() - Renders end of component.
The component and its renderer verifies during every step if it is allowed to render. During a form submit, if an input or command component or any of its parents has a rendered attribute, then it will also be evaluated during apply request values phase as part of safeguard against tampered/hacked requests.
True, this look like clumsy and inefficient. It was considered the achilles heal of JSF as per spec issue 941. It's been suggested to remove all those repeated checks and stick to the one done in UIComponent#encodeAll(), or to evaluate isRendered() on a per-phase basis. During EG discussion, it became clear the root of the problem is in EL, not in JSF, and that performance could be greatly improved with CDI. So there was no necessity to solve it from JSF spec side on.
If your concern is that the managed property should be checked only once after its setting if it's null or empty, then consider to move it into a method which is annotated with #PostConstruct. Such a method will be called directly after bean's construction and all dependency injection.
#PostConstruct
public void init() {
if (profilePage == null || profilePage.trim().isEmpty()) {
profilePage = "main";
}
}
See also:
Why JSF calls getters multiple times?
you can use CDI Producers methods.
It will be called many times, but the result of first call is cached in scope of the bean and is efficient for getters that are computing or initializing heavy objects!
See here, for more info.

jsf page evaluation

there's a jsf page with a form:
....
<h:form>
<h:commandLink action="#{userBean.logout}" value="Logout" />
</h:form>
....
<ui:repeat value="#{categoryBean.allCategories}" var="c">
....
The categoryBean.allCategories is a call to EJB which is based on a <f:param> from previous page acquired via #ManagedProperty. So when the user clicks on Logout, the whole page evaluates, but without the param and there's NullPointerException. Is there any possibility how to skip the evaluation?
Make use of the rendered attribute:
<h:panelGroup rendered="#{not empty param.name}">
<ui:repeat value="#{categoryBean.allCategories}" var="c">
...
</ui:repeat>
</h:panelGroup>
Alternatively you can also just do a nullcheck in getAllCategories() method.
if (param != null) {
// Return it.
}
return null;

Resources