Group elements for a single ajax call in event="change" - ajax

I have a form with inputs to fill customer data with name surname and id
name surname lastName
[ ] [ ] [ ]
id other fields
[ ] [ ]
Inputs are defined as usually:
<p:inputText id="name" required="true" value="#{contactForm.name}" label="Name" styleClass="form-control">
<p:clientValidator/>
</p:inputText>
<p:message for="name" />
When id field is filled I make an ajax call to see if data corresponds with a customer in this way:
<p:outputLabel for="ID" value="ID" />
<p:inputText id="ID" required="true" value="ID" label="ID" styleClass="form-control">
<p:ajax
event="change"
listener="#contactController.identifyCustomer(contactForm)}"
process="#this name,surname1,surname2"
update="newCustomerPanel"
/>
<p:clientValidator/>
</p:inputText>
<p:message for="dni" />
In the happy case user introduces all data in a correct way this works nice.
My problem comes when the ajax call is executed with no data retrieved and the user needs to change some of the inputs, if the event needs to be launched user must pass through id input field change data and return which is not the way.
Now is working with workaround: inserting an ajax call to all fields involved. When any input launches event, in server side I check if all data is complete and has changed to call the service that retrieves customer data...
But honestly, this is an ugly solution that wastes lot of calls and does not give a good user experience.
So I was wondering, is there a way group all fields and assign the ajax call and event="change" to this group?

Ajax tag can be used as a wapper for multiple components:
<f:ajax event="change">
<h:input value... />
<h:input value... />
<h:input value... />
</f:ajax>

Related

PrimeFaces password validation

I have some trouble understanding this PrimeFaces showcase:
<h:panelGrid columns="2" id="matchGrid" cellpadding="5">
<h:outputLabel for="pwd1" value="Password 1: *" />
<p:password id="pwd1" value="#{passwordView.password5}" match="pwd2" label="Password 1" required="true" />
<h:outputLabel for="pwd2" value="Password 2: *" />
<p:password id="pwd2" value="#{passwordView.password5}" label="Password 2" required="true" />
</h:panelGrid>
In particular, I do not understand, why the value binding of both input fields point to the same property password5.
If I follow this example, but add some validation for password strength
#StrongPassword
private String password5;
I get duplicated validation messages on this constraints (for both fields). This is not the intended behaviour, I'd expect
the content of the first input field to be validated for password strength and
the content of the second input field to be validated for equality with the content of the first field
How to achieve this?
As there doesn't seem to be a need to record the second input in the view bean, I didn't add another property for it and just removed the value binding:
<p:password id="pwd2" label="Password 2" required="true" />
This gives the desired result. The content of the second field is also preserved on validation errors.
The best way to validate two passwords to equals in Primefaces <p:password component is to use attribute match, you could put it to your main input password input form and indicate id of your second checking input form (Id of another password component to match value against - from Primefaces docs).
Let me show you an example:
<h:panelGrid columns="2" id="matchGrid" cellpadding="5">
<p:outputLabel for="usPassword" value="Password:"/>
<p:password id="usPassword" value="#{authBean.password}"
required="true" placeholder="Password"
requiredMessage="Error: enter your password"
match="usPasswordConfirm"/>
<p:outputLabel for="usPasswordConfirm" value="Repeat Password:"/>
<p:password id="usPasswordConfirm" value="#{signupBacking.password}"
required="true" placeholder="Repeat Password"
requiredMessage="Error: repeat your password"/>
</h:panelGrid>
Here I used match="usPasswordConfirm" and the same id value has the second password input form, so Primefaces will check both typed values for a match

Mutually exclusive input fields with JSF and PrimeFaces

