Why does my s:selectItems throws no such element exception? - jsf-2

I'm getting this error java.util.NoSuchElementException when i tried to check one of my checkbox under h:selectManycheckBox when i submit the form.
The many checkbox is dynamically populated from the bean. Here is my code.
<h:form id="eF">
<h:inputText id="i" value="#{aklat.suggest}">
<a4j:support event="onkeyup" action="#{aklat.complete}" reRender="m"></a4j:support>
</h:inputText>
<s:div>
<h:selectManyCheckbox value="#{aklat.selectedBooks}" layout="pageDirection" id="m">
<s:selectItems value="#{aklat.books}" var="_book" itemLabel="#{_book}" itemValue="#{_book}" label="#{_book.bookName}"/>
</h:selectManyCheckbox>
<a4j:commandButton value="Add Users" action="#{aklat.fire}"></a4j:commandButton>
</s:div>
</h:form>
The weird part is it renders some data output but when i checked the source code. there are no input type checkbox element.
Is something I am missing.

I assume your managed bean is request scope...
because you are making an ajax request, you have to enable "aklat.books" to persist its value longer than request but shorther than session scope.
If you have tomahawk between your app libraries you can use savestate like this (put it after the h:form tag) :
<t:saveState value="#{aklat.books}"/>
if no tomahawk, you can use a4j:keepAlive:
<a4j:keepAlive beanName = "#{aklat.books}"/>

Related

prime faces ajax not working

We have a JSF project with the following versions of JARs:
Prime Faces 5.1
JSF 2.0
Javaee-api 5
But the Project Facets(in eclipse) defines JSF 2.2, we never changed it.
JPA 2 ( javaee-api 5)
Ejb 3.0
Our ajax is not working.
<p:selectOneRadio id="enrolledInPlanFlag" value="#{phInfoBean.enrldPlanFlag}" label="Action" >
<f:selectItem itemLabel="Yes" itemValue="Yes" />
<f:selectItem itemLabel="No" itemValue="No" />
<p:ajax process="enrolledInPlanFlag" update="#form"/>
</p:selectOneRadio>
<p:dialog id="dialog" header="APTC Warning" widgetVar="dlg1" modal="true" height="200" width="500" resizable="false" rendered="#{phInfoBean.enrldPlanFlag eq 'Yes'}">
I am trying to display dialog based on the selectOneRadio. But the AJAX is not working and we have the wierd situation where sometimes it works and sometimes it not.
We have annotated managed bean with #ViewScoped.
Please help.
Make it work
You never show your dialog in your code. You could attach an oncomplete event to your p:ajax
<p:ajax process="enrolledInPlanFlag" update="#form" oncomplete="PF('dlg1') != null ? PF('dlg1').show() : ''" />
The condition PF('dlg1') != null is required as if you choose "No" your dialog is no longer rendered in your page, therefore PF('widgetVarOfDialog') is unreachable.
Additional notes
I would improve this code by:
Changing enrldPlanFlag to a boolean instead of a string (cleaner IMO)
Display the dialog programatically in an listener (called from your p:ajax) if the boolean is true
Why? To leave the logic in your bean instead of your .xhtml page

JSF command button updating even there are validation errors

