Thursday, June 6, 2013

How to Convert date in SelectOneMenu in jsf or primefaces

I found in internet many developers face same problem with the SelectOneMenu of Primefaces.Especialy when using date conversion.
The date is showen in the SelectOneMenu like this  :

Thu May 30 00:00:00 WET 2013

when using this code :

<p:selectOneMenu id="Dateplanif" value="#{ gestionduplanning.dateplanificationnew}"> 
      <f:selectItems value="#{gestionduplanning.datelist}" var="da" itemValue="#{da}" itemLabel="#{da}"  />  
 </p:selectOneMenu> 

The Solution that i found for this problem is to convert my date list to String then convert it back to date.
I will show you a sample example where you need to chose a date from a list of dates ,and after clicking on the button you will be redirected to the second jsf page that have the date that you chosed :

jsf managedbean :
public class Testbean {
    @EJB
    private ManageOfPlanifieLocal manageOfPlanifie;
    List<Date> listdate = new ArrayList<Date>();
    List<String> listdatestring = new ArrayList<String>();
    String newdate="";
    Date dateplanification;     
 @PostConstruct
    public void initialize() {
        listdate=manageOfPlanifie.retournerdatedesplanif();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");     
        for(int i=0;i<listdate.size();i++)
        {listdatestring.add(formatter.format(listdate.get(i)));}     
    }  
    public String gototest2(String datedate) throws ParseException  
    {dateplanification= new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH).parse(datedate);
        return "test2.xhtml?faces-redirect=true";
    }
The first jsf page that show the list of dates :
<h2>Choix de l'equipe</h2>  
         <h:outputLabel for="dateplanif" value="date de planification : " />
         <p:selectOneMenu id="dateplanif"  value="#{testbean.newdate}" >             
             <f:selectItems value="#{testbean.listdatestring}" var="da" itemValue="#{da}" itemLabel="#{da}" />  
    </p:selectOneMenu>           

      <p:commandButton value="suivant"  style="color:black;" action="#{testbean.gototest2(testbean.newdate)}" update="@form" />

The second jsf page show the value selected :

 <h:outputText value="Date : "/>   
 <h:outputText value="#{testbean.dateplanification}" />