highlight specific dates (values from bean)

2019-07-03 16:23发布

问题:

Using the primefaces <p:calendar> component, I need to highlight certain dates. I am aware of its beforeShowDate attribute, but the dates to be highlighted need to be fetched from the backing bean.

Using a <h:inputHidden value="#{bean.theDates}" /> results in a single String value containing comma separated Date Strings.

How can I set a styleClass for a given list of dates (in my bean)?

回答1:

Use an EL expression to output the dates from your bean as an array in your beforeShowDay JavaScript function. The function should check if the date is in your array, if it is set the correct CSS class in the returned array.

The output of #{bean.theDates} could be ['2014-01-01','2014-02-01'], and your JavaScript function would look something like this:

JavaScript in head of page:

<script>
    function highlightDays(date) {
        var dates = #{bean.theDates};
        var cssclass = '';
        for (var i = 0; i < dates.length; i++) {
            if (date === new Date(dates[i])) {
               cssclass = 'mycss';
            }
        }
        return [true, cssclass];
    }
</script>

PrimeFaces Calendar:

<p:calendar beforeShowDate="highlightDays" />