Using findComponent on preRenderView listener - jsf

On the JSF page:
<f:event type="preRenderView" listener="#{backingBean.test()}" />
<h:inputHidden id="inputHiddenId" value="dummy" />
On the backingBean:
public void test() {
System.out.println("test");
FacesContext fc = FacesContext.getCurrentInstance();
UIComponent comp = fc.getViewRoot().findComponent("inputHiddenId");
if (comp != null) {
System.out.println("comp " + comp); // Does not print
}
}
The phaseListener shows that test() is called during render response phase:
START PHASE RESTORE_VIEW 1
END PHASE RESTORE_VIEW 1
START PHASE RENDER_RESPONSE 6
test
END PHASE RENDER_RESPONSE 6
However, it is not finding the inputHiddenId component. It seems that the component is not available during this time. Does it need to be on a postback? How can I access the component when first loading the page? Sorry, I am not too familiar with the intricacies of the JSF lifecycle. If anyone could shed some light on this, it would be greatly appreciated.
Reposting the problem:
The real problem is that I have a form with several fields. After the form is submitted, users can still edit certain fields which has the effect of resetting other sections on the form and making it invalid. Since it is a long form, users should be able to save the form even though it fails validation, and return to it later. So when loading the page, I'd like it to display inline validation on the fields. We are using JBoss Seam. The validation method displays the errors using
StatusMessages.instance().addToControl("inputHiddenId", severity, message)
The validation method is called from the page.xml using
<action execute="#{backingBean.pageInitWithValidation()}" on-postback="false" />
However this doesn't display the error message inline on the ui component
<s:div id="errorMessages">
<h:inputHidden id="inputHiddenId" value="dummy" />
<h:messages for="inputHiddenId" />
</s:div>
It shows it instead at the top in the global messages
<h:messages globalOnly="true" />
That's why I tried to use the preRenderView, but that had the same effect.
I'm currently using a second method with the body onload event along with a4j:jsFunction, but it is not very clean.
<a4j:jsFunction name="validate"
action="#{backingBean.validate()}" render="formId" />
<h:body onload="validate()">

Related

Primefaces won't call setter on ManagedBean

