0

I am working with JSF and Primefaces. I want to show some rows of a datatable with a different background color depending on a condition. That condition is if a date () is greater or equal than current date that rows must be shown with a color especified in the CSS file. How can I get the current date?

This is the Facelet

<p:dataTable id="dataTableCitizens" rowStyleClass="#{item.dateLastDate ge currentDate ? 'colored' : null}" value="#{citizensManagedBean.listCitizens}"  var="item">

This is the CSS

.colored {
background-color: yellow;
}

I have created a faces-config.xml file inside WEB-INF with the following code:

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.0"
              xmlns="http://java.sun.com/xml/ns/javaee" 
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

    <managed-bean>
    <managed-bean-name>currentDate</managed-bean-name>
    <managed-bean-class>java.util.Date</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

, but when I run the web app it gives me a java.lang.NullPointerException. What am I doing wrong?

josh23
  • 1
  • 1
  • 6

2 Answers2

1

The most basic solution is to create a variable in your bean and initiate it with a @PostConstruct annotation :

private Date currentDate;

@PostConstruct
public void init() {
     currentDate = new Date();
}

//Getter and Setters...

Then you can access it in your view : #{yourBean.currentDate}

Or you can use Omnifaces' default implementation of #{now}.

Thrax
  • 1,926
  • 1
  • 17
  • 32
  • correct, but this bean should better be application scoped, or there will be many currentDate instances around. – tt_emrah Oct 24 '14 at 12:08
0

what Thrax is suggesting is right but not complete. If you want to have the date using Primefaces or JSF you will have to set that code like this:

Firstly we're going to create a java class and call currentDate or getMyDate, no matter how you want to name it. Then paste the Thrax construct. Plus you'll have to add it @ManagedBean upper to you class.

We add ManagedBean in order to call it the class in JSF. Now if you go to ur JSF and type #{curr....} (ctrl+space) you will be able to see your class a bean, but when you try to call the attribute currentDate it wont appear. So what you need to do is just create Get and Set methods. Finally you will call SetCurrentDate method in init constructor giving it the variable currentDate as parameter and that's it. You just will have to call again this attribute in the JSF you need to, this time it will appear and it will be shown in your page.

This class you look like this

currentdate