Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to initialize datepicker in stimulus controller?

Lee Terng Gio asked in Javascript

I'm using datepicker and turbo frame. The datepicker is broken when the frame is replaced. I'm doing turbo:load in javascript file, it works when navigating between pages, but it will be broken when the form is replaced. I'm thinking to initialize datepicker in stimulus controller but I'm not familiar with stimulus. There aren't many documentation on stimulus, any idea?

Reply

Turbo:load runs when a page loads, not a frame. It's the same as the old turbolinks event. Frames are independent from page views which means you need to setup a Stimulus controller instead.

Check out stimulus-flatpickr and you won't have to build anything. 👍

https://github.com/adrienpoly/stimulus-flatpickr

Reply

For anyone digging into this as of Rails 7, there is a stimulus 3 support issue to deal with here.

Presently it requires a pin to beta version
bin/importmap pin stimulus-flatpickr@beta

You will also need to have some css references, such as to the latest version
<link rel="stylesheet" href="https://ga.jspm.io/npm:flatpickr@4.6.9/dist/flatpickr.min.css">
otherwise the input field will be deemed as readonly...

Reply

i tried all but in the end it breaks all bootstrap when i use flatpickr

Reply

Here is my solution: it also works well in Bootstrap modals. year option doesn't work well in modals, to solve the problem i have added the required code.

import Flatpickr from 'stimulus-flatpickr'
export default class extends Flatpickr {
connect() {
//global options
this.config = {
...this.config, //spread options in case some where defined in initialize
enableTime: false,
time_24hr: true
};
document.addEventListener("focusin", this.getFocus);
// document.addEventListener('focusin', (e) => {
// //not equal to null
// if (e.target.closest(".flatpickr-calendar") !== null) {
// e.stopImmediatePropagation();
// }
// });
//always call super.connect()
super.connect();
}
disconnect() {
document.removeEventListener("focusin", this.getFocus);
}
getFocus= (e) => {
if (e.target.closest(".flatpickr-calendar") !== null) {
e.stopImmediatePropagation();
}
}
// https://github.com/adrienpoly/stimulus-flatpickr
}

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.