Monday, December 10, 2012

Using JSF date time converter inside Richfaces' tab labels

How many of you out there have tried using JSF's f:convertDateTime tag but ends in frustration?  It seems pretty easy and straightforward to use, however, it never seems to work the way you want it to, isn't it?

For those of you who are trying to use the tag but ends up pulling out your hair, you only need to remember one thing when using f:convertDateTime.  That is, make sure you are using the tag only for dates ONLY.

So, what do I mean by that?  For example, the tag does not work if you have something like the following:

 <h:outputText value="Date Created : #{object.dateCreated}"/>
   <f:convertDateTime pattern="MM/dd/yyyy" type="date"   dateStyle="short"/>
</h:outputText>


The above piece of code will not work because <h:outputText> contains a mixture of regular text strings and the date object.  The conversion will not happen because f:convertDateTime  could not detect the text to be of a date object.  When the above code is changed into the following it'll work just fine.
  
<h:outputText value="Date Created : "/>
<h:outputText value="#{object.dateCreated}">
   <f:convertDateTime pattern="MM/dd/yyyy" type="date"      dateStyle="short"/>
</h:outputText>


A couple days ago, I was trying to put some customized labels in .  As you know Richfaces' rich:tab has name and label attributes, which can be used for name of the tab and label display of the tab respectively.   I was in a situation where the label to be displayed depended on the  object.  

Let's say, if it's object A, I want the label to display 'A - 12/09/2012'.  For all the other objects, it'll just display B, C, D etc.

So, here's the code that I used to achieve it:

 <rich:tab name="name">
   <f:facet name="label">
     <h:panelGroup>
       <h:outputText value="#{object.label}" />
       <h:outputText value=" - " 

           rendered="#{object.label ==  'A'}" />
       <h:outputText value="#{object.dateCreated}" 
           rendered="#{object.label ==  'A'}">
          <f:convertDateTime pattern="MM/dd/yyyy" 

            type="date" dateStyle="short"/>
       </h:outputText>
    </h:panelGroup>
   </f:facet>
 </rich:tab>


For every object that is A, it'll display the name A and the date.  All other objects will be displayed the respective label of the object.

I've been trying to figure out how to display the tab's labels dynamically and it did not seem so hard.