add general message when validation failed - jsf

I have a form with all kind of fields and for each field I have a validator and p:message attached when validation failed.
I need to add a message at top of the page\form with custom text(something like: "please fix all problem in form") only if I have a validation failure(I don't want to use growl).
how do I set the custom message and how do I trigger it to show(it is not attached to a specific field).
I'm using JSF 2 and primeface 3.4.

You can place
<h:panelGroup id="my_custom_error_msg">
<h:outputText value="Please fix all problem in form"
rendered="#{facesContext.validationFailed}"/>
</h:panelGroup>
And render it upon form submit, for example:
<h:commandButton value="Submit">
<f:ajax render="#form my_custom_error_msg" execute="#form"/>
</h:commandButton>
If you also have some homemade validation and messages sent from your bean to your page you can extend the rendered condition into
rendered="#{facesContext.validationFailed or not empty facesContext.messageList}"

Related

How to access POST parameters when validation failed

I need to show the response page depending on some of the input fields. E.g. the tabid inputHidden below:
#{controllerBean.tabId}
...
<h:form id="edit">
<h:inputHidden value="#{controllerBean.tabId}" id="tabid" />
<h:inputText value="#{controllerBean.name}" id="name" />
</h:form>
But when some other input in the same form has validation error (e.g. the "name" inputText). The "controllerBean.tabId" value will not be assigned because JSF returns at validation stage.
I still need the tabId to show the page correctly and having 2 ideas in mind:
#{param['edit:tabid']}
or use binding:
#{tabId.value}
<h:inputHidden value="#{controllerBean.tabId}" id="tabid" binding="tabId" />
My question is, which of these 2 is the better or Best Practice? Or there are even better ways to do this?
update:
Note. In my specific case, the tabid is set by client javascript.
Server reply with a few items in the html.
Javascript put these items into different tabs on the page.
One of the tabs POST data to server with the current tabid in the form.
So my server need to know the tabid to show the response page with the correct tab selected.
You can add a lifecycle event listener to the component and pick the value from it. I'm going to recommend the preValidate listener:
<h:form id="edit">
<h:inputHidden value="#{controllerBean.tabId}" id="tabid">
<f:event type="preValidate" listener="#{controller.grabTabId}"/>
</h:inputHidden>
<h:inputText value="#{controllerBean.name}" id="name" />
</h:form>
This registers the listener to fire just before the validation phase of the request. You'll now have a listener defined in your backing bean to look like:
public void grabTabId(ComponentSystemEvent cse){
//obtain a reference to the component
HtmlInputHidden hiddenElement = (HtmlInputHidden)cse.getComponent();
//get the value from the component.
String hiddenValue = hiddenElement.getValue();
}
<h:form id="edit">
<h:inputHidden value="#{controllerBean.tabId}" id="tabid" />
<h:inputText value="#{controllerBean.name}" id="name" >
<p:ajax process="tabid" immediate="true" event="keyup" />
</h:inputText>
</h:form>
The above code will do is when the user put some value the value will be processed and will be set the managedBean. that what you want I think.
Another non-perfect way of accomplishing this is to move the validation logic to your action method. If validation fails, you just stop processing (and add an applicable FacesMessage). You just need to be aware that all model values will have been updated, and you can clear them if necessary.
Since updating model values on failed validation goes against the JSF lifecycle, I think any solution will be somewhat of a hack.

<p:commandButton CONDITIONAL onclick event

i have a jsf-form with an input field and a save-button as seen in the code below. What i want to achieve is, when the save-button clicked, the input should be validated with the regex-pattern. If the validation failed, no save-confirmation-dialog should be shown. Otherwise a save-confirmation-dialog shown, and let the user to choose if to save or not.
In the code below, the dialog has always been shown, despite the conditional onclick="if(#{conditionOK}). I want no confirmation-dialog got shown, when conditionOK returns false!!! After many tries, i think the facescontext.isValidateFailed() will not be re-evalutated.
Please help :(
All what i want, is only to check, if the regex-Validator returns true. For this case, the confirmation-dialog should be shown.
My approach could be wrong. Many thank if you guys have also other solutions.
<h:form id="save_all_form">
<p:inputTextarea rows="1" style="width:100%;resize:none"
value="#{cusBean.saveAll}" autoResize="false"
validatorMessage="Wrong format">
<f:validateRegex pattern="#{msgs.pattern}" />
</p:inputTextarea>
<ui:param name="conditionOK"
value="#{facesContext.postback and !facesContext.validationFailed}" />
<p:commandButton value="#{msgs.button_overwrite_all}"
onclick="if(#{conditionOK}){confirmation.show()}"/>
</h:form>
I do not think that the JSF-validation is the way to go for you. It is intended to prevent the change of model data in the case, that the validation fails.
And if you would like to make a check in JavaScript you have to update the section in HTML. JavaScript does not reevaluate the Expression, so the value when the view was rendered the first time will be used everytime.
Try the following in the xhtml:
<h:form id="save_all_form">
<p:inputTextarea id="input" rows="1" style="width:100%;resize:none"
value="#{cusBean.saveAll}" autoResize="false">
<p:ajax global="false" update="input submit" partialSubmit="true"/>
</p:inputTextarea>
<p:commandButton id="submit" value="#{msgs.button_overwrite_all}"
onclick="if(#{cusBean.validate(msgs.pattern)}){confirmation.show()}"/>
</h:form>
And add this method in CusBean:
public boolean validate(String pattern) {
return getSaveAll().matches(pattern);
}
The result will be, that there is not JSF validation which takes place and the value of the textArea is submitted everytime you change it. Plus the commandButton-section is updated so the condition will be updated.
Like the other answer explained onclick event is too early to check the validation status of a JSF request(using !facesContext.validationFailed) because the request has not been submitted yet; Validation has not been run so the validation status will always be false (well, sort of) during onclick.
So what you'll want to do is carry out an ajax validation of the field (like shown in the earlier answer) and then use the primefaces args variable to check the status of the request:
<p:commandButton value="#{msgs.button_overwrite_all}" id="createReport" onclick="if(!args.validationFailed){confirmation.show();}"/>

Restrict f:validator on a specific submit button alone

I'm having a JSF form in which I have a textarea and multiple buttons.
For the text area I'm doing validation using f:validator
<f:validator validatorId="myValidator" />
<a4j:support event="onsubmit" ajaxSingle="true" process="textarea1" />
The validator is working as expected. Now i have multiple submit buttons on the page i want the validation to happen on specific button only and validator should be ignored on the remaining buttons.
Is there anyway to restrict the validator on a specific submit button alone. Thanks.
You can use the disabled attribute.
<f:validator validatorId="myValidator" disabled="#{empty param['formId:buttonId']}" />
Where formId is the ID of your <h:form> and the buttonId is the ID of the button which is supposed to be the only button to trigger validation.
I assume that you want to submit the textarea value to the server when clicking on other buttons too (so no point of playing with the process attribute)
How about adding immediate="true" to the other buttons ?
That way they will skip validation, while the submit button without immediate="true" will do the validation as expected
Or
There seems another workaround in this article JSF 2 - Conditionally Skip Validation
Something like
<h:commandButton action="#{bean.someMethod"} value="Submit2">
<f:param name="skipValidation" value="true"/>
</h:commandButton>
and inside the validate method of the validator check for the skipValidation attirbute (look for further explanation in the article...)

JSF 2 - No way to do Required Inputs + Clear (Immediate) Button?

This question is similar to the question here but that solution doesn't work here.
Take this simple-to-the-max example:
<h:form>
<h:inputText required="true" value="#{mrBean.someValue}" />
<h:inputText required="true" value="#{mrBean.someValue2}" />
<h:commandButton value="Submit">
<f:ajax execute="#form" />
</h:commandButton>
<h:commandButton immediate="true" action="#{mrBean.clearAllValues}" value="Clear">
<f:ajax render="#form" />
</h:commandButton>
</h:form>
And the bean Code:
public void clearAllValues() {
setSomeValue(null);
setSomeValue2(null);
}
Take this scenario:
Enter 'X' value in first input
Submit it using the 'Submit' Button. (failed in validation)
Enter 'Y' into the same input.
Click the 'Clear' button.
Result: Inputs don't clear and value of first input returns to 'X'.
I would expect this scenario to clear the input values but it doesn't, instead, it restores 'X' which is the previously submitted value. It actually never really runs mrBean.getSomeValue() on the bean (Which would have returned null and clear the input field)
The problem is related to JSF not working well with required fields and immediate. I wonder if anyone managed to overcome this problem.
Thanks!
Ben.
Your code example is oversimplified. The described problem symptoms will only occur when you have multiple required inputs. Add one more required input field to the example. Fill out only one of them. A validation error will occur for the empty one. Then enter something else in both and press clear. The valid input will indeed retain the previously submitted value.
This problem is described in detail in this question and this blog article. The solution boils down to collecting all to-be-cleared input components and calling EditableValueHolder#resetValue() on each of them. This can be done with a <f:actionListener> as shown in the blog article.
Another way in your particular case since you just want to clear out the entire form is to use a <h:button> which will basically just refresh the page. If your bean is request or view scoped then it will also be recreated with all properties set to default.
<h:form>
<h:inputText required="true" value="#{mrBean.someValue}" />
<h:commandButton value="Submit">
<f:ajax execute="#form" />
</h:commandButton>
<h:button value="Clear" />
</h:form>
Are you sure clearAllValues is executed? Do you get any errors in the logs or console?
Try adding execute
<f:ajax render="#form" execute="#this">

Validating a wrong date entry in rich faces

In one of our functionality we have some date fields for inline edit where we have enabled manual input. If in rich:calendar component, we manually enter improper date or junk data it will not even call the action method. As per our requirement we need to display an error message for date validation for these kind of fields. Is there any way to track that the date entered in the calendar field is improper with this component.
Code for the reference:
<rich:calendar id="actualOpeningDtCal" rendered="#{!empty aProgram.id}"
value="#{aProgram.actualOpeningDate}" placeholder="dd-mmm-yyyy"
inputSize="20" enableManualInput="true" datePattern="dd-MMM-yyyy"
buttonIcon="../content/images/calendar.png" showWeeksBar="false"
showFooter="false">
<a4j:support event="oninputblur" reRender="aList" ajaxSingle="false"
action="#{aController.inlineEdit}">
<f:setPropertyActionListener value="#{aProgram}"
target="#{aController.inLineEditaBean}" />
</a4j:support>
<a4j:support event="oncollapse" reRender="aList" ajaxSingle="false"
action="#{aController.inlineEdit}">
<f:setPropertyActionListener value="#{aProgram}"
target="#{aController.inLineEditaBean}" />
</a4j:support>
</rich:calendar>
If validation fails, then there are error messages. Perhaps you aren't showing them. Use <rich:messages> instead of <h:messages> to have them rendered on ajax response.
A bad practice, but might work, would be to use immediate="true" (bypasses validation) and then do the validation in the action method.

Resources