JSF 2.0 page navigation not working - jsf

I'm using JSF 2.0 in my web project. But navigation is not working properly, in my case. I think this problem arose due to changes in hierarchy of the files because action method is working fine. I'm attaching the snapshot to give idea about files' hierarchy.
If anyone could help to overcome this, I'll be very thankful.

You have to add ajax="false" to you primefaces commandButtons in order to perform navigation or use the simple <h:commandButton ...
if you want to use primefaces ajax button , you should sue redirect then,
like this
<p:commandButton action="home?faces-redirect=true" value="Redirect to home"/>
also look a t similar question over here:
PrimeFaces commandButton doesn't navigate or update

Upgrade to PrimeFaces 3.2. Then you'll be able to navigate by ajax. The update/render of #all was not supported before that version. If you can't upgrade, then you need to bring in the following JavaScript hack:
var originalPrimeFacesAjaxResponseFunction = PrimeFaces.ajax.AjaxResponse;
PrimeFaces.ajax.AjaxResponse = function(responseXML) {
var newViewRoot = $(responseXML.documentElement).find("update[id='javax.faces.ViewRoot']").text();
if (newViewRoot) {
document.open();
document.write(newViewRoot);
document.close();
}
else {
originalPrimeFacesAjaxResponseFunction.apply(this, arguments);
}
};
Put this in a .js file which you import in the very end of the <h:head> tag. E.g.
<h:head>
...
<h:outputScript name="js/primeFacesAll.js" />
</h:head>

Related

Widget for var 'FileUpload' not available

Primefaces 7.0, JSF 2.1.19
I am trying to replace richfaces 3.3.3 with primefaces 7.0 (and upgrade JSF to 2.1) and got a special behaviour from the fileUpload widget: When I first render the page it works without problems (no fileupload done, just render it), then I navigate again to the same page it is broken:
The fileupload component:
<p:fileUpload disabled="#{antragAttachments.fileUploadDisabled}" id="attachmentUpload" widgetVar="attachmentUpload" binding="#{antragAttachments.fileUpload}"
fileUploadListener="#{antragAttachments.fileUploadListener}" label="Durchsuchen..." uploadLabel="Datei anhängen" cancelLabel="Abbrechen" invalidFileMessage="test typ"
mode="advanced" fileLimit="1" sizeLimit="15728640" invalidSizeMessage="Der Dateianhang ist zu groß! Die maximale Größe beträgt 15MB!" previewWidth="1"
oncomplete="uploadComplete();" auto="true">
</p:fileUpload>
This is the (menu) component the navigate again to the xthtml:
<ui:repeat value="#{name}" var="item" >
<div id="menuOP" class="ebene#{item.shifting} #{item.selected ? 'divselected' : 'divnotselected'} #{item.spriteClass}">
<p:commandLink immediate="#{item.immediate}" value="#{item.label}" rendered="#{item.enabled}" action="#{item.navigate}"
styleClass="#{item.selected ? 'selected' : 'notselected'}" oncomplete="#{item.oncomplete}"/>
<h:outputText id="menuNoLinkText" rendered="#{!item.enabled}" styleClass="disabled" value="#{item.label}" />
</div>
</ui:repeat>
I tried to remove the immediate, set the type to "submit", use h:commandLink (without the oncomplete of course) just to see if I can get this running somehow. Does not work.
I also looked at the Primefaces fileupload introduction from balusC, but my problem is not the fileupload, it is the second rendering. There is also a Primefaces forum entry about something similar, but the trick von melloware did not work also.
What I do not understand, by the first click on the menu the rendering works fine and after every click on the menu-commandlink the browser console tells me that the widget is not available.
I found examples with similar problems, but there is most of the time a javascript call of the widget like PF('attachmentUpload').doSomething(), but this is not the case here.
EDIT:
I found out that when I first click on the commandlink the fileupload.js is loaded:
By the second click this is not the case anymore:
I also found a thread with the same problem: <p:layout> and <p:fileUpload> not working on page refresh, but there the only solution seems to be to take the css and js for fileupload and add it manualy to as resource... which is a little creepy...

