Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally color the background in a table cell?

I am rendering a table with p:dataTable (PrimeFaces) and what I want to do is color the background of cells depending on the value of their content. This is different from coloring a row or a column -- it is the individual cell.

First a CSS problem. If I do this:

                    <p:column headerText="xyzzy">
                        <div style="background-color: green">
                            <h:outputText value="#{rowVar.anumber}" >
                                <f:convertNumber groupingUsed="true" />
                            </h:outputText>                        
                        </div>
                    </p:column>

the background color just of the content gets set, not the whole cell. In other words the padding is still the default.

Second, I want to make the style string a variable expression. I can add a function to the backing bean, but how do I access the table content in the method? Will this work?

<div style="#{bean.computeCSS(rowVar.number}">

EDIT:

I figured out a way to do the conditional part, but I still need help with the CSS part. My solution looks like:

                    <p:column headerText="xyzzy">
                        <div class="#{rowVar.anumber gt 0 ? 'colored' : ''}">
                            <h:outputText value="#{rowVar.anumber}">
                                <f:convertNumber groupingUsed="true" />
                            </h:outputText>                        
                        </div>
                    </p:column>

Although I dislike getting to fancy in EL, this has the advantage of not needed a backing bean method.

However I still only get the background color set, not the whole cell.

like image 890
AlanObject Avatar asked Mar 11 '12 16:03

AlanObject


2 Answers

You can add a css class to the row and to the column too, that identifies a cell. Use the dataTable's rowStyleClass attribute (example). If you want to color multiple rows:

<p:dataTable value="#{bean.rows}" var="rowVar"
     rowStyleClass="#{rowVar.firstCol gt 0 ? 'firstColColored' : ''}
                           #{rowVar.secondCol gt 0 ? 'secondColColored' : ''}">
     <p:column styleClass="firstCol">...
     <p:column styleClass="secondCol">

css:

.firstColColored .firstCol {
     background: pink;
}
like image 180
Adam Avatar answered Oct 07 '22 05:10

Adam


how about adding padding to your class , with px or percents...

something like this

.colored{
    background-color:yellow;
    padding-top:25px;
    padding-bottom:25px;
    padding-right:50px;
    padding-left:50px;
}
like image 42
Daniel Avatar answered Oct 07 '22 05:10

Daniel