I'm in the middle of building a web application (Spring 4, Primefaces 5.1 and JPA).
While one of my xhtml-pages has no problems working with its ManagedBean, the others won't really work. To be more specific, the UI input components (like inputText) won't call any setters from the managed Beans.
I've already run my Tomcat (8) on debug mode, which showed me that the page calls the get-methods, but no set-methods at all. If I try to persist something, all values are null (or 0, in case of an int-value). (it even persists an object into the database with all values null, though I have declared some #NotNull constraints which should be taken to the database configuration via JPA)
So, question is: How can I make my inputFields work with the fields of my ManagedBean? (Eclipse also shows me in the editor, that theoretically, the connection to the fields is there, it knows the managed bean, the field and the get-/set-methods)
SoftwareManagedBean.java
#ManagedBean(name = "swmb")
#ViewScoped
public class SoftwareManagedBean extends AssetManagedBean implements
Serializable {
private String bezeichnung;
private Software neueSoftware;
// +some more private fields, every single one with its get-/set-method
#Override
public String getBezeichnung() {
return super.getBezeichnung();
}
#Override
public void setBezeichnung(final String bezeichnung) {
super.setBezeichnung(bezeichnung);
}
//instantiante the field "neueSoftware"
public void createEmptySoftware(){
if(neueSoftware != null)
return;
this.neueSoftware = new Software();
}
//Persist Software with values from inputFields
public void addSoftware() {
createEmptySoftware();
neueSoftware.setBezeichnung(getBezeichnung());
softwareService.addSoftware(neueSoftware);
//...
neueSoftware = null;
}
viewSoftware.xhtml
<h:body>
<p:dialog header="Neue Software anlegen" widgetVar="SwNeuDialog" width="60%"
closeOnEscape="true" draggable="false" resizable="false" position="center">
<h:form id="SwDlgForm">
<h:panelGrid columns="3" border="0" >
<p:outputLabel for="swBezeichnung" value="Bezeichnung: " />
<p:inputText id="swBezeichnung" value="#{swmb.bezeichnung}"
label="Bezeichnung" required="true" />
<f:verbatim/>
<p:outputLabel for="swKategorie" value="Kategorie: " />
<p:selectOneMenu id="swKategorie" value="#{swmb.kategorie}" label="Kategorie" required="true" >
<f:selectItem itemLabel="Kategorie wählen" value="#{null}" noSelectionOption="true"/>
<f:selectItems value="#{swmb.kategorieListe}" var="kat" itemLabel="#{kat.bezeichnung}" itemValue="#{kat}"/>
</p:selectOneMenu>
<p:commandButton value="neue Kategorie hinzufügen" />
<!-- + some more input fields -->
<p:commandButton value="Speichern" action="#{swmb.addSoftware()}" onclick="PF('SwNeuDialog').hide()" resetValues="true" process="#this"/>
<p:commandButton value="Abbrechen" onclick="PF('SwNeuDialog').hide()" resetValues="true" process="#this"/>
</h:panelGrid>
</h:form>
</p:dialog>
<!-- dataTable -->
</h:body>
AssetManagedBean.java
#ManagedBean
public abstract class AssetManagedBean {
//name of the hard-/software
private String bezeichnung;
//+ some more fields with get-/set methods
public String getBezeichnung() {
return bezeichnung;
}
public void setBezeichnung(String bezeichnung) {
this.bezeichnung = bezeichnung;
}
I hope that code is sufficient to see the problem, since the rest of the code follows the same structure. I think, the problem could lie within the xhtml file, but I don't see where or why. I've got the SpringBeanFacesELResolver (or however it is called), I've already looked through the code and compared it to another xhtml page and its Managed Bean, but there are no differences anymore. (though one is working, one not)
My debugger showed, how the working class/page (viewAdministration.xhtml) called the get-/set methods of the managed bean:
opening dialog window: get...(), set...()
clicking the commandButton to submit/persist: get() (old Value), set() (new Value), get() (new Value)
Another get() (called by the add... method)
(+ another get() for the dataTable on the main page)
on viewSoftware.xhtml, it looks like this:
opening dialog window: get()
clicking the commandButton to submit/persist:
another get() called by the addSoftware method
As you can see, when I try to submit, there is no set or get.
So, to summarize:
no setter called by trying to submit
the code on viewSoftware.xhtml and SoftwareManagedBean is similar to another, functioning ManagedBean + xhtml page (I've compared it again and again)
annotations in Managed Beans are the same (#ManagedBean, #ViewScoped)
the inputFields are inside a form (
I'm totally clueless, but I think it is some small mistake from my side that I can't just see.
I've searched through the web and especially stackoverflow, but all the problems and answers I've found couldn't help me finding what's wrong
Even without inheriting from a superclass it won't work (tried that out too)
I hope, you can help me. If this post is lacking some information, I'm sorry about that, I tried my best to not let this post grow too big and still get as much relevant information in it as possible.
So, I have found my mistake (or at least, I think I have). Only took me 2 weeks, but anyway...
I tried to test it out more specifically, wrote test classes and an xhtml page. Nothing worked (from simple Input over Dates to own classes).
The solution to this problem was to disable ajax on my commandButton (ajax="false"). When I tried to understand more of it, I realized that the commandButton opening the dialog window was nested in a facet inside a dataTable, and thus it had problems to properly set the values of the input fields.
So, thank you for your help. Maybe/hopefully this can or will help some other people later as well.
From the first glance at the code, without reading it whole, try putting process="SwDlgForm" on your command buttons, instead of process="#this". If that doesn't solve the problem, I'll read more carefully and try to help.

How to evaluate a FacesComponent property inside a custom component

Lately, I've been working on a dynamic form project but is stop with a custom component problem. What I have:
A faces component for formField:
#FacesComponent(value = "formField")
public class FormFieldCompositeComponent {
private boolean email;
}
A custom component jsf:
<o:validator for="email_text" validatorId="emailValidator" disabled="#{not cc.email}" />
OR
<c:if test="#{not cc.email}">
<f:validator for="email_text" validatorId="emailValidator"></f:validator>
</c:if>
OR
<f:validator disabled="#{not cc.email}" for="email_text" validatorId="emailValidator"></f:validator>
And the validator:
#FacesValidator("emailValidator")
public class EmailValidator implements Validator { }
My problems are:
1.) If I use an ordinary f:validator, like the one I use above and then use c:if to enable/disable it, then it will not work. According to some articles I've read it's because f:validator validates on build time, not on render time.
2.) If I use o:validator, it works but the problem is every time you hit submit a new line of invalid email error is added to p:messages. Example I clicked submit button 3 times, then I get 3 times the email error.
Any idea?
More info (anatomy of the project)
Example I have a page user with field email, it will include the following custom components:
+user.xhtml
+formPanel
+formField (this is where the validator is defined)
+formButtons (the action button)
+p:messages is defined
user.xhtml
<formPanel>
<formField field="email" />
<formButtons />
</formPanel>
Command button is like (formButtons):
<p:commandButton id="saveButton" rendered="#{cc.attrs.edit}"
value="#{messages['action.save']}"
action="#{cc.attrs.backingBean.saveOrUpdate()}" icon="ui-icon-check"
ajax="#{cc.attrs.ajaxSubmit}">
<c:if test="#{cc.attrs.backingBean.lcid != null}">
<f:param name="cid" value="#{cc.attrs.backingBean.lcid}" />
</c:if>
</p:commandButton>
The p:messages as defined on formPanel:
<p:messages id="formMessages" showDetail="true" showSummary="false" redisplay="false"></p:messages>
Note:
1.) What I've noticed is that the validator is called n times, where n is the number of submit or click done.
xhtml - https://github.com/czetsuya/crud-faces/blob/master/crud-faces/src/main/webapp/administration/user/user.xhtml
the tags - https://github.com/czetsuya/crud-faces/tree/master/crud-faces/src/main/webapp/resources/tags
bean component - https://github.com/czetsuya/crud-faces/tree/master/crud-faces/src/main/java/org/manaty/view/composite
Seems like there's no chance for the f:validator so I push through o:validator and come up with a workaround. Need to catch if the error is already in the FacesMessages list:
boolean match = false;
for (FacesMessage fm : context.getMessageList()) {
if (fm.getDetail().equals(message)
|| fm.getSummary().equals(message)) {
match = true;
break;
}
}
if (!match) {
throw new ValidatorException(facesMessage);
}

why getQueryString() does not work in jsf backing bean with h:commandButton

I have build a login snippet of code that is on the top of menu bar. If a user is in any of the page by navigating and presses all of sudden the login button, I'll like to see that person authenticated and at the same time stay on the page where he originally comes from. so I used this on the backing bean:
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
then if there is let say mypage.htm?a=2&b=2 get a=2&b=2 with the request.getQueryString()
but getQueryString returns null, how can I can have the original URL entirely from the backing bean?
It returned null because the command button does not submit to an URL which includes the query string. Look in the generated HTML output of <h:form>. You'll see that generated HTML <form action> does not include the query string at all.
You need to pass the current query string yourself as a request parameter in the login link/button.
Grab the current request URI and query string and add it as from parameter in login link/button (note: use a normal link/button, it doesn't need to be a command link/button):
<h:button value="login" outcome="/login">
<f:param name="from" value="#{request.requestURI}#{empty request.queryString ? '' : '?'}#{request.queryString}" />
</h:button>
In login page, set the from parameter as view scoped bean property:
<f:metadata>
<f:viewParam name="from" value="#{login.from}" />
</f:metadata>
In login action method, redirect to it:
public void submit() throws IOException {
User user = userService.find(username, password);
if (user != null) {
// ... Do your login thing.
FacesContext.getCurrentInstance().getExternalContext().redirect(from);
} else {
// ... Do your "unknown login" thing.
}
}
<h:commandButton> sends a POST request to the server, more specifically to the Faces Servlet, and the JSF lifecycle starts. As you may know, you can't access to the query string parameters in a POST request.
In case you want to send a GET request from your form or retrieve the query string parameters when accessing to the page, you must map each expected query parameter using <f:viewParam>
<f:metadata>
<f:viewParam id="a" name="a" value="#{bean.a}" />
<f:viewParam id="b" name="b" value="#{bean.b}" />
</f:metadata>
More info:
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
ViewParam vs #ManagedProperty(value = "#{param.id}")
You can also solve this by changing the <h:form> wrapping the <h:commandButton> to an omnifaces form with includeRequestParams set to true: <o:form includeRequestParams="true">. See BalusC's response to this question.

Rerendering show/hide trick with AJAX (JSF+richfaces) only work for first record in a4j:repeat

For a while now, I've been working on a JAVA-based web project, and have found this website to be very helpful on numerous occasions.
So, 'got some problems of my own now - and would appreciate if you help out!
Ok, so Here's the thing -
I'm trying to render a list of messages, each of which consists of a message title and a message body. The trick I'm working on is that the message body, for as long as the title (which is an a4j:commandLink) hasn't been clicked-on, should be hidden. And once the title's clicked - the body should be displayed. And once its clicked again - hide. And so forth.
Here's what I did at the JSF side (some parts have been omitted for simplicity):
<a4j:repeat var="msg" value="#{ForumRenderJSF.messages}">
<a4j:region id="msgAjaxRegion" renderRegionOnly="true">
<a4j:outputPanel id="msgPanel" ajaxRendered="true">
<rich:panel style="width: 100%; border: 0">
<a4j:form id="msgForm">
<!--
The message's title.
Each click results in either the revealing or hiding of the message's body.
-->
<a4j:commandLink value="#{msg.title}" action="#{ForumRenderAssistJSF.reevaluateRender}"/>
<h:outputText value=" By: <i>#{msg.userNick}</i>, #{msg.timestamp}" escape="false"/>
<!--
The message's body.
-->
<!-- A (textual) flag, indicating whether the body should be rendered. -->
<h:inputText id="renderBodyFlag"/>
<br/>
<!-- The body. -->
<a4j:outputPanel rendered="#{rich:findComponent('renderBodyFlag').value == true}">
<h:outputText value="#{msg.body}"/>
</a4j:outputPanel>
</a4j:form>
</rich:panel>
</a4j:outputPanel> <!-- msgPanel -->
</a4j:region>
</a4j:repeat>
Note the usage of:
1. A dummy "renderFlag" field (should be hidden, eventually), which value denotes whether the body should be rendered.
2. A backing bean for rendering assistance (ForumRenderAssistJSF); It goal is to flip the proper renderFlag's value from "true" to "false", and vice-versa.
3. An a4j:region to isolate each message when firing the request for ForumRenderAssistJSF.reevaluateRender() -- so that the bean can find the right "renderFlag" field.
As for the bean:
public class ForumRenderAssistJSF {
public void reevaluateRender()
{
FacesContext context = FacesContext.getCurrentInstance();
UIViewRoot root = context.getViewRoot();
UIComponent renderFlagComp = (new UIComponentLookup()).lookup(root, compLookup); // My recursive search
String renderFlagVal = (String) ((HtmlInputText)renderFlagComp).getValue();
if (!renderFlagVal.equals("true"))
{
((HtmlInputText)renderFlagComp).setValue("true");
}
else
{
((HtmlInputText)renderFlagComp).setValue("false");
}
}
}
AND THE PROBLEM IS:
The trick actually works -- but only for the first message in the list!
For the rest of them, I see that the server can reach the right renderFlag input-text component (tested by inserting values at the client), but for some reason - the client always renders it blank (no content) upon AJAX reply!
I tried digging deep inside richfaces tutorials and manuals, and to me it seems like everything is as it should be. So, I'm kind'a lost here, and as I said - would deeply appreciate your help in regards!
Thanks!
Have you tried using a rich:simpleTogglePanel? It seems to provide all the functionality you need.

How to display my application's errors in JSF?

In my JSF/Facelets app, here's a simplified version of part of my form:
<h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
I'd like to be able to assign an error to a specific h:message tag based on something happening in the continueButton() method. Different errors need to be displayed for newPassword and newPassword2. A validator won't really work, because the method that will deliver results (from the DB) is run in the continueButton() method, and is too expensive to run twice.
I can't use the h:messages tag because the page has multiple places that I need to display different error messages. When I tried this, the page displayed duplicates of every message.
I tried this as a best guess, but no luck:
public Navigation continueButton() {
...
expensiveMethod();
if(...) {
FacesContext.getCurrentInstance().addMessage("newPassword", new FacesMessage("Error: Your password is NOT strong enough."));
}
}
What am I missing? Any help would be appreciated!
FacesContext.addMessage(String, FacesMessage) requires the component's clientId, not it's id. If you're wondering why, think about having a control as a child of a dataTable, stamping out different values with the same control for each row - it would be possible to have a different message printed for each row. The id is always the same; the clientId is unique per row.
So "myform:mybutton" is the correct value, but hard-coding this is ill-advised. A lookup would create less coupling between the view and the business logic and would be an approach that works in more restrictive environments like portlets.
<f:view>
<h:form>
<h:commandButton id="mybutton" value="click"
binding="#{showMessageAction.mybutton}"
action="#{showMessageAction.validatePassword}" />
<h:message for="mybutton" />
</h:form>
</f:view>
Managed bean logic:
/** Must be request scope for binding */
public class ShowMessageAction {
private UIComponent mybutton;
private boolean isOK = false;
public String validatePassword() {
if (isOK) {
return "ok";
}
else {
// invalid
FacesMessage message = new FacesMessage("Invalid password length");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(mybutton.getClientId(context), message);
}
return null;
}
public void setMybutton(UIComponent mybutton) {
this.mybutton = mybutton;
}
public UIComponent getMybutton() {
return mybutton;
}
}
In case anyone was curious, I was able to figure this out based on all of your responses combined!
This is in the Facelet:
<h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" id="newPassword1Error" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" id="newPassword2Error" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
This is in the continueButton() method:
FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));
And it works! Thanks for the help!
You also have to include the FormID in your call to addMessage().
FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));
This should do the trick.
Regards.
Remember that:
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage( null, new FacesMessage( "The message to display in client" ));
is also valid, because when null is specified as first parameter, it is applied to the whole form.
More info: coreservlets.com //Outdated
JSF is a beast. I may be missing something, but I used to solve similar problems by saving the desired message to a property of the bean, and then displaying the property via an outputText:
<h:outputText
value="#{CreateNewPasswordBean.errorMessage}"
render="#{CreateNewPasswordBean.errorMessage != null}" />
Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.
I tried this as a best guess, but no luck:
It looks right to me. Have you tried setting a message severity explicitly? Also I believe the ID needs to be the same as that of a component (i.e., you'd need to use newPassword1 or newPassword2, if those are your IDs, and not newPassword as you had in the example).
FacesContext.getCurrentInstance().addMessage("newPassword1",
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Message"));
Then use <h:message for="newPassword1" /> to display the error message on the JSF page.
Simple answer, if you don't need to bind it to a specific component...
Java:
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Authentication failed", null);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);
XHTML:
<h:messages></h:messages>

Resources