JSF 1.2 to open external link in new tab. without distrubing current flow [duplicate]

I need to open a JSF page in a new window by POST on click of a <h:commandButton>. I know I can acheive this using the JavaScript. But I would like to achive this using JSF and not JavaScript.
How can I achieve this? I'm using JSF 2.0.
The only non-JS way is to set target="_blank" in the parent <h:form>.
<h:form target="_blank">
...
<h:commandButton value="Open in new Window" />
</h:form>
This however affects all non-ajax(!) actions which are performed in the very same form. So if you're smart, make the action which shouldn't open in a new window an ajax action. However, ajax is also JavaScript and you mentioned that you don't want to use JS (I hope you don't get shocked once you discover that PrimeFaces is actually full of JavaScript).
If you absolutely need to restrict it to a single action, then you really can't go around asking little help to JavaScript.
<h:form>
...
<h:commandButton value="Open in new Window" onclick="this.form.target='_blank'" />
</h:form>
When you restrict the target only to a single action, maybe you want to get the form in its initial state.
With the oncklick action you set the target of the form to a _blan page.
After the click, the page is opened in a new tab/page (triggers the action event).
At last, the onblur action is triggered and set the form again to its initial state (the rest of the buttons will open in the _self page)
With this code, you can restrict to only a h:commandbutton to open in a new page.
The rest of the buttons will be opened in the self page:
<h:commandButton
onclick="this.form.target='_blank'"
onblur="this.form.target='_self'"
id="listadoRebuts"
action="#{giaquaBusquedaCorte.abrirListadoRebuts}"
value="#{msg.seqVisorbtnRecibos}">
</h:commandButton>

Oncomplete of Primefaces component fileUpload is never called

I have a form upload component on my page and want to make more actions in JavaScript after file upload is complete and page updated.
I put simple log statement to test for "oncomplete" execution, but it never happens.
File is successfully uploaded and other parts of page updated, but no "oncomplete" actions performed.
Here is my component:
<p:fileUpload id="objectUpload1"
fileUploadListener="#{importBackingBean.handleFileUpload}"
mode="advanced" dragDropSupport="true"
invalidFileMessage="Недопустимый тип файла"
invalidSizeMessage="Размер файла превышает 5 МВ"
cancelLabel="#{msg['stop_LABEL']}"
uploadLabel="#{msg['Upload_LABEL']}"
label="#{msg['Choose_LABEL']}" update="results objects_Data"
sizeLimit="5000000" allowTypes="/(\.|\/)(xlsx|xls)$/"
oncomplete="load();" />
And my Javascript:
<script type="text/javascript">
function load() {
console.log('File Uploaded!');
$("button[id*='load']").click();
}
</script>
Button:
<p:commandButton value="Загрузить полисы"
oncomplete="#{importModelBean.needToLoadMore ? 'load();' :'none();'}"
id="load"
action="#{importBackingBean.loadOneRow(importModelBean.current)}"
process="#this" update="mainViewForm:objects_Data" />
When I click the button manually it works just fine. But not getting clicked with oncomplete of filepload.
Using the codes given, I have reproduced this scenario. Although $("button[id*='load']").click(); has been invoked correctly, no log is showing. I am guessing that the button with an id load is set to ajax=”false”. If this is true, then I think that the message was logged the moment console.log('File Uploaded!'); is invoked but was cleared since the page is updated after the load button process. Do you need the log for something? If not, just remove console.log('File Uploaded!'); code and it should work just fine.
EDIT:
I misunderstood you. I thought that your concern was that the message was not logged in the console.
I have tested your codes on two projects (running on two different computers) and I can’t reproduce your problem.
Project 1:
Primefaces 6.0
JSF 2.0
WAS 8.5
IE 11
Project 2:
Primefaces 5.x
JSF 2.0
Glassfish 4.1
Google Chrome
I even tried oncomplete=”alert(‘hello!’)” and it worked fine.
I think that the problem is somewhere else.
For the mean time, can you try the following codes and see if it works:
<p:fileUpload id="objectUpload1"
fileUploadListener="#{importBackingBean.handleFileUpload}"
mode="advanced" dragDropSupport="true"
invalidFileMessage="Недопустимый тип файла"
invalidSizeMessage="Размер файла превышает 5 МВ"
cancelLabel="#{msg['stop_LABEL']}"
uploadLabel="#{msg['Upload_LABEL']}"
label="#{msg['Choose_LABEL']}" update="results objects_Data"
sizeLimit="5000000" allowTypes="/(\.|\/)(xlsx|xls)$/"
oncomplete="rc()" />
<p:remoteCommand name="rc"
oncomplete="#{importModelBean.needToLoadMore ? 'load();' :'none();'}"
action="#{importBackingBean.loadOneRow(importModelBean.current)}"
process="#this" update="mainViewForm:objects_Data" />
For more information about p:remoteCommand, please refer to primefaces showcase RemoteCommand.