I'm new to JSF, my question may be silly for you.. It is very much valuable for me..
<h:form id="form1">
<p:messages autoUpdate="true" showDetails="true" />
<p:dataTable id='form1ID'>....</dataTable>
<p:inputText value="#{bean.name}" required="true"
requiredMessage="Please Enter Name!" label="Name ">
</p:inputText>
</h:form>
<h:form id="form2">
<p:messages autoUpdate="true" showDetails="true" />
<p:dataTable id='form2ID'>....</dataTable>
<p:inputText value="#{bean.name}" required="true"
requiredMessage="Please Enter Name!" label="Name ">
</p:inputText>
<p:commandButton value="Submit" update=":form1:form1ID"
actionListener="#{mgmtBean.doCreateType}" />
</h:form>
I have two forms. when I click on form2 command button with empty fields, it will show error messages perfectly since i have added <p:messages autoUpdate="true" showDetail="true"/>.
The bad thing or surprising thing here for me is, it is showing error messages on top of form1 also may be because of <p:messages autoUpdate="true" showDetail="true"/> added in form1 and i'm trying to update form1 on command button click in form2.
I don't want to show error messages on form1 when form2 is throwing validation error messages. How can i fix this ? I googled it out.. but couldn't find the solution.
Evironment i'm using is jsf-api-2.1.5 and primefaces 4.0 version and view technology is facelets(XHTML)
Hope it is clear..
Any idea is highly appreciated.
Try to disable rendering of messages on the form1:
<p:messages autoUpdate="true" showDetails="true" rendered="#{bean.renderedmessage}"/>
And in the bean, add the renderedmessage variable:
public Boolean getRenderedmessage() {
return renderedmessage;
}
/**
* #param renderedmessage the renderedmessage to set
*/
public void setRenderedmessage(Boolean renderedmessage) {
this.renderedmessage = renderedmessage;
}
And, for the doCreateType() method, add:
public void doCreateType(){
..............
setRenderedmessage(false);
.............
}
After the form1 is updated, you can choose some event or method, where you can setRenderedmessage(true);
What you're currently experiencing should indicate to you that you usually don't need two <p:messages/>s in the same JSF view; one is enough.
Regardless of the fact that you have two <h:form/>s on your page, there's still only one FacesContext associated with that view (The FacesContext object is a JSF construct that encapsulates all the information/data/components etc that's associated with a given JSF page request).
By default the <p:messages/> will display every FacesMessage that is queued within it's associated instance of FacesContext, regardless of the source of the message (well, almost: if you set globalOnly="true" on the <p:messages/>, you can change that behaviour).
That being said, you basically have two options:
Get rid of the extra <p:messages/> and rely on (and appropriately position) only one to display all errors/warnings for that view
Specify the for attribute, set to the desired component. Doing so, you'll guarantee that only one input component can trigger the display of its associated message component. For example
<h:form id="form1">
<p:messages for="inputName" autoUpdate="true" showDetails="true" />
<p:dataTable id='form1ID'>....</dataTable>
<p:inputText id="inputName" value="#{bean.name}" required="true"
requiredMessage="Please Enter Name!" label="Name ">
</p:inputText>
</h:form>
Note that I've set an id attribute on the <p:inputText/> component; this is necessary so you can use it in the for attribute for the messages component.
Further reading:
What is FacesContext used for?
I have fixed the issue by using the following code
<p:messages autoUpdate="true" showDetails="true" visibility="info"/>
so it is just displaying info messages and other pop up error messages will not be showun.

Dynamically add Primefaces Hotkey control

