Search code examples
javajsfjsf-2primefaces

Unable to take PrimeFaces p:rating value and save it into the Oracle database


I would like to use p:rating component, to vote and save the value into the database (if it is already voted to be able to extract the value from the db later). In the Entity i have also comments fields and i would like if comments are already written to add only the vote so i sometimes i make merge instead of persist (if there is nothing for this request written in the DB). I have the following code in my .xhtml page:

<h:form
        rendered="#{not empty userRequestBean.request.hiredAgency.city}">
        <p:rating value="#{userRequestBean.rating}" stars="10"
            onRate="#{userRequestBean.rateAgency()}">
        </p:rating>
    </h:form>

In my bean I have:

@ManagedBean(name = "userRequestBean")
@SessionScoped
public class UserRequestBean implements Serializable {
    private Integer rating; // Plus get and set methods
    private TComment agencyComment = new TComment();
    public void rateAgency() {
        if (rating == null) return;
        EntityManager em = HibernateUtil.getEntityManager();
        if (!em.getTransaction().isActive())
            em.getTransaction().begin();
        Query queryAgencyComment = em.createQuery("select comment "
                + "from TRequest req join req.requestComments comment "
                + "where req.id = :requestId ");
        Long requestId = (Long) request.getId();
        queryAgencyComment.setParameter("requestId", requestId);
        agencyComment = (TComment) queryAgencyComment.getSingleResult();

        if (agencyComment.equals(null)) {
            agencyComment = new TComment();
            agencyComment.settRequest(request);
            agencyComment.setCommentDate(new Date());
            agencyComment.setAssessment(rating);
            em.persist(agencyComment);
            em.getTransaction().commit();
        } else {
            agencyComment.setAssessment(5);
            em.merge(agencyComment);
            em.getTransaction().commit();
        }
    }

But onRate, the method rateAgency is not executed. It is executed only once when the page is rendered. How can i implement this working?


Solution

  • The attribute onRate defines a JavaScript (client side) action, whilst you are trying to run a server method. You need an ajax action instead:

    <p:rating value="#{userRequestBean.rating}" stars="10" >
        <p:ajax event="rate" listener="#{userRequestBean.rateAgency()}" />
    </p:rating>
    

    Useful links: