Turbo stream replace - how to render javascript on modal

I have a modal form that has some date and time fields in it that use flatpickr. I am submitting the form and doing a turbo stream replace. When there are form validation errors it replaces the form and displays the errors, but the flatpickr fields get wiped out back to regular text fields. I’m not sure how to tell the modal or turbo stream to load those fields again on replace.

<%= turbo_stream.replace “new_detail”, partial: “details/form”, locals: { detail: @detail } %>

Any ideas?

Flatpickr is initialized in packs/application.js

document.addEventListener(“turbo:load”, function() {
flatpickr("[data-behavior=‘flatpickr’]", {
altInput: true,
altFormat: “F j, Y”,
dateFormat: “Y-m-d”,
})

$( ‘.flatpickr1’ ).flatpickr({
enableTime: true,
noCalendar: true,
dateFormat: “H:i”,
time_24hr: true
});
$( ‘.flatpickr2’ ).flatpickr({
enableTime: true,
noCalendar: true,
dateFormat: “H:i”,
time_24hr: true
});
})

That depends on how you’re initializing Flatpickr in the first place. You’ll need to add an event/mutation observer of some sort that can recognize that the page has changed, and trigger that initialization routine again. The DOM has changed, so anything that needs to run at page load needs to run again.

Walter

Just updated my original post. The boxes are initialized in packs/application.js. How / where would an event mutation observer go?

Take a look at GitHub - adrienpoly/stimulus-flatpickr: A modest, yet powerful wrapper of Flatpickr 📆 for Stimulus

If your turbo-stream returns the text input with this stimulus controller, then it re-initializes itself when it’s re-added to the page.

<%= f.text_field :my_date,
    data: {
      controller: "flatpickr",
      flatpickr_date_format: "Y-m-d",
      flatpickr_min_date: Time.zone.now
    } %>

Awesome. Thanks! I got it working great with that gem.