I have a PrimeFaces application where I would like to make two input text fields mutually exclusive: the user should fill either field, but not both.
In the following example, the user could search contacts either by phone number or by email.
<h:form>
<h:outputLabel>Phone Number:
<h:inputText id="phoneInput" value="#{contactSearch.phone}"
disabled="#{not empty contactSearch.email}">
<p:ajax event="keyup" update="emailInput"/>
</h:inputText>
</h:outputLabel>
<h:outputLabel>Email Address:
<h:inputText id="emailInput" value="#{contactSearch.email}"
disabled="#{not empty contactSearch.phone}">
<p:ajax event="keyup" update="phoneInput"/>
</h:inputText>
</h:outputLabel>
<!-- Possibly other fields... -->
<h:commandButton value="Search" action="#{contactSearch.search}"/>
</h:form>
Is this the proper way to do it? I am concerned about:
Possible "deadlock" issues, where both fields end up being disabled
The whole form being submitted and/or valdiated in the Ajax request, when I just would like to update the disabled state of the input field
Missing some predefined PrimeFaces control which does all the work :)
This is not trivial in standard JSF. JSF utility library OmniFaces has a validator for exactly this purpose, the <o:validateOne>.
<h:inputText id="email" ... />
<h:inputText id="phone" ... />
<o:validateOne components="email phone" />
However, in UX perspective, you'd better redesign your form to provide a single UISelectOne component to select the type and a single UIInput field to enter the value. E.g.
<h:selectOneRadio ... value="#{bean.type}">
<f:selectItem itemValue="email" />
<f:selectItem itemValue="phone" />
</h:selectOneRadio>
<h:inputText ... value="#{bean.value}" />
Update: as server side validation is not affordable and you'd really like to disable the the other without making much ajax traffic, your only bet is using pure JavaScript/jQuery for the job (if necessary in combination with server side validation as fallback).
Here's a generic jQuery based approach:
<h:inputText styleClass="onlyone" a:data-onlyone="groupName" />
<h:inputText styleClass="onlyone" a:data-onlyone="groupName" />
...
$(document).on("input", ":input.onlyone", function() {
var $this = $(this);
var $others = $("[data-onlyone='" + $this.data("onlyone") + "']").not($this);
$others.val(null).attr("disabled", !!$this.val());
});
The data-onlyone value should represent the group name, so you can have multiple of "only one" inputs throughout the document.

Validate two components with dynamic id

Here is what I am trying to do:
I have a form with multiple pairs of input fields and a save button.
When the save button is pressed then for each pair of input fields should be validated if they are numbers and if the left value is smaller than the right value.
If not the validation errors will be shown and if it is the case a dialog will pop up to ask for the name under which it should be saved.
Here is what I got so far:
<h:form>
<ui:repeat value="#{myBean.someList}" var="elem">
<h:inputText id="min#{elem.id}" value="#{elem.minimum}" />
<h:inputText id="max#{elem.id}" value="#{elem.maximum}" />
<br />
<h:message for="min#{elem.id}" style="color:red" />
<h:message for="max#{elem.id}" style="color:red" />
</ui:repeat>
<h:commandButton value="save">
<f:ajax execute="#form" render="#form updateValidationFailedFlag"
onevent="
function(ajaxResult){
if(ajaxResult.status=='success' && !globalValidationFailedFlag)
showSaveDialog();
}"
/>
</h:commandButton>
<h:outputScript id="updateValidationFailedFlag">
globalValidationFailedFlag = #{facesContext.validationFailed};
</h:outputScript>
</h:form>
This works but doesn't check if the minimum is smaller then the maximum.
It will validate the input (checks if the input are integer) and shows the save dialog if no validation error occured.
To check if the minimum is smaller then the maximum I tried to follow the tutorial at http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/
Variant 1 adds a listener after the validation is done and is able to add error messages that are shown in the browser. But that doesn't count as a validation failure and doen't set the facesContext.validationFailed flag.
Variant 2 writes a custom validator for one component and gives the other component as parameter to that validator. That would look something like this:
<f:validator validatorId="myValidator" />
<f:attribute name="maximum" value="#{max#{elem.id}}" />
That is not really valid EL and I don't know how to write it correctly.
What can I do to validate if each of those min-max pairs is valid
You don't need #{elem.id} here. The <ui:repeat> already takes care of that. It would be evaluated to an empty string anyway when JSF needs to set the id attribute.
<ui:repeat value="#{myBean.someList}" var="elem">
<h:inputText id="min" value="#{elem.minimum}" />
<h:inputText id="max" value="#{elem.maximum}" />
<br />
<h:message for="min" style="color:red" />
<h:message for="max" style="color:red" />
</ui:repeat>
As to the validation, just pass the value of the other component along:
<h:inputText id="min" binding="#{min}" value="#{elem.minimum}" />
<h:inputText id="max" value="#{elem.maximum}">
<f:validator validatorId="myValidator" />
<f:attribute name="min" value="#{min.value}" />
</h:inputText>
Note that I moved the validator to the second component. Otherwise it would be still invoked if the second component didn't pass conversion.
If you happen to use JSF utility library OmniFaces, then you could use its <o:validateOrder> instead.
<h:inputText id="min" value="#{elem.minimum}" />
<h:inputText id="max" value="#{elem.maximum}" />
<o:validateOrder components="min max" showMessageFor="min" />
See also:
How to use EL with <ui:repeat var> in id attribute of a JSF component
JSF doesn't support cross-field validation, is there a workaround?

RichFaces: partial form validation

