Search code examples
javascripttwigflatpickr

Setting minDate with a variable with flatpickr


Couldn't find any answers on related threads or on the flatpickr documentation so posting here hoping for a miracle.

I'm using flatpickr and have to set a minDate based on a variable.

var $date = $('#calendar').data('date');
console.log ($date); // this will return the correct value

$("#calendar").flatpickr( {
    altInput: true,
    altFormat: "F j, Y",
    dateFormat: "Ymd",
    minDate:  $date , 
    maxDate: new Date().fp_incr(60), // 60 days from now
    disableMobile: "true",
    });

And on my page I have

<input id="calendar" placeholder="Pick a date" data-date="{{ "now"|date("Ymd") }}" >

I'm using twig so my console.log will return today's date but it has no impact on the minDate. In the future the minDate will not be today's date, I just used it to test.

In an older version of flatpickr you could set these types of variables directly in instead of in the js code, but it seems like it's unfortunately not in use anymore.


Solution

  • According to flatpickr documentation

    Date Strings, which must match the dateFormat chronologically
    YYYY-MM-DD HH:MM

    So, "now"|date("Ymd") is invalid, try "now"|date("Y-m-d")

    https://flatpickr.js.org/examples/#supplying-dates-for-flatpickr