Please have a look at the following form. In particular, take note of the ajax and graphicImage elements. The ajax element is embedded in a selectOneMenu. When the menu selection is changed the image is correspondingly updated. The update will sometimes cause a "blink" (old image disappears, form resizes (shrinks), new image appears, form is back to original size). I am guessing that the not blink (blink) results from the speed (or lack thereof) with which the new image is fetched from the url (a server elsewhere on the web). Short of caching all the images locally, is there a way to address this? Cause old image to remain in place until the new image is ready? At least prevent the form from resizing?
<h:form rendered="#{orderController.addingNew}" styleClass="demo">
<fieldset>
<legend>New Order</legend>
<h:panelGrid columns="2">
<h:outputText value="Patient"></h:outputText>
<h:selectOneMenu validatorMessage="required" value="#{orderController.patientId}" onchange="submit()">
<f:selectItems value="#{orderController.patients}" />
</h:selectOneMenu>
<h:outputText value="Product"></h:outputText>
<h:selectOneMenu value="#{orderController.productId}">
<f:selectItems value="#{orderController.products}" var="product" itemValue="#{product.id}" itemLabel="#{product.name}" />
<f:ajax render="productImage" listener="#{orderController.productSelectionChanged}"/>
</h:selectOneMenu>
<h:graphicImage url="#{orderController.productImageUrl}" id="productImage"/>
</h:panelGrid>
<h:panelGroup>
<h:commandButton value="Save" action="#{orderController.save}" accesskey="s" styleClass="demo"/>
<h:commandButton value="Cancel" action="#{orderController.cancel}" accesskey="c" immediate="true" styleClass="demo"/>
</h:panelGroup>
</fieldset>
<h:outputText value=" " />
</h:form>
You could bind an onevent attribute to your ajax tag:
<f:ajax render="productImage" listener="#{orderController.productSelectionChanged}"
onevent="ajaxEventListener"/>
Then, you get notified whenever some phase of the ajax process happens. You might be interested in implementing something like this with jQuery:
function ajaxEventListener(data) {
var status = data.status; // Can be "begin", "complete" or "success".
var source = data.source; // The parent HTML DOM element.
//Give your form an id in order to access the image in JS
var $image = $(document.getElementById("yourFormId:productImage")); //Grab your image
switch (status) {
case "begin": // Before the ajax request is sent.
// Fade out your image
$image.fadeOut( "slow" );
break;
case "success": // After update of HTML DOM based on ajax response.
// You've got the url properly updated, start fading in the image again
$image.fadeIn( "slow" );
break;
}
}
In order to improve loading times, you should read some papers about how to cache resources in the web browser. That's not JSF specific, though, it's something you could do with a web filter.
See also:
Execute JavaScript before and after the f:ajax listener is invoked
How to select JSF components using jQuery?
http://api.jquery.com/fadeout/
http://api.jquery.com/fadeIn/
Related
I'm working on old system which has a lot of code written back in the days using jsf1.2. Now I have the task to dynamically add/remove group of input elements via ajax on button click.
I was guided by this post on how to add input fields dynamically, made little tweaks to support ajax and made prove of concept which works perfectly fine.
Now the problem occurs when instead of <h:inputText> .. </h:inputText> or other form fields I use our own custom tag component.
When using the custom tag I get the page displayed on page load, but if I try to remove an item, for the first component in the list I get the error java.io.IOException: Cannot add the same component twice: editform:parentTable:0:fieldsTable:0:HTML_TITLE_INPUT_en
I believe the problems is due to the component already being in the component tree when the custom tag tries to add it again on postback, but still I don't know how to fix the issue.
Note 1: I have to use our custom tag since it has a lot of logic inside and it is used to display every type of form field (inputText, textarea, checkboxes etc)
xhtml code:
<h:dataTable id="parentTable" value="#{bean.groups}" var="group" styleClass="parentTableStyleClass">
<h:column>
<h:dataTable id="fieldsTable" value="#{group.fields}" var="field">
<h:column>
<h:outputLabel value="#{field.label}" styleClass="col-sm-2 control-label" />
</h:column>
<h:column>
<customTag:propertyValue
name="#{field.name}"
operation="edit"
instance="#{bean.instance}"
styleClass="form-control"
inputWrapperClass="col-sm-5"/>
</h:column>
</h:dataTable>
</h:column>
<h:column>
<p:commandButton value="Remove Group"
styleClass="btn btn-secondary btn-sm"
action="#{bean.removeGroup(group)}"
process="#(.parentTableStyleClass)"
update="#(.parentTableStyleClass)" />
</h:column>
</h:dataTable>
The tag class:
public void encodeBegin(FacesContext context) throws IOException {
getChildren().clear();
...
// bunch of logic
...
HtmlPanelGroup wrapper = new HtmlPanelGroup();
HtmlInputText inputText = new HtmlInputText();
...
// bunch of code creating input text field
...
wrapper.setStyleClass(getInputWrapperClass() + " input-group");
wrapper.getChildren().add(inputText);
getChildren().add(wrapper);
}
So, i have code:
<h:form id="newMessages" rendered="#{not empty welcome.letters and urlBean.welcome}" styleClass="infoNotes">
**some not important code here**
<ui:repeat id="data" value="#{welcome.letters}" var="letter" varStatus="status">
<h:panelGroup rendered="#{status.index lt 3}">
<div>
<h:commandLink styleClass="noticeClose" rendered="#{letter.content.IMPORTANCE ne '2'}">
<f:ajax listener="#{welcome.onMessageNoticeClose(letter)}" event="click" render="#{cc.clientId}:newMessages newLettersCount"/>
</h:commandLink>
</div>
</h:panelGroup>
**some not important code here**
</ui:repeat>
**some not important code here**
</h:form>
method used when we "click" on close button
public void onMessageNoticeClose(Document letter) {
try (RequestContext ctx = RequestContextFactory.create()) {
DocumentEngine.getInstance().markAsRead(letter, true, ctx);
}
Utils.getRolesBean().recalcMessageCount();
loadMessages();
}
and couple of methods that recalc message count and load new messages. So if we have new unread messages we show them on main page (3 of them). So, problem is when we click close button 'styleClass="noticeClose"', we mark letter as read and didnt show it on main page. But with that code have bug, if in list we have only one message and button close clicked, this letter mark as "read" and message count recalc correct, but it still showed on main page, and don`t rendered only after page will be reloaded. So, solution is if we h:form surround with h:panelgroup like:
<h:panelGroup id="newMessages">
<h:form rendered="#{not empty welcome.letters and urlBean.welcome}" styleClass="infoNotes">
but i don`t understand how it work... Can anyone help me understand this or just explain. Thank you.
This question already has an answer here:
Ajax update/render does not work on a component which has rendered attribute
(1 answer)
Closed 7 years ago.
I want to update two components after ajax action but don't know how to do this (if it is even possible).
I have three pages:
<h:form id="loginForm">
<p:panelGrid columns="2" >
<h:outputText value="Login: "/>
<p:inputText value="#{bean.person.username}" requiredMessage="*" />
<h:outputText value="Hasło: "/>
<p:password value="#{bean.person.password}" requiredMessage="*"/>
<p:commandButton value="Login" action="#{bean.validatePerson}" update="loginConfirmationPage"/>
</p:panelGrid>
</h:form>
Menu page is similar to this above with menu items with rendered atribute (fe. show logout button when user is logged in) and loginConfirmationPage on which i want to show username.
I need to update both of these pm:pages to get logout button on menu page and also display username on confirmation page.
How can I do this? For now i can only update one page. I tried to type statement similar to these:
<p:commandButton value="Login" action="#{bean.validatePerson}" update="loginConfirmationPage,menuPage"/>
or
<p:commandButton value="Login" action="#{bean.validatePerson}" update="loginConfirmationPage;menuPage"/>
Both not working. How can i do this?
var name = "";
$.post("Path/To/Server/File", {'serverFileVariableName' : clientElementID},
//data is what the server file will return
function(data){
//In this case, the data is the username.
name = data;
//invoke the show method to display
logOut.show();
}
);
//done
I lost whole day on this issue and got nothing. I know that the question was asked but it was never answered. BalusC said that this issue is fixed in JSF 2.2.5 but either it is not or i do something wrong.
I use h:inputFile tag with ajax to render choosen image in preview div after chosing one from disk. However it's rendered only once and i have to reload page to see next chosen image. It causes more errors. For example when I use SUBMIT button to send chosen image to DB, ajax from commandLink is not executed (image is saved and rendered after page after refresh).
It looks to me like ajax is broken after chosing an image from disk and followed ajax actions are not executed, even they dont belong to h:inputfile.
This is my JSF form (one of its versions because i tried so many tricks)
<h:panelGroup class="photo-update" rendered="#{profileBean.page eq 'photo'}">
Dodaj lub zmień swoje zdjęcie profilowe[...]
<h:form enctype="multipart/form-data">
<h:panelGroup id="form-content">
<h:panelGroup id="current-image" class="current-image">
<p:graphicImage value="#{imageBean.getUserImage()}"/>
</h:panelGroup>
<h:panelGroup id="accept-container-ajax">
<h:panelGroup id="accept-container" class="accept-container"
rendered="true">
<div class="arrow">
<img src="resources/images/arrow.png"/>
<div class="change-text">Zamień na</div>
</div>
<h:panelGroup id="new-image" class="new-image">
<p:graphicImage value="#{profileBean.getConvertedImage()}"/>
</h:panelGroup>
<h:commandLink class="btn btn-default ok-button" value="zatwierdź"
action="#{profileBean.uploadPhoto}">
<f:ajax render="accept-container-ajax current-image"
execute="#form"/>
</h:commandLink>
</h:panelGroup>
</h:panelGroup>
<div class="btn btn-default change-image-container">
Zmień zdjęcie
<h:inputFile immediate="true" id="change-image"
class="change-image" value="#{profileBean.image}">
<f:ajax render="accept-container-ajax" execute="#form"/>
</h:inputFile>
</div>
</h:panelGroup>
</h:form>
</h:panelGroup>
This is fragment of the bean:
public StreamedContent getConvertedImage() throws IOException {
return userBo.convertPartToStream(image);
}
public void uploadPhoto() {
this.renderChangeContainer = false;
if (userBo.addImage(this)) {
FacesContext.getCurrentInstance().addMessage(
null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "...", null));
} else {
FacesContext.getCurrentInstance().addMessage(
null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "...", null));
}
}
injected BO methods are OK.
Please give me a clue what is going on.
EDIT:
I also see ugly iframe with some response content i guess.
I would like to customize the presentation of faces messages.
For this,
<h:inputText id="name" required="true" />
when validation is failed, then it will be shown in a
<h:message for="name" />
However, I would like to customize the presentation call JS as follows:
<div class="notification"></div>
function showNotification(msg){
$(".notification").html(msg);
$(".notification").fadeIn(1000, function(){
timeout = setTimeout(function(){
$(".notification").fadeOut(1000);
}, 5000);
});
}
How can I achieve this?
You can use FacesContext#getMessageList() to get the messages in the view, if necessary the ones for a specific client ID. You can iterate over them in a ui:repeat. Each item is a FacesMessage which has several getters. You can display any HTML in the message unescaped by using <h:outputText escape="false">.
So, in a nutshell:
<ui:repeat value="#{facesContext.messageList('form:name')}" var="message">
<div><h:outputText value="#{message.summary}" escape="false" /></div>
</ui:repeat>
(in the above example, I assume that your form has id="form")
Or, if that HTML help link is actually not part of the message, then so:
<ui:repeat value="#{facesContext.messageList('form:name')}" var="message">
<div>#{message.summary} help</div>
</ui:repeat>