Let's suppose that we have a rating system based on PrimeFaces Rating
component. Basically, we have three rating components that allows to the user
to express his opinion about the main shots of a tennis player: serve, forehand
and backhand. The user should rate at least one of these three shots. So, the
code without this restriction will look like this:
<h:form>
<p:messages/>
Rating Rafael Nadal favorite shots:
<p:panelGrid columns="2">
<p:outputLabel for="serveId"
value="Serve:"/>
<p:rating id="serveId"
value="#{playerBean.serve}" />
<p:outputLabel for="forehandId"
value="Forehand:"/>
<p:rating id="forehandId"
value="#{playerBean.forehand}"/>
<p:outputLabel for="backhandId"
value="Backhand:"/>
<p:rating id="backhandId"
value="#{playerBean.backhand}"/>
<p:commandButton value="Submit"
update="@form"/>
</p:panelGrid>
</h:form>
Further, we must ensure that the user will rate at least one type of
shots which involves some validators. A very quick approach consist in adding
into equation the OmniFaces ValidateOneOrMore
validator. This is just one of the suite of multi-field validators provided by
OmniFaces and it is capable to validate if at least ONE of the given UIInput components has
been filled out.
In order to use it, you need to add OmniFaces
into your application (this task is very easy to accomplish and similar with
PrimeFaces; you can simply copy the OmniFaces JAR into your application or use
the Maven dependency). Further, you have to know that ValidateOneOrMore
validator is exposed to page authors via <o:validateOneOrMore/> tag. This tag requires
an attribute named components
whose value is a string of components client IDs separated by space. The
referenced components enter into validation. For example, we have used it as
below:
<h:form>
<p:messages/>
Rating Rafael Nadal favorite shots:
<p:panelGrid columns="2">
<p:outputLabel for="serveId"
value="Serve:"/>
<p:rating id="serveId"
value="#{playerBean.serve}" />
<p:outputLabel for="forehandId"
value="Forehand:"/>
<p:rating id="forehandId"
value="#{playerBean.forehand}"/>
<p:outputLabel for="backhandId"
value="Backhand:"/>
<p:rating id="backhandId"
value="#{playerBean.backhand}"/>
<p:commandButton value="Submit"
update="@form"/>
<o:validateOneOrMore id="oneormore"
components="serveId forehandId backhandId" />
</p:panelGrid>
</h:form>
That's all! In the screenshots below, you can see how the validation
works:
Invalid case:
Valid cases:
The validation error message can be altered via the optional attribute, message or via message bundle. More details about using the OmniFaces multi-field validators are available here. You also may want to consider this SlideShare presentation.
The complete application from this post is available here.
Read more such goodies in:
Read more such goodies in:
Niciun comentariu :
Trimiteți un comentariu