Star-based rating input

The rating component provides star-based rating with the ability to select and cancel.

How to do it…

The basic declaration for the component would be as follows:

<p:rating value="#{ratingBean.rate}" />

Here, the rate value binding is a java.lang.Integer definition. The default visual of the component will be as shown in the following screenshot:

How to do it…

The stars attribute sets the number of stars to display with a default value 5.

There's more…

With the readonly attribute, it's possible to only display the value output of the component by disabling user interaction. When set to true, the cancellation button will also not be rendered on the left-hand side of the component.

When the disabled attribute is set to true, the rating component will act the same as when the readonly attribute is set to true, but the color of the stars will get faint, as seen in this screenshot:

There's more…

Note

Currently, the rating component does not support half or quarter values.

AJAX behavior events

It is also possible to invoke a server-side method instantly when the user rates or cancels the rating. The rating component provides two AJAX behavior events for this, rate and cancel.

A sample definition that updates the growl component with AJAX behavior would be as follows:

<p:rating id="instantRating" value="#{ratingBean.rate}">
  <p:ajax event="rate" listener="#{ratingBean.handleRate}"
    update="growl" />
  <p:ajax event="cancel" listener="#{ratingBean.cancelRate}"
    update="growl" />
</p:rating>

The handleRate method gets org.primefaces.event.RateEvent, as shown in the following code snippet, despite the cancelRate method that has no arguments. The rating is contained in rateEvent and can be retrieved as an object with the getRating() method:

public void handleRate(RateEvent rateEvent) {
  Integer rate = (Integer) rateEvent.getRating();
  MessageUtil.addInfoMessage("rating.selected", rate);
}
public void cancelRate() {
  MessageUtil.addInfoMessage("rating.cancelled");
}

PrimeFaces Cookbook Showcase application

This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on every Servlet 3.x compatible application server, such as JBoss WildFly or Apache TomEE.

The showcase for the recipe is available under http://localhost:8080/pf-cookbook/views/chapter3/rating.jsf.

See also

For details about the MessageUtil class, see the Internationalization (i18n) and Localization (L10n) recipe in Chapter 1, Getting Started with PrimeFaces.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.133.180