0

I'm working on a datatable in which a single column contains various fields like

  • Name
  • Salary
  • Date
  • Birth

So I took datatype as String in my bean for that column.

Now my concern is, can I use p:calendar for date of birth with datatype String in my bean?

If so then how?

Dylan Slabbinck
  • 836
  • 1
  • 15
  • 27
Akash D
  • 15
  • 7
  • the problem with String is : You can not expect the user input type information example User A : `10/11/2016` and User B : `11/10/2016`, User C `Wed 13,11,2016` did you get the point – Yagami Light Dec 08 '16 at 14:54
  • 1
    Sounds like a bad choice.. why not use real good types and take a different approach – Kukeltje Dec 08 '16 at 21:03
  • @Kukeltje what different approach,could you please be more specific.I need some string fields like name and some date fields in the same column – Akash D Dec 09 '16 at 11:35
  • That is next to impossible since I do not see the problem with using multiple different fields with different types in one colum. – Kukeltje Dec 09 '16 at 17:38

1 Answers1

1

Use a FacesConverter

Proof of concept:

@Named
public class DateStringConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
        SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return parser.parse(arg2);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
        return arg2.toString();
    }

}

xhthml

<p:calendar value="#{dateAsString}" pattern="yyyy-MM-dd" converter="#{dateStringConverter}" />
jklee
  • 1,958
  • 2
  • 10
  • 22
  • and how do you handle the case of `MM.DD.YYYY` – Yagami Light Dec 08 '16 at 15:05
  • I don't understand. This isn't a valid pattern. Do you know the p:calendar component? – jklee Dec 08 '16 at 15:11
  • please read this post http://stackoverflow.com/questions/12575990/calendar-date-to-yyyy-mm-dd-format-in-java and read my comment you will understand that if the date is in `String` user can input every/anything inside it – Yagami Light Dec 08 '16 at 15:15
  • p:calendar validate the user input. I have changed my answer to a FacesConver. – jklee Dec 08 '16 at 15:17
  • @jklee i didn't get it..how can i use the facesConverter and after implementing it, will i be able to use p:calendar with datatype string in bean? – Akash D Dec 08 '16 at 17:07