I am building an app where one of the requirements is heavy use of hotkeys. So heavy in fact that we want to pull those hotkeys back into a central controller.
The basic idea is each page will have a key associated with it. When jsf hits that key, it will go back to a central enummap to decide what hotkeys are supposed to be associated with that page and what methods are supposed to be added to the keys of that page.
My problem is the dynamic load. I can't use the
For now, I have this
<h:form binding="#{hotkeyController.form}">
<f:event listener="#{hotkeyController.genKeyHandler('HOTKETEST')}" type="preRenderComponent"/>
<p:outputPanel id="displayHotkey">
<h:outputText value="#{hotkeyController.keyText}" rendered="#{not empty hotkeyController.keyText}"/>
</p:outputPanel>
</h:form>
Then for my backing bean i have this
public void genKeyHandler(String pageKey) {
Hotkey hotkey = new Hotkey();
hotkey.setBind("ctl+shift+d");
hotkey.setAsync(true);
// "#{hotkeyController.keyHandler('HOTKETEST', 'F1')}"
hotkey.setActionExpression(createMethodExpression("#{hotkeyController.keyHandler('HOTKEYEXAMPLE', 'CTLSHIFTD')}", null,
String.class, String.class));
hotkey.setUpdate("displayHotkey");
form.getChildren().add(hotkey);
hotkey = new Hotkey();
hotkey.setBind("ctl+shift+a");
hotkey.setAsync(true);
// "#{hotkeyController.keyHandler('HOTKETEST', 'F1')}"
hotkey.setActionExpression(createMethodExpression("#{hotkeyController.keyHandler('HOTKEYEXAMPLE', 'CTLSHIFTA')}", null,
String.class, String.class));
hotkey.setUpdate("displayHotkey");
form.getChildren().add(hotkey);
}
Now this works in the sense that it actually inserts the hotkey into the form. I can see it in inspector. But, my problem is two fold. One, if I refresh the page, I get duplicate ID errors, if I use the preRenderView, I get "Error restoring component" errors. seems like no combination will work.
Is there any way to make this work? All I want is to have the bean method that inserts the hotkeys fire the first time a page is loaded and only fired once in the life of the page/view/whatever. This shouldn't be this hard.
My suggestion is that you use an exclusive form for the hotkeys.
Here is the sample:
<h:form id="mainForm">
<p:remoteCommand name="loadHotKeys" action="#{hotkeyController.genKeyHandler('HOTKETEST')}" update=":hotkeyForm" global="false" process="#this" />
<p:outputPanel id="displayHotkey">
<h:outputText value="#{hotkeyController.keyText}" rendered="#{not empty hotkeyController.keyText}"/>
</p:outputPanel>
</h:form>
<h:form id="hotkeyForm" binding="#{hotkeyController.form}" />
<script type="text/javascript">
jQuery(document).ready(loadForm());
</script>
And the genKeyHandler method should clear the hotkeyForm (form.getChildren().clear()) before adding the hotkeys.

Displaying a message from managed bean with primefaces confirmation dialog component

in my page , i'm trying to display a confirmation dialog after clicking a button .In the confirmation dialog i used the attribute message to display it , this message is taken value after clicking the button . So i did it like that :
<p:commandButton value="Delete" update="testPlanetree" id="deleteBtn"
disabled="#{projectTestManagementMB.disable}" oncomplete="deleteConfirmation.show()"
action="#{projectTestManagementMB.testFn}"/>
<p:confirmDialog id="confirmDialog" message="#
{projectTestManagementMB.deleteConfirmationMsg}"
header="Confirming Deleting Process" severity="alert"
widgetVar="deleteConfirmation">
<p:commandButton id="confirm" value="Yes Sure" update="messages"
oncomplete="deleteConfirmation.hide()" />
<p:commandButton id="decline" value="Not Yet"
onclick="deleteConfirmation.hide()" type="button" />
</p:confirmDialog>
ProjectTestManagementMB Managed Bean :
private String deleteConfirmationMsg;//with getters and setters
public void testFn(){
deleteConfirmationMsg="do you want to delete ...";
}
The problem is that the deleteConfirmationMsg never take the value "do you want to delete ..." (is always empty)
Any idea will be appreciated
The <p:confirmDialog> has already generated its HTML representation on the very first HTTP request returning the page with the form and the dialog. It's merely hidden by CSS and is supposed to be shown/hidden by JS. When you change the confirm message afterwards in a bean action method, then it won't be reflected in the generated HTML output as long as you don't ajax-update it.
So, in order to get the changed message being reflected, you'd need to update the HTML representation of the <p:confirmDialog> in the client side before showing it in the oncomplete. You can for this use the update attribute of the command button which should show the dialog.
<p:commandButton ... update="confirmDialog testPlanetree">
try this i should works :
<p:commandButton value="Delete" update="testPlanetree" id="deleteBtn" actionListener="#
{projectTestManagementMB.testFn}"
disabled="# {projectTestManagementMB.disable}"
oncomplete="deleteConfirmation.show()" />

How to find indication of a Validation error (required="true") while doing ajax command

I have a form inside a dialog which I close by clicking on commandbutton with ajax ,
like this
<h:commandButton value="Add" action="#{myBean.addSomething(false)}"
id="add_something_id" >
<f:ajax render="#form someTable" execute="#form"
onevent="closeAddNewSomethingDialogIfSucceeded"></f:ajax>
</h:commandButton>
and here is the js code for closing the dialog
function closeAddNewSomethingDialogIfSucceeded(data) {
if(data.status === 'success') {
$("#dialog_id").dialog("close");
}
}
No problems till here...
Now I changed some of the dialog form fields into required="true" and now I want to prevent the closing of the dialog of i got validation errors...
But the ajax data.status still reaches its success state , and I can't figure out what indication of validation failure I can hook on...
any ideas?
Thanks to BalusC answer I did the following:
in JSF , added :
<h:panelGroup id="global_flag_validation_failed_render">
<h:outputText id="global_flag_validation_failed" value="true"
rendered="#{facesContext.validationFailed}"/>
</h:panelGroup>
the f:ajax was changed into
<f:ajax render="#form someTable global_flag_validation_failed_render"
and in js added the following check
if(data.status === 'success') {
if($("#global_flag_validation_failed").length === 0){
$("#dialog_id").dialog("close");
}
}
Not specifically for required="true", but you can check by #{facesContext.validationFailed} if validation has failed in general. If you combine this with checking if the button in question is pressed by #{not empty param[buttonClientId]}, then you can put it together in the rendered attribute of the <h:outputScript> as follows:
<h:commandButton id="add_something_id" binding="#{add}" value="Add" action="#{myBean.addSomething(false)}">
<f:ajax execute="#form" render="#form someTable" />
</h:commandButton>
<h:outputScript rendered="#{not empty param[add.clientId] and not facesContext.validationFailed}">
$("#dialog_id").dialog("close");
</h:outputScript>
(note that you need to make sure that the script is also re-rendered by f:ajax)
A bit hacky, but it's not possible to handle it in the onevent function as the standard JSF implementation doesn't provide any information about the validation status in the ajax response.
If you happen to use RichFaces, then you could just use EL in the oncomplete attribute of the <a4j:xxx> command button/link. They are namely evaluated on a per-request basis instead of on a per-view basis as in standard JSF and PrimeFaces:
<a4j:commandButton ... oncomplete="if (#{!facesContext.validationFailed}) $('#dialog_id').dialog('close')" />
Or if you happen to use PrimeFaces, then you could take advantage of the fact that PrimeFaces extends the ajax response with an additional args.validationFailed attribute which is injected straight in the JavaScript scope of the oncomplete attribute:
<p:commandButton ... oncomplete="if (args && !args.validationFailed) $('#dialog_id').dialog('close')" />
(note that & is been used instead of &, because & is a special character in XML/XHTML)
Or you could use the PrimeFaces' RequestContext API in the bean's action method to programmatically execute JavaScript in the rendered view.
RequestContext.getCurrentInstance().execute("$('#dialog_id').dialog('close')");
No conditional checks are necessary as the bean's action method won't be invoked anyway when the validation has failed.
Two things
1) Checking for an error in the 'onevent' function
Surely you have a message tag for the mandatory field?
<h:message id="m-my-field-id" for="my-field-id" errorClass="error-class"/>
So you can check for the error-class something like
var message = $('#m-my-field-id');
if(message.hasClass('error-class'){
//do this
}
else{
//do that
}
2) The DOM isn't up to date on success
Yes, I can see the message on the page in Firefox, yet jQuery tells me it is not there.
I have found that using the smallest possible timeout is sufficient to fix this
setTimeout(
function(){
setErrorStyle(source.attr('id'));
},
1
);
I think you should take a look at PrimeFaces' RequestContext. This would help you trigger client-side code on the server side.
#BalusC
in your example code the clientId of the button is not set as a param because it is a AJAX request. So
not empty param[add.clientId] is always false.
But this works:
param['javax.faces.source'] eq add.clientId
(tested with jsf-impl-2.2.12.redhat-1)
regards

Resources