How refresh image using javascript - jsf-2

Using primefaces fileupload i am trying to show recently uploaded image in img tag just above the upload compontent but it shows only after i manually press F5 or hit enter on browser i have tried location.reload() and histry.go(0) but image is not loading
<img height="100" src="relativepath/productId"/>
<p:fileUpload oncomplete="history.go(0)" fileUploadListener="#{productController.upload}" mode="advanced"
dragDropSupport="false" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />

do not limit yourself to javascript. an update after ajax, with a timestamp parameter in url will work fine.
this should be the xhtml code:
<h:panelGroup id="panelToUpdate">
<img height="100" src="relativepath/productId?t=#{myManagedBean.currentTimeInMillis}"/>
</h:panelGroup>
<p:fileUpload update="panelToUpdate" fileUploadListener="#{productController.upload}"
mode="advanced" dragDropSupport="false" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
and this should be the method in your managed bean:
public long getCurrentTimeInMillis()
{
return System.currentTimeMillis();
}

The following code loads the image every 1 second... Hope I helped
<div id="wraper">
</div>
<style>
var t=setInterval(runFunction,1000);
function runFunction() {
document.getElementById("p1").innerHTML = '<img height="100" src="relativepath/productId"/>
<p:fileUpload oncomplete="history.go(0)" fileUploadListener="#{productController.upload}" mode="advanced"
dragDropSupport="false" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />'
}
</style>

Related

How to position a p:dialog in Prime Faces after its resizing

