I have two requirements for my InputText:
- value of the p:inputText should be immediately displayed on screen in h:outputText with keyup-event
- the value should be unique in database
I'm using Primefaces 4.0, JSF 2.2 with Glassfish 4 and Java 7
My code looks like this at the moment
Example.xhtml
<h:form>
<p:inputText id="value" value="#{myBean.value}" >
<p:ajax event="keyup" update="example" process="@this" />
<f:validator binding="#{uniqueValueValidator}" />
</p:inputText>
<h:outputText id="example" value="#{myBean.value}">
<p:commandButton value="Save" action="#{myBean.saveValue}"/>
</form>
MyBean.java
@Named
@RequestScoped
public class MyBean {
@Inject
private DBService service;
private String value;
//getter, setter
public String saveValue() {
service.saveValue(value);
return "showall";
}
}
UniqueValueValidator.java
@Named
public class UniqueValueValidator implements Validator {
@Inject
private DBService service;
@Override
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException {
if(service.isValueNotUnique(value.toString()) {
// throw ValidatorException
}
}
}
My problem is now, that on every keyup-event the value is validated and a call to the database is made. But I want to validate the value only when the form is submitted.
My first solution was to move the validation into the saveValue
method.
public String saveValue() {
if(service.isValueNotUnique(value) {
// add a FacesMessage
return null;
} else {
service.saveValue(value);
return "showall";
}
}
But here I think it is not good practice to mix validation code and logic code in one method.
So I hope you have a nicer solution for me ;)