How to access POST parameters when validation failed - jsf

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.

Related

How to call listener or backing bean method after completing a javascript call in jsf?

According to my scenario, Need to invoke the javascript first. After the javascript call two hidden values will be updated. With the updated hidden values , have to call Bean method. In this scenario, I am getting called javascript and bean method at the same time. So In my bean method, I am not getting the updated values in the hidden fields.
Little bit detail explanation
Textbox(address) is used to type address. And having two hidden elements which will used to store street name and city name based on the address field.
By the Javascript call, Collecting two values (Street name and City name) from the google maps API (codeAddress()). Based on the entered address in the textbox updating the two hidden fields(street and city). Bean method has to handle With the updated hidden values.
But From my code, Backing bean and the java script is called simultaneously. So I am not getting the Updated value in the Backing Bean.
My code is following :
JSF CODE
<h:form prependId="false">
<div id="panel-one">
<h:outputLabel value="ADDRESS"/>
<h:inputText type="text" id="address" size="40" value="#{Bean.address}"/>
<h:inputHidden id="street" value="#{Bean.streetName}" />
<h:inputHidden id="city" value="#{Bean.city}" />
<h:commandButton type="submit" value="Verify Address"
onclick="checkAddress()">
<f:ajax execute="#form" render="#none" listener="#{Bean.checkAddress()}"/>
</h:commandButton>
</div>
</h:form>
Javascript
checkAddress() {
document.getElementById("street").value = //Setting value from other javascript API;
document.getElementById("city").value = //Setting value from other javascript API;
}
In the above javascript collecting values and setting it with two textbox. With the updated values again calling the checkAddress() method in backing bean. FYI : *checkAddress()* is a AJAX CALL. I am doing mistake in h:commandButton of JSF , but dont know how to fix it. Any help is much appreciated.
There're several things odd with your provided code:
I don't see a need for prependId
Defining onclick on a commandButton is a bad idea[tm]
You're setting yourself and/or the person inheriting that code up for a headache by having a JS function and a bean method both called checkAddress
You don't seem to do anything based upon the fired action? (having render="#none")
That said, a kind of hack that should do what you need is hiding the actual button and clicking it programmatically:
<h:form id="addrF">
<h:outputLabel value="ADDRESS"/>
<h:inputText type="text" id="address" size="40" value="#{bean.address}"/>
<button class="clickMe">Verify Address</button>
<h:inputHidden id="street" value="#{bean.streetName}" />
<h:inputHidden id="city" value="#{bean.city}" />
<h:commandButton id="submitBtn" style="display:none;">
<f:ajax execute="#form" render="#none" listener="#{Bean.checkAddress()}"/>
</h:commandButton>
</h:form>
<h:outputScript>
$(".clickMe").click(function(ev) {
ev.preventDefault();
$.getJSON(
"https://maps.googleapis.com/maps/api/geocode/json",
{ address : $("#addrF\\:address").val() },
function(data) {
// set street, city
$('#addrF\\:submitBtn').click();
}
);
});
</h:outputScript>
You probably want additional value validation, etc. and your access to the maps API might be different (I haven't used it at all). The point is: you need to click() on the hidden commandButton only after your ajax call completed.
Please try using event="" in f:ajax and then use onevent to call javascript function.
Event value would be "click" and onevent value would be name of javascript function. like
You could try to set a Delay for the JavaScript setTimeout()
<h:commandButton type="submit" value="Verify Address"
onclick="setTimeout(function(){checkAddress()},1000);">
1000 miliseconds = 1 second, you just change that value for your convenience

<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();}"/>

Javascript error in XHTML page in JSF 2

I have the following code in an xhtml page in JSF 2. But when the page loads I get an javascript error that
document.getElementById("country") is null or not an object.
Why is this happening?
<h:form>
<h:panelGrid columns="2">
Selected country locale :
<h:inputText id="country" value="#{country.localeCode}" size="20" />
Select a country {method binding}:
<h:selectOneMenu value="#{country.localeCode}" onchange="submit()"
valueChangeListener="#{country.countryLocaleCodeChanged}">
<f:selectItems value="#{country.countryInMap}" />
</h:selectOneMenu>
<script>
alert("hi");
document.getElementById("country").disabled=true;
</script>
</h:panelGrid>
</h:form>
It's not finding your component. Since your <h:inputText> is inside of an <h:form> the id will have the following pattern
formName:componentName. Since you did not specify an id for <h:form>, JSF will generate one for you. That's why you are seeing j_id1926454887_72d35e53:country where j_id1926454887_72d35e53 is the form id. If you want to deal with simpler id, then you should add an id value to your <h:form>. For example
<h:form id="form">
<h:inputText id="country" value="#{country.localeCode}" size="20" />
</h:form>
The id for <h:inputText> will now be form:country.
Even simpler, you could simply add prependId = "false" to your form
<h:form prependId="false">
and now your id for <h:inputText> will simply be country.
How can I get this id dynamically?
I'm going to modify your code slightly to achieve what you want (I'm thinking that you want to disable the input based on a specific event). Consider this simpler example
<h:form>
<h:inputText id="country" value="#{country.localeCode}" size="20" onclick="disableInputText(this.form)" />
</h:form>
Here I'm attaching a javascript function to an HTML DOM Event handler. In this case, I want the input to be disabled when I click on it (hence onclick). I'm also passing the form as a reference in the function. Then, define your Javascript like this.
<script>
function disableInputText(form) {
form[form.id + ":country"].disabled = true;
}
</script>
We simply grab the input in the javascript with the corresponding id via the object form and set its disabled attribute to true. (You can sort of view the form object as Map).
Also check the link below for more attributes of <h:inputText> and the different handlers you can use (the ones with on as prefix).
inputText Tag Attribute.
Also, check out the answer with the most votes to get a bigger picture on how ids are generated and other ways on how they can be determined.
How can I know the id of a JSF component so I can use in Javascript
It's seems to be a naming issue. the id of the field is not rendered as country.
i found a question that seems relevant. Composite components & ID

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">

When is a f:param actually sent?

I've got the following h:commandButton:
<h:commandButton action="#{myBean.myAction}" value="Send">
<f:param name="myFlag" value="true" />
</h:commandButton>
I want to gain access to myFlag insinde a Validator, that's attached to another element with f:validator.
Unfortunately, when I want to retrieve the parameter through the FacesContext, I only get null returned.
Is it that the parameters are only sent once all validators have been invoked?
The <f:param> inside <h:commandButton> is only supported since JSF 2.0, but you're using JSF 1.2. The <f:param> is then only supported in <h:commandLink>.
<h:commandLink action="#{myBean.myAction}" value="Send">
<f:param name="myFlag" value="true" />
</h:commandLink>
There are alternatives, such as a <h:inputHidden> or <f:setPropertyActionListener> or <f:attribute> or in this case perhaps just plain <input type="hidden"> (the hidden input component and the action listener will only set their value during update model values which is later than validations phase; the attribute tag has better to be set on the component which invokes the validator). As the functional requirement is unclear, it's not possible to suggest the best alternative.
Update as per the comments, apparently all you need to know is if the particular button is pressed or not; in that case just give it and the parent form a fixed ID
<h:form id="form">
<h:commandButton id="send" ...>
this way it will have a fixed request parameter name of form:send and you could check on that in the validator:
if (externalContext.getRequestParameterMap().containsKey("form:send")) {
// Send button is pressed.
}
You can by the way also check for that in the required validators as follows:
<h:inputText ... required="#{not empty param['form:send']}" />
See also:
Action dependent requireness

Resources