I have a Prime Faces p:dialog that has been resized while new components are inserted when opened ('show' state). However its position doesn't change and it's size is increasing from the down left corner until the page bottom.
I need to reposition it every time I render new components dynamically. Is there any JavaScript function I can call to its widget to reposition?
I'm using PrimeFaces 3.5 with Mojarra 2.1.13.
I had a similar situation with a TabView inside a dialog. The TabView content was dynamically loaded.
<p:dialog widgetVar="dialogWidgetVar">
<p:tabView value="#{tabBean.tabs}" var="tabsVar"
onTabShow="PF('dialogWidgetVar').initPosition();" dynamic="true">
<p:tab id="Tab#{tabsVar.id}" title="#{tabsVar.name}">
...
</p:tab>
</p:tabView>
</p:dialog>
As you can see it will call the function initPosition() with every change of a Tab. This function will reposition your dialog. You can use this function in several cases.
http://forum.primefaces.org/viewtopic.php?f=3&t=16893
This is a method that should work in your case :
Bean code :
#ManagedBean
#ViewScoped
public class Bean
{
private boolean visible;
public void setVisible(boolean visible)
{
this.visible = visible;
}
public boolean getVisible()
{
return this.visible;
}
public void onBeforeShowDialog(AjaxBehaviorEvent event)
{
visible = true;
}
public void onBeforeHideDialog(AjaxBehaviorEvent event)
{
visible = false;
}
}
View code :
<h:commandButton value="Show dialog">
<f:ajax listener="#{bean.onBeforeShowDialog}" render="dialog" />
</h:commandButton>
<p:dialog id="dialog" visible="#{bean.visible}">
content
<h:commandButton value="Hide dialog">
<f:ajax listener="#{bean.onBeforeHideDialog}" render="dialog" />
</h:commandButton>
</p:dialog>
A second method should also work is by JavaScript :
To add in <h:head /> :
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<script>
function centerAndShowDialog(dialog)
{
$(dialog).css("top",Math.max(0,(($(window).height() - $(dialog).outerHeight()) / 2) + $(window).scrollTop()) + "px");
$(dialog).css("left",Math.max(0, (($(window).width() - $(dialog).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
dialog.show();
}
</script>
View code :
<p:commandButton id="basic" value="Show Dialog" onclick="centerAndShowDialog(dlg);" type="button" />
<p:dialog id="dialog" header="Dynamic Dialog" widgetVar="dlg" dynamic="true">
Content
</p:dialog>
Note : Since I'm not using PrimeFaces, I've not tested this code so I hope it work well, but the idea is here!

How can I get geocoder address to backing bean?

Using PrimeFaces p:gmap component.
I have a page with a gmap component with a set of markers.
I want to display the street address in the gmapInfoWindow and pass it to the backing bean as well.
When I click on the map marker, I call a javascript function to get the reverse geocoder address.
I can fetch the address and display it in a javascript alert dialog, but I can't get it to fill the backing bean variable or in the info marker.
The variable does get filled, but it does not get updated until the next time I click on the marker.
As a result, the addresses are always one marker click behind.
Does anyone know how I can get the address to update during the current page session?
Thanks.
The backing bean code onMapMarkerSelect just has a System.out.println statement to show the mapAddress variable.
Here is the page code:
<h:form prependId="false" >
<p:gmap id="gmap" center="#{mappingSessionBean.mapCenter}" zoom="#{mappingSessionBean.mapZoom}" type="HYBRID" rendered="true"
style="#{mappingSessionBean.polygonGmapStyle}" onPointClick="handlePointClick(event);"
model="#{mappingSessionBean.mapModel}" fitBounds="#{mappingSessionBean.fitBoundsFlag}"
widgetVar="map" >
<p:ajax id="gmapAjax" event="overlaySelect" immediate="true" onstart="handlePointClick(event);" listener="#{mappingSessionBean.onMapMarkerSelect}" />
<p:gmapInfoWindow id="infoWindow" >
<p:outputPanel >
<h:panelGrid columns="1" >
<h:outputText id="infoWindowTitle" value="#{mappingSessionBean.selectedMarker.title}" />
<h:outputText id="infoWindowAddress" value="#{mappingSessionBean.mapAddress}" rendered="true" />
<p:commandButton value="Zoom In" action="#{mappingSessionBean.selectedViewInfoListener}" update="gmap" />
</h:panelGrid>
</p:outputPanel>
</p:gmapInfoWindow>
</p:gmap>
<h:inputHidden id="address" value="#{mappingSessionBean.mapAddress}" />
</h:form >
<script type="text/javascript" >
function handlePointClick(event) {
if(navigator.geolocation)
{
browserSupportFlag = true;
var latlng = event.latLng;
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if( status == google.maps.GeocoderStatus.OK )
{
alert( results[0].formatted_address );
document.getElementById('address').value = results[0].formatted_address;
document.getElementById('infoWindowAddress').value = results[0].formatted_address;
}
else
{
alert( "Geocoder failed due to: " + status );
}
});
}
else
{
alert( "No Geolocation");
}
}
</script>
Here is a general solution, I guess you can do better if you will find a way to trigger an event on inputHidden without the use of the button
b.t.w : jQuery comes with primefaces so you can use it without any additional includes
instead of
<h:inputHidden id="address" value="#{mappingSessionBean.mapAddress}" />
place
<f:ajax listener="#{mappingSessionBean.myajax}" execute="address">
<h:inputHidden id="address" value="#{mappingSessionBean.mapAddress}" />
<h:commandButton id="addressBtn" style="display:none"/>
</f:ajax>
(you can replace execute="address" with execute="#form")
and in js code replace
document.getElementById('address').value = results[0].formatted_address;
with
jQuery("#address").val(results[0].formatted_address);
jQuery("#addressBtn").click(); // this will trigger the ajax listener
and finally in your bean add the implementation of the ajax listener itself
public void myajax(AjaxBehaviorEvent event) {
System.out.println(getMapAddress());
}

JSF 2.0 with Richface 4.0 not rerendering component

Do you have any idea why this part of code isn't working:
View:
<a4j:commandButton value="#{labels.comments}"
action="#{reservation.displayComments}"
render="dataComments" />
<h:panelGroup id="dataComments" rendered="#{reservation.showComments}" >
...
<h:panelGroup/>
Bean:
public String displayComments(){
showComments = !showComments;
return "";
}
Click on the link simply do nothing.
Try something like this:
<a4j:commandButton value="#{labels.comments}"
action="#{reservation.displayComments}"
render="dataComments" />
<h:panelGroup id="dataComments">
<h:panelGroup id="innerPanel" rendered="#{reservation.showComments}" >
...
<h:panelGroup/>
<h:panelGroup/>
Always show your dataComments element, unless you will have nothing on the page to refresh.

IE Primefaces Enter Key Submit Workaround

I've run into and issue with IE not allowing me to hit the enter key to submit a form. I found a partial solution (http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter) but my dialog window closes. My validations are run and the error messages are displayed. How would I keep my dialog open?
<p:dialog id="sgupdlg" header="#{bundle['signUp.HEADER']}" widgetVar="signUpDlg"
modal="true" styleClass="dialog dialog1" draggable="false"
resizable="false" showEffect="fade" hideEffect="fade" position="top">
<h:form id="signUpFrm" binding="#{signUpDetail.signUpFrm}">
<p:growl id="growl" showDetail="true" showSummary="false" life="3000" errorIcon="/images/Validation-Error.png" infoIcon="/images/Validation-Success.png"/>
<p:inputText value="#{signUpDetailBean.firstName}" name="nameInput" required="true" requiredMessage="First Name is Required"/>
<p:inputText value="#{signUpDetailBean.lastName}" required="true" requiredMessage="Last Name is Required"/>
<p:commandButton styleClass="form-btn2"
value="#{bundle['signUp.button.LABEL']}" actionListener="#{signUpDetail.signUp}" onclick="trackingSignUpOverlaySave()"
oncomplete="handleSignUpRequest(xhr, status, args)" update="growl"/>
<p:commandButton type="reset" styleClass="close" />
</h:form>
</p:dialog>
<script type="text/javascript">
$ = jQuery
$(function(){
$('input').keydown(function(e){
if (e.keyCode == 13) {
$('#signUpFrm').submit();
return false;
}
});
});
</script>
function closeWhenValidationSuccesful(dialog, xhr, status, args) {
if (!args.validationFailed) {
dialog.hide();
}
}
<p:commandButton value="Save" action="doSomething" update=":formName:panelContainingValidatedElements"
oncomplete="closeWhenValidationSuccesful(dialogWidgetVar, xhr, status, args)" />
I use the following to keep a dialog open and display validation errors. You will need to move your inputs into a panelGrid so that it can be target by the update attribute.
A simple tag would solve it.
oncomplete="if (args.validationFailed){} else {Professor.show(),Student.hide();}"
you suppose to apply this on Professor widget var

Struts2 pagination

My Struts2 application needs the pagination functionality applied to some records, but what I need to customize is the "Last 1 - 2 - 3 Next" appearance and also have the ability to use a combo box for the selection of how many records should be visible(10 - 20 - 30 - 40 -50).
I have tried two way to accomplish this goal:
1) use display tag library, but I'm not able to customize the appearance, because is auto-generated by the library, and I don't how implement the combo box for select how many records should be visible
2) create my own code for accomplish this functionality but is a job too long and not enough time due to the expiry.
My question is: exists some Struts2 library for realize this functionality? Or, is possible to customize the display tag library for the page scroll bar and the records combo box?
I can give insight from struts2 code base there is no functionality as described by you provided by struts2 in itself..
Regarding the Display tag i have not used them much but since they are the part of oprn source i am sure we can customize that one more thing regarding the customization of display tag ask question under display tag you will get better answer at at quick pace
I wrote a custom tld just for the purpose as below and then just use it like this:
Usage:
paginate.tag
1}">
<c:set var="showingPage"
value="${param.pageNumber == null ? 1 : param.pageNumber}" />
<c:url value="${postUrl}" var="previousUrl">
<c:param name="pageNumber" value="${showingPage - 1}" />
<c:param name="perPage" value="${perPage}" />
</c:url>
<c:url value="${postUrl}" var="nextUrl">
<c:param name="pageNumber" value="${showingPage +1}" />
<c:param name="perPage" value="${perPage}" />
</c:url>
<div class="pagination" />
<c:if test="${showingPage > 1}">
<< Previous
</c:if>
<fmt:formatNumber var="endCounter" pattern="0">
<%= totalCount % perPage > 0 ? Math.ceil(totalCount/perPage) + 1 : totalCount/perPage %>
</fmt:formatNumber>
<c:forEach begin="1" end="${endCounter}" var="index">
<c:url value="${postUrl}" var="url">
<c:param name="pageNumber" value="${index}" />
<c:param name="perPage" value="${perPage}" />
</c:url>
${index}
</c:forEach>
<c:if test="${endCounter != showingPage}">
Next >>
</c:if>
</div>
</c:if>
hi you can try struts2 jquery grid here is the code
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<%# taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
<!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" xml:lang="en" lang="en">
<sj:div id="resultsDiv">
<body>
<div id="mainframe">
<s:form>
<div id="sucessMsg">
<s:property value="msg" />
</div>
<s:url id="editurl" action="editUser" />
<s:url id="deleteurl" action="deleteUser" />
<script type="text/javascript">
function editLinkFormatter(cellval, options, rowObject, icon, link_class, link_action) {
//alert(rowObject.username);
return "<a href='#' onClick='javascript:openEditDialog(""+cellval+"",""+rowObject.username+"")'><font class='hyperlink'><u>" + rowObject.username + "</u></font></a>";
}
function deleteLinkFormatter(cellval, options, rowObject, icon, link_class, link_action) {
return "<a href='deleteUser?userid="+cellval+"' onClick='javascript: return delete_user()'><font class='hyperlink'><u>Delete</u></font></a>";
//return "Delete";
}
colModal: [
{name: 'userid', formatter: function (cellvalue, options, rowObject) {
return editLinkFormatter(cellvalue, options, rowObject,
'ui-icon-pencil', 'edit-link-class', 'Edit');
}},
{name: 'userid', formatter: function (cellvalue, options, rowObject) {
return deleteLinkFormatter(cellvalue, options, rowObject, icon, link_class, link_action);
}}
];
function openEditDialog(userid,username) {
$("#resultsDiv").load("<s:property value="editurl"/>?userid="+userid+"&username="+username);
}
function delete_user() {
var agree=confirm("Are you sure you want to Delete?");
if (agree){
return true;
}
else{
return false;
}
// $("#edit_Users").dialog('open');
}
function unlockerFormatter(cellval, options, rowObject, icon, link_class, link_action) {
if(rowObject.loginStatus=='Locked'){
return "<a href='unlockuser?userid=" + rowObject.userid + "')'><font class='hyperlink'><u>Locked</u></font></a>";
}
else{
return "UnLocked";
}
/* return "<a href='deleteUser?userid="+cellval+"' onClick='javascript: return deleteUser("+cellval+")'><u>Delete</u></a>"; */
//return "Delete";
}
</script>
<sj:dialog id="edit_Users" title="Edit User" autoOpen="false"
modal="true" width="800" />
<sj:div id="draggable" draggable="true">
<s:url id="remoteurl" action="viewUserstemp" />
<sjg:grid id="gridtable" caption="Users" dataType="json"
href="%{remoteurl}" pager="true" gridModel="gridModel"
rowList="10,15,20,50,100" rowNum="10" rownumbers="true" viewrecords="true"
width="800" navigator="true" navigatorView="false" navigatorDelete="false" navigatorAdd="false" navigatorEdit="false" navigatorSearch="false">
<sjg:gridColumn name="userid" index="userid" title="User Id"
sortable="false" />
<sjg:gridColumn name="userid" index="username" title="User Name"
sortable="true" formatter="editLinkFormatter" />
<sjg:gridColumn name="emailid" index="emailid" title="Email Id"
sortable="true" />
<sjg:gridColumn name="userCreatedDate" index="userCreatedDate"
title="Created Date" sortable="true" />
<sjg:gridColumn name="userModifiedDate" index="userModifiedDate"
title="Modified Date" sortable="true" />
<sjg:gridColumn name="accstatus" index="accstatus"
title="Account Status" sortable="true" />
<sjg:gridColumn name="userid" index="username" title="Delete User"
sortable="true" formatter="deleteLinkFormatter" />
<sjg:gridColumn name="loginStatus" index="loginStatus" title="Unlock User"
sortable="true" formatter="unlockerFormatter" />
</sjg:grid>
<br></br>
<s:submit action="loadUserValues" cssClass="ui-button ui-widget ui-state-default ui-corner-all ui-state-hover" name="button"
id="button" value="New User" />
<br />
</sj:div>
</s:form>
<%--
<td height="25" align="left" valign="middle">
<s:url id="url" action="unlockuser">
<s:param name="userid">
<s:property value="userid" />
</s:param>
</s:url>
<s:set name="type" value="%{loginStatus}" />
<s:if test="%{#type=='Locked'}">
<s:a href="%{url}" title="Click here to Unlock" ><s:property value="loginStatus"/></s:a>
</s:if>
<s:else>
Unlocked
</s:else> --%>
</td>
</div>
</body>
</sj:div>
</html>

Resources