1
votes

I would like to allow user to select only a date or a range of dates. It's for and SQL search.

One date selected: I search the items with this date
Two dates selected: I search the items between these two dates

I'm using PrimeFaces 8.0. I would like to have only one field to do that.

2 options tested with <p:datePicker>:

  • selectionMode="multiple", great but i can't limit the number of date to maximum 2 dates. Not very user friendly too. Would be nice to be able to select only 2 dates, at the third date selected the 2 previous are unselected.
  • selectionMode="range", perfect to select two date, but if you selected only one date, it's not submitted to a backing bean, totally ignored. How can I submit just one date?
1
Not sure, but did you try with apart from using selectionMode="range", when you submit it then if second date is null or not selected, set a default date that you know means only 1 date was selected? Like for example set it to 1900/01/01, I know its more like a workaround but atleast you can start working on better solution - BugsForBreakfast
Hello @BugsForBreakfast thank you for your answer. You really helped me ! I wrote a JS code to set the same date than the first date selected as second date. I add it in the original post - Dorian Honoré
Glad to know it was helpfull :) thanks for sharing it - BugsForBreakfast

1 Answers

1
votes

This code will loop over all primefaces widgets on the page. If the widget is a datePicker, and has only one date selected, it will add the same date as second date.

for (var widgetVar in PrimeFaces.widgets) {
    
    try {

    var widget = PrimeFaces.widgets[widgetVar];

    if(widget.jq && widget.jq[0].classList.contains('p-datepicker')){
        var datePicker = PF('' + widget.widgetVar);
        console.log('datePicker found');
        console.log(datePicker);
        console.log('Date : ');
        console.log(datePicker.getDate());
       
        if(datePicker.getDate() && datePicker.getDate().length == 2 && datePicker.getDate()[1] == null){
            datePicker.setDate(datePicker.getDate()[0]);
        }
    }

    } catch (error) {
       console.error(error);
    }
    
}