React to a MenuButton being clicked

We have code that periodically refreshes our document. We also have as part of the JSF page, menuButtons (primefaces), originaly as part of dataTable cell/s in a column. We want to disable the refresh when the menuButton is clicked (the menu is expanded), and re-enable it when the menuButton is closed (to prevent page refresh from closing menu).
I've attempted to catch menuButton events using java script, but to no avail. Part of the problem is that I do not know how to identify the JSF component uniquely from javascript, as ID does not seem to work when attempting to catch events. There also does not exist any satisfactory event attributes (as part of Primefaces menuButton) that I can hook up to javascript.
Below is the minimal code that I could extract. I have extracted the menu to be on its own (not part of dataTable) for simplicity, as the question still stands. I may have a reference to a bean and dictionary files in there, but you should get the idea:
<?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">
<ui:composition 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"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:form id="virtualMachineTableForm">
<!-- Lazy load table -->
<p:remoteCommand name="lazyload"
update=":vmGroupTabs:virtualMachineTableForm:testMenu"
actionListener="#{backupGroupController.refreshHard()}" />
<!-- Refresh hard button -->
<p:commandButton id="refreshButton"
update=":vmGroupTabs:virtualMachineTableForm:testMenu"
icon="ui-icon-refresh"
immediate="true"
title="#{msg.action_refresh}"
actionListener="#{backupGroupController.refreshHard()}"/>
<p:menuButton
id="testMenu"
value="#{msg.menuButton_SelectItem}">
<p:menuitem
value="Toggle refresh"
onclick="toggleRefreshState()">
</p:menuitem>
</p:menuButton>
<!-- Poller -->
<p:poll interval="5" listener="#{backupGroupController.refreshSoft()}"
update=":vmGroupTabs:virtualMachineTableForm:testMenu" widgetVar="poll" />
</h:form>
<script type="text/javascript">
var toggleRefreshState = function(){
if (poll.isActive()) {
poll.stop();
alert("Poller stopped" );
}
else {
poll.start();
alert("Poller started" );
}
};
$(document).ready(function(){
poll.start();
setTimeout("lazyload();", 100);
});
//
// $("???SomeWayToIdentifyMenu???").on({
// onMenuOpen???: function(){
// alert("Opening menu - stopping refresh");
// }
// onMenuClose???: function(){
// alert("Closing menu - starting refresh");
// }
// });
</script>
</ui:composition>
Is it possible to catch menu open/close (or for that matter any) events for jsf primefaces menu buttons on the client side using Java script?
Is it possible to determine if the menubutton is open/closed for the purpose of disabling refresh to prevent menu from disappearing.
Your help appreciated, Thank you,
Werner
In the end it is all html, javascript and css. Javascript in PF is mainly jquery and all components have javascript code behind them to function on the client side.
There are several ways to plug into this. Attaching plain jquery event handlers to the right element (checkable via your browser developer tool and/or checking what the PrimeFaces javascript does) is an option, but you have to reapply them over and over again when e.g. ajax calls take place. Another option is to override the basic menu button functionality without changing the PF original source.
Since the code is open source, you can try to find the javascript source of the PrimeFaces MenuButton. It is in this case all defined in menu.js and this can be fairly easily looked at (and is cleanly written)
In there you can see all events that are added to the component and also if there e.g. are onBeforeShow handlers or not (some components in PrimeFaces have those, the MenuButton not which is unfortunate for you, but I've not seen a usecase like this up to now).
The downside of overriding the basic functionality unfortunatly is that this will then be true for all menu buttons. So you have to implement some logic to decide if you actually need to perform some custom action or not. There are several ways to do that, but the easiest in my opinion is to check for the presence of a specific style class (e.g. 'stopPoll').
Now to the actual overriding:
var oldPFShow = PrimeFaces.widget.MenuButton.prototype.show
PrimeFaces.widget.MenuButton.prototype.show = function() {
alert("before show");
oldPFShow.apply(this, arguments);
}
var oldPFHide = PrimeFaces.widget.MenuButton.prototype.hide
PrimeFaces.widget.MenuButton.prototype.hide = function() {
oldPFHide.apply(this, arguments);
alert("after hide");
}
(do not forget to call the original functions)
Where I put the alerts, you have to implement checking for the presence of a class or leave that out if you have one menu button on that page or want the behaviour for all menubuttons
Some general comments: (Will be removed later on, but difficult to format in the comments)
I've attempted to catch menuButton events using java script, but to no
avail.
Posting attempts can help, since sometimes you are close and just have some small oversight). In those cases it is easier to write an answer for people trying to give support
Part of the problem is that I do not know how to identify the
JSF component uniquely from javascript,
This is a generic PrimeFaces thing (and differs from component sets). Apply a widgetVar attribute and with PF('') you have a handle to the specific components.
And as you can see the explicit fact that you use a PrimeFaces menuButton is of the highest importance. Having a small piece of code (smaller then you have now, but compliments for the mcve) is confirmation of this (assumption is the mother of all... ) Adding 'javascript' as a very generic tag, often attracts the 'wrong' people, as does 'java' So please next time leave those out
The easiest way to achieve this is to add javascript to the menuButtons to change a global variable and have the periodic refresh read that global variable and act accordingly. As you have no code or indication what components you are using I can't get more specific then that. Here would be the javascript code I would expect to see
window.preventRefresh = false;
function doPeriodicRefresh() {
if(!preventRefresh) {
window.location.reload();
}
}
setInterval(doPeriodicRefresh, 60000);
function showMenu() {
window.preventRefresh = true;
menu.show();
}
function hideMenu() {
window.preventRefresh = false;
menu.hide();
}
Your mouseovers/mouseout for the menu should call showMenu and hideMenu, any parameters would have to be proxied through.
This also depends on how you are doing your periodic refresh. If you are using the refresh header or metatag I don't believe you will be able to stop these from javascript.

ui is undefined jsf primefaces

I have a problem with using primefaces autocomplete component. When triggered ia get the error $ui. is undefinded and the backing bean is not even called.
My code is:
<p:autoComplete completeMethod="#{auto.uliList}" value="#{naroc.ulValue}"></p:autoComplete>
Big thanks for any help!
This is recognizeable as a jQuery / jQuery UI conflict.
PrimeFaces ships with jQuery and jQuery UI libraries by itself already. If you have manually included jQuery and/or jQuery UI by a custom <script> or <h:outputScript>, then it would only conflict with PrimeFaces-provided ones and result in this kind of "foo is undefined" errors. You should remove your manually included jQuery scripts from the page (and your webapp) and rely on PrimeFaces-provided ones instead.
If you have pages which don't necessarily use PrimeFaces components (and thus its bundled jQuery scripts won't necessarily be auto-included on every page), then you need to explicitly specify PrimeFaces own jQuery instead:
<h:outputScript library="primefaces" name="jquery/jquery.js" />
I just managed to resolve my problem.
it was quite simple but effective. So if you come up with a prolem similar to mine just add this code to your page head:
<h:outputScript target="head">
jQuery.noConflict();
</h:outputScript>

Resources