JSF + Primefaces: Problem with "rendered" components with ajax - java

EDIT
Cant seem to get rendered to work correctly with update attributes. Here is my codes
<ui:define name="left">
<h:form>
<p:commandLink value="Hey"
actionListener="#{bean.setRenderComment}"
update="comment"/>
</h:form>
</ui:define>
<ui:define name="right">
<h:panelGroup id="comment" rendered="#{bean.renderComment}">
hello
</h:panelGroup>
</ui:define>
renderComment is a boolean attributes inside bean. setRenderComment basically toggle the state of renderComment like this
this.renderComment = !this.renderComment;
Right, every time I click on the link Hey, I need to refresh to either render hello on or off. How can I fix it, so that I dont need to refresh

I am not using Primefaces but Richfaces on my projects. So I am not really aware on how the refresh process is done by Primefaces. However, I have an idea that can be tested easily.
Your problem may be due to the fact that the component to re-render (i.e. update) is not found on the HTML page. If your rendered attribute is equals to false, then the <SPAN> with comment id is not integrated in the HTML page generated. Thus, when the Ajax request is received on the client side, the Ajax engine is not able to refresh this <SPAN> as it is not found.
So what you can do is to always render your panelGroup and move your rendered attribute to a nested <h:outputText> that contains the Hello message.
Here is what I am suggesting:
<h:panelGroup id="comment">
<h:outputText value="Hello" rendered="#{bean.renderComment}"/>
</h:panelGroup>
This way, the panelGroup will always be refreshed after the Ajax call, and it will contain the Hello message or not, regarding the value of the renderComment attribute of your bean.

Since the component with the ID comment isn't one of the form's (an UINamingContainer component) children, you need to prefix the ID with : to instruct JSF to scan from the "upper level".
This should do:
<p:commandLink value="Hey"
actionListener="#{bean.setRenderComment}"
update=":comment" />

Related

<f:ajax> tag fails to render multiple components [duplicate]

The following code is inspired from PrimeFaces DataGrid + DataTable Tutorials and put into a <p:tab> of a <p:tabView> residing in a <p:layoutUnit> of a <p:layout>. Here is the inner part of the code (starting from p:tab component); the outer part is trivial.
<p:tabView id="tabs">
<p:tab id="search" title="Search">
<h:form id="insTable">
<p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
<p:column>
<p:commandLink id="select" update="insTable:display" oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
</p:column>
</p:dataTable>
<p:dialog id="dlg" modal="true" widgetVar="dlg">
<h:panelGrid id="display">
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
</h:form>
</p:tab>
</p:tabView>
When I click the <p:commandLink>, the code stops working and gives the message:
Cannot find component with expression "insTable:display" referenced from "tabs:insTable:select".
When I try the same using <f:ajax>, then it fails with a different message basically telling the same:
<f:ajax> contains an unknown id "insTable:display" cannot locate it in the context of the component "tabs:insTable:select"
When it happens during another Ajax postback and the JSF project stage is set to Development, then it fails with a JavaScript alert with the message:
malformedXML: During update: insTable:display not found
How is this caused and how can I solve it?
Look in HTML output for actual client ID
You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.
Note: if it happens to contain iteration index like :0:, :1:, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.
Memorize NamingContainer components and always give them a fixed ID
If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer parent, then just reference its own ID.
<h:form id="form">
<p:commandLink update="result"> <!-- OK! -->
<h:panelGroup id="result" />
</h:form>
If it's not inside the same NamingContainer, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer separator character, which is by default :.
<h:form id="form">
<p:commandLink update="result"> <!-- FAIL! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
<p:commandLink update=":result"> <!-- OK! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
<p:commandLink update=":result"> <!-- FAIL! -->
</h:form>
<h:form id="otherform">
<h:panelGroup id="result" />
</h:form>
<h:form id="form">
<p:commandLink update=":otherform:result"> <!-- OK! -->
</h:form>
<h:form id="otherform">
<h:panelGroup id="result" />
</h:form>
NamingContainer components are for example <h:form>, <h:dataTable>, <p:tabView>, <cc:implementation> (thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler may be helpful in this during development.
If you know to find the javadoc of the UIComponent in question, then you can also just check in there whether it implements the NamingContainer interface or not. For example, the HtmlForm (the UIComponent behind <h:form> tag) shows it implements NamingContainer, but the HtmlPanelGroup (the UIComponent behind <h:panelGroup> tag) does not show it, so it does not implement NamingContainer. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.
Solving your problem
So in your case of:
<p:tabView id="tabs"><!-- This is a NamingContainer -->
<p:tab id="search"><!-- This is NOT a NamingContainer -->
<h:form id="insTable"><!-- This is a NamingContainer -->
<p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
<h:panelGrid id="display">
The generated HTML output of <h:panelGrid id="display"> looks like this:
<table id="tabs:insTable:display">
You need to take exactly that id as client ID and then prefix with : for usage in update:
<p:commandLink update=":tabs:insTable:display">
Referencing outside include/tagfile/composite
If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer() like so:
<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">
Or, if this command link is inside a composite component and the target is outside it:
<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">
Or, if both the command link and target are inside same composite component:
<p:commandLink update=":#{cc.clientId}:display">
See also Get id of parent naming container in template for in render / update attribute
How does it work under the covers
This all is specified as "search expression" in the UIComponent#findComponent() javadoc:
A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:
Identify the UIComponent that will be the base for searching, by stopping as soon as one of the following conditions is met:
If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root UIComponent of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
Otherwise, if this UIComponent is a NamingContainer it will serve as the basis.
Otherwise, search up the parents of this component. If a NamingContainer is encountered, it will be the base.
Otherwise (if no NamingContainer is encountered) the root UIComponent will be the base.
The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base UIComponent (except that if a descendant NamingContainer is found, its own facets and children are not searched).
If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a NamingContainer by the rules in the previous bullet point. Then, the findComponent() method of this NamingContainer will be called, passing the remainder of the search expression.
Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".
"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree.
Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :) are not only searched in the context of the closest parent NamingContainer, but also in all other NamingContainer components in the same view (which is a relatively expensive job by the way).
Never use prependId="false"
If this all still doesn't work, then verify if you aren't using <h:form prependId="false">. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.
Referencing specific iteration round of iterating components
It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat> and <h:dataTable> like so:
<h:form id="form">
<ui:repeat id="list" value="#{['one','two','three']}" var="item">
<h:outputText id="item" value="#{item}" /><br/>
</ui:repeat>
<h:commandButton value="Update second item">
<f:ajax render=":form:list:1:item" />
</h:commandButton>
</h:form>
However, since Mojarra 2.2.5 the <f:ajax> started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).
This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>.
When using PrimeFaces, consider Search Expressions or Selectors
PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:
#this: current component
#form: parent UIForm
#all: entire document
#none: nothing
PrimeFaces has enhanced this with new keywords and composite expression support:
#parent: parent component
#namingcontainer: parent UINamingContainer
#widgetVar(name): component as identified by given widgetVar
You can also mix those keywords in composite expressions such as #form:#parent, #this:#parent:#parent, etc.
PrimeFaces Selectors (PFS) as in #(.someclass) allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="#(.myClass)" work?
first of all: as far as i know placing dialog inside a tabview is a bad practice... you better take it out...
and now to your question:
sorry, took me some time to get what exactly you wanted to implement,
did at my web app myself just now, and it works
as I sayed before place the p:dialog out side the `p:tabView ,
leave the p:dialog as you initially suggested :
<p:dialog modal="true" widgetVar="dlg">
<h:panelGrid id="display">
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
and the p:commandlink should look like this (all i did is to change the update attribute)
<p:commandLink update="display" oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
the same works in my web app, and if it does not work for you , then i guess there is something wrong in your java bean code...
It's because the tab is a naming container aswell... your update should be update="Search:insTable:display" What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"
Please note that from PrimeFaces 10 and up, you are able to use observer and event.
This allows you to update components based on a custom event name, set by the #obs(event) keyword. For example:
<p:commandButton update="#obs(myEvent)"/>
<h:panelGroup>
<p:autoUpdate on="myEvent"/>
</h:panelGroup>
See:
https://www.primefaces.org/showcase/ui/ajax/observer.xhtml
I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.
Remove the update on your component that is not working
Put a temporary component with a bogus update within the component you were trying to update
hit the page, the servlet exception error will tell you the correct client Id you need to reference.
Remove bogus component and put correct clientId in the original update
Here is code example as my words may not describe it best.
<p:tabView id="tabs">
<p:tab id="search" title="Search">
<h:form id="insTable">
<p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
<p:column>
<p:commandLink id="select"
Remove the failing update within this component
oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
</p:column>
</p:dataTable>
<p:dialog id="dlg" modal="true" widgetVar="dlg">
<h:panelGrid id="display">
Add a component within the component of the id you are trying to update using an update that will fail
<p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
</h:form>
</p:tab>
</p:tabView>
Hit this page and view the error.
The error is:
javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from
tabs:insTable: BogusButton
So the correct clientId to use would then be the bold plus the id of the target container (display in this case)
tabs:insTable:display
Try change update="insTable:display" to update="display". I believe you cannot prefix the id with the form ID like that.

How to make a form tag comunicate to another form tag?

I am using JSF 2.2, PrimeFaces and Glassfish and I have this:
<h:form id="formularioAltas">
//more code
<p:commandButton value="Guardar" action="#{altasBean.agregarRefaccion()}" />
</h:form>
<h:form id="myForm" enctype="multipart/form-data" prependId="false" rendered="#{altasBean.estado}">
// more code here
</h:form>
And I need formularioAltas to tell myForm that the value of the boolean property estado has changed. I uderstand it like doing a simple update to myForm when the commandButton is executed but that cant be cause they are in diferent forms. I needed this way cause I have problems uploading files to the server so I decided to use two different forms. I have working this forms but I want to show only myForm when the commandButton is executed.
Any ideas?
<p:commandButton value="Guardar" action="#{altasBean.agregarRefaccion()}" update=":myForm" />
: because you climb the container hierarchy one step up to the container which contains both forms and myForm because that's her name.

JSF - Calling bean method when clicking <a> element

So I have an anchor element, and it's href attribute is set dynamically from the bean. I am using an anchor since it is interacting with fancybox javascript. What I need to have happen is to call a method in the bean when the anchor is clicked so that the href will update again. There is a textbox above that is also bound to bean. What needs to happen is to take the text from the text box, and parse that into a query string for the anchor's href.
I'm trying to figure out the best way to have this happen (if it is possible). Would I be able to use javascript (or Ajax) to call an updateHref() method?
The textbox and anchor element (it's ModelBean.ending that needs to be updated):
<h:inputTextarea value="#{ModelBean.tweet}" class="textarea.hs-input #{ModelBean.tweetClass}" style="width:200px;" >
<f:facet name="label">
Tweet
</f:facet>
</h:inputTextarea>
</td>
</tr>
<tr>
<td>
<h:commandButton value="Analyze Tweet" class="hs-button orange" action="#{ModelBean.tweetAnalysis()}" />
</td>
<td>
<a href="https://app.hubspot.com/social/#{ModelBean.hubID}/publishing/compose_bookmarklet?body=#{ModelBean.ending}" class="hs-button primary fancybox-iframe" data-fancybox-type="iframe" >
Tweet it!
</a>
</td>
</tr>
Here's the bit of java that would need to be called:
ending = URLEncoder.encode(tweet, "UTF-8");
ending = ending.replaceAll("\\+", "%20");
If you think any other part of the code would be useful please let me know! And thanks in advance for any suggestions!
If you use JSF 2.0, f:ajax tag may solve your problem. Here is sample usege of f:ajax tag,
<h:commandLink value="#{..}">
<f:ajax execute="name" render="output" />
</h:commandLink>
<h:inputTextarea id="output" value="#{..}" />
execute=”name” – Indicate the form component with an Id of “name” will be sent to the server for processing. For multiple components, just split it with a space in between, e.g execute=”name anotherId anotherxxId”. In this case, it will submit the text box value.
render=”output” – After the Ajax request, it will refresh the component with an id of “output“. In this case, after the Ajax request is finished, it will refresh the h:inputTextarea component.

Cancellation of Ajax Request in RichFaces

I have issue with canceling Ajax Request. Our application interface is build in RF.
On the progress bar modal there should be cancel button - that interupt current operation,
for example cancel filling controls from database. How to make it?
I tried using reloading page, flags with "if" conditions on getters for controls and also using "bypassUpdates" with no positive effects.
Thanks in advance for your help
XHTML (Button):
<a4j:commandButton id="showData"
value="View" styleClass="hBtn"
disabled="#{events.isButtonsDisabled}"
oncomplete="if (#{facesContext.maximumSeverity==null})
{window.open('/seed/pages/data.jsf','DATA')};"
actionListener="#{events.actionShow}"/>
JAVA: (Button):
public void actionShow(ActionEvent evt) {
//Some logic, getting data from database
}
XHTML (Main Page - showing wait Popup)
<a4j:form>
<a4j:status id="ajaxStat"
onstart="Richfaces.showModalPanel('waitPanel');"
onstop="#{rich:component('waitPanel')}.hide()" />
</a4j:form>
XHTML (Popup):
<rich:modalPanel id="waitPanel" autosized="true" moveable="false"
minWidth="250" styleClass="popup">
<f:facet name="header">
<h:panelGroup>
<h:outputText value="Operation in progress"></h:outputText>
</h:panelGroup>
</f:facet>
<f:facet name="controls">
<h:panelGroup>
<h:graphicImage value="../images/icons/action_close.gif" styleClass="hidelink" id="hidelink"/>
<rich:componentControl for="waitPanel" attachTo="hidelink" operation="hide" event="onclick"/>
</h:panelGroup>
</f:facet>
<a4j:form id="msgFrm" ajaxSubmit="true">
<h:outputText value="Please wait..."/>
<h:graphicImage styleClass="progressBar" value="../images/indicatorbar.gif"/>
<a4j:commandButton value="Cancel" type="button"
onclick="#{rich:component('waitPanel')}.hide()"
action="#{main.cancelAction}"
bypassUpdates="true"/>
</a4j:form>
</rich:modalPanel>
JAVA (Popup):
public void cancelAction(){
//there was setter for true/false flag for actionShow() here, now there is nothing here (it was not working)
}
Reloading the page stops all current ajax requests. It does not stop the java backing beans from finishing the requests but I assume that is not the question.
c:if and the ajax render do not mix very well. Possibly you could use 'rendered' to disable updating the controls? Then split the control in two parts. One is shown with valid data and for example bright blue. The other is rendered without any data and has a grey picture.
But... I'm not sure I understand the question correctly.
Edit 23-1-2012: Seeing the code I would say that the cancelAction must set a flag that then finishes the action running inside actionShow(). Then the ajax request finishes and the popup is closed. Can't see why this won't work.

javascript popup does not get managed value

I do not understand that when I press save in the form below I save the current contents of the inputTextArea, but when I want to look at a preview of the contents of inputTextArea I see the contents of the last saved mail template. What I should see is of course the current value of the textArea (after it is converted). Why does it not show the updated value of customMailTemplate?
<h:form id="gameMailForm" prependId="false" rendered="#{customizeGameMailBean.renderGameMailPanel}">
<h:panelGrid columns="3">
<h:inputTextarea
styleClass="gameMailTextArea, textArea"
id="gameMailTextArea"
value="#{customizeGameMailBean.customMailTemplate}"
converter="gameMailTemplateConverter"
style="height: 120px; width: 300px; font-size: 11px;">
<f:validator validatorId="gameMailValidator"/>
</h:inputTextarea>
<p:commandButton value="Save"
action="#{customizeGameMailBean.saveMailTemplate}"
ajax="false"/>
<p:commandButton value="Preview"
ajax="true"
action="#{customizeGameMailBean.doNothing}"
oncomplete="javascript: window.open('gameMailPreview.jsp','Game Email','width=300,height=300')"
immediate="true"/>
</h:panelGrid>
</h:form>
gameMailPreview.jsp:
<%#page import="wmc.web.controller.CustomizeGameMailBean"%>
<%#page import="javax.faces.context.FacesContext"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% CustomizeGameMailBean gameMailBean = (CustomizeGameMailBean) request.getSession().getAttribute("customizeGameMailBean");%>
<%=gameMailBean.getCustomMailPreview()%>
Is something maybe wrong about the timing?
By the way game doNothing is really doing nothing. It is an empty void method.
The problem is that the second command button has its immediate attribute set to true. This will cause the action method to be invoked in the apply request values phase, and thereafter skip immediately to render response.
In effect, no model values will be updated, thus you keep having the previous values in the model. Confusingly maybe, but the component will retain the value you just entered. I just didn't transfer to the model. For more information about this look up what the immediate attribute means in JSF and especially what it does when applied to a command button.
(I also would like to remark that using the session scope to communicate values to a popup is asking for trouble. This opens the door to all kinds of race conditions when the user has the page opened in multiple tabs or windows. If possible, you might be better off using Java EE 6's conversation scope.)

Categories