I have a form containing several fields(name, surname, etc) and a datatable. Datatable is dedicated to store addresses into the backing bean. A person can have more than one address so I add a button as follows:
<a4j:commandButton action="#{bean.addAddressRow}" value="Add address" reRender="addresses" />
where "addresses" is the id of my datatable. I use a4j because there's no need to refresh the page.z
What I want to do is to skip the validation of the entire form except the address fields when this button is pressed. So a user can add one more address if all the previous addresses are correctly filled. The other fields should not be validated.
Is it possible to do?
Wrap your address table and the commandButton with <a4j:region> tags and set the attribute renderRegionOnly to true. Look at following example. Here only the last two text boxes (txt2 and txt3) are validated when you press the first button. If you press the second button all three text boxes are validated.
<h:form>
<h:inputText required="true" id="txt1"/>
<rich:message for="txt1" style="color:red"/>
<a4j:region renderRegionOnly="true">
<h:inputText required="true" id="txt2"/>
<rich:message for="txt2" style="color:red"/>
<h:inputText required="true" id="txt3"/>
<rich:message for="txt3" style="color:red"/>
<a4j:commandButton value="Ok1" />
</a4j:region>
<a4j:commandButton value="Ok2" />
</h:form>

How to let validation depend on the pressed button?

I have created form and I want to show previous existing items on a table while a new one is creating. I'd like to show matching items as form is filling up. But when I try to filter the list without having the form completed, the validation messages appear and the table doesn't get updated.
Don't know if it's possible, but what I want to do something like this:
<h:form id="form">
<h:outputText value="Name: "/>
<p:inputText value="#{itemsBean.name}" id="name" required="true"/>
<br/>
<h:outputText value="Description: "/>
<p:inputText value="#{itemsBean.description}" id="description" required="true"/>
<p:commandButton value="Save" update="form" actionListener="#{itemsBean.save}"/> //validate and save
<p:commandButton value="Filter" update="form" actionListener="#{itemsBean.updateItemsList}"/> //don't validate, and update the table.
<p:dataTable id="list" value="#{itemsBean.itemsList}" var="item">
<p:column>
<h:outputText value="#{item.name}"/>
</p:column>
<p:column>
<h:outputText value="#{item.description}"/>
</p:column>
</p:dataTable>
</h:form>
I'm very new to JSF.
I understand that you want to filter based on the name input field. The <p:commandButton> sends by default an ajax request and has a process attribute wherein you can specify which components you'd like to process during the submit. In your particular case, you should then process only the name input field and the current button (so that its action will be invoked).
<p:commandButton process="#this name" ... />
The process attribute can take a space separated collection of (relative) client IDs of the components, wherein #this refers to the current component. It defaults in case of <p:commandButton> to #form (which covers all input fields of the current form and the pressed button), that's why they were all been validated in your initial attempt. In the above example, all other input fields won't be processed (and thus also not validated).
If you however intend to skip the required validation for all fields whenever the button in question is been pressed, so that you can eventually process multiple fields which doesn't necessarily need to be all filled in, then you need to make the required="true" a conditional instead which checks if the button is been pressed or not. For example, let it evaluate true only when the save button has been pressed:
<p:inputText ... required="#{not empty param[save.clientId]}" />
...
<p:inputText ... required="#{not empty param[save.clientId]}" />
...
<p:commandButton binding="#{save}" value="Save" ... />
This way it won't be validated as required="true" when a different button is pressed. The trick in the above example is that the name of the pressed button (which is essentially the client ID) is been sent as request parameter and that you could just check its presence in the request parameter map.
See also:
Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
I Have tested this with non-ajax submits:
<p:inputText ... required="#{not empty param.includeInSave1}" />
...
<p:inputText ... required="true" />
...
<p:commandButton value="Save1" ajax="false">
<f:param name="includeInSave1" value="true" />
</p:commandButton>
<p:commandButton value="Save2" ajax="false" />
The first input is required validated only on Save1 button submit.
Additionally to the BalusC answer (very useful and complete) I want to add that when you use a <h:commandButton /> it will validate (required, custom validations) all the fields in the <h:form /> where the command button is located, therefore when you need to use more than one command button you could consider that it is a good practice to use different <h:form /> to different responsibilities to avoid unexpected behavior in submit actions of the command buttons.
It is well explained in a BalusC answer: Multiple h:form in a JSF Page
If your form has validations and you do not update the <h:form /> or you do not show messages, you could get a headache thinking that the <h:commandButton /> is not firing your action, but likely is a validation problem that has not been shown.
Change your filter commandbutton like this to ignore validation:
<p:commandButton value="Filter" update="list" actionListener="#{itemsBean.updateItemsList}" process="#this"/>
EDIT:
The related post on SO, I think this will solve your issue too
JSF 2.0: How to skip JSR-303 bean validation?

Resources