Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing h:datatable cell color or style dynamically in JSF

Tags:

datatable

jsf

I have a datatable where I want to change the color of a cell based on some analysis that is run on the contents. The table is linked to an array of Comment objects, which I have given a String cssClass that gets updated once the analysis is run. This is what I have tried plugging into the rowClasses property of the datatable. It's not working and I think the issue may be that I cannot access the variable created for each row of the datatable, from inside the datatable declaration.

Datatable code:

<h:dataTable value="#{post.comments}" var="comment" class="hs-table" rowClasses="#{comment.cssClass}" >
             <h:column>
                   #{comment.name}
             </h:column>
             <h:column>
                   #{comment.email}
             </h:column>
             <h:column>
                   #{comment.msg}
             </h:column>
 </h:dataTable>

The Comment class:

public class Comment {
private String msg;
private String email;
private String name;
private Date date;
private String cssClass;

public Comment(){
    cssClass = "normColumn";
}
epublic String getCssClass() {
    return cssClass;
}

public void setCssClass(String cssClass) {
    this.cssClass = cssClass;
}

}

Where the cssClass is updated in the managed bean:

if(tone>0)
            c.setCssClass("commentPos");
        else if(tone<0)
            c.setCssClass("commentNeg");

The class never gets assigned. Am I doing something wrong, or is this simply not possible?

like image 914
Webster Gordon Avatar asked Jun 14 '12 18:06

Webster Gordon


1 Answers

In the standard JSF <h:dataTable> component, the rowClasses attribute is unfortunately not evaluated on a per-row basis. It's evaluated on a per-table basis. Component libraries like Tomahawk and PrimeFaces however support the kind of attribute which you're looking for on their <t:dataTable> and <p:dataTable>.

With the standard JSF <h:dataTable> component you need to supply a comma-separated string of all row classes. This can look something like this:

public String getRowClasses() {
    StringBuilder rowClasses = new StringBuilder();

    for (Comment comment : comments) {
        if (rowClasses.length() > 0) rowClasses.append(",");
        rowClasses.append(comment.getCssClass());
    }

    return rowClasses.toString();
}

which is then to be referenced as

<h:dataTable ... rowClasses="#{post.rowClasses}">

See also:

  • <h:dataTable> tag documentation - lists all attributes and the accepted values
like image 195
BalusC Avatar answered Sep 22 '22 23:09

BalusC