So I have a form page for Orders
, and I implemented Files Upload using Active Storage
, and also Implemented Drag and Drop feature called Filepond
using importmap
and javascript
However when I start my rails server using rails s
and navigate to the form page, Filepond
does not appear (Drag n Drop feature)
NOW when I refresh the page, then it loads up the Filepond
NOW again when I navigate to some other page and come back to the form, the filepond does not load
app/javascript/application.js
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "bootstrap"
import "custom/custom"
import "filepond"
import "filepond-plugin-image-preview"
app/javascript/custom/custom.js
// Import FilePond
import * as FilePond from 'filepond';
// Import the plugin code
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
// Register the plugin
FilePond.registerPlugin(FilePondPluginImagePreview);
// Get a reference to the file input element
const inputElement = document.querySelector('#files-upload');
// Create a FilePond instance
const pond = FilePond.create(inputElement, {
credits: {},
storeAsFile: true,
allowMultiple: true,
allowReorder: true,
});
views/orders/_form.html.erb
<%= form_with(model: order) do |f| %>
.......
.......
<%= f.file_field :files, multiple: true, direct_upload: true,
required: true, id:"files-upload" %>
........
........
<% end %>
CONCLUSION:
Every time I navigate to the form page, I will have to refresh the page once in order for the filepond's drag n drop feature
to work
so is there any way to fix this in rails 7 so that we never need to refresh the page for filepond
to work??
Ok, so I got to know the problem, the problem lies with JavaScript, Since Rails 7 uses Turbo to handle JavaScript, we need to use Event "turbo:load"
provided by Turbo Hotwire,
turbo:load
fires once after the initial page load, and again after every Turbo visit. Access visit timing metrics with the event.detail.timing object.source: https://turbo.hotwired.dev/reference/events
custom.js
// Import FilePond
import * as FilePond from 'filepond';
// Import the plugin code
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
// Register the plugin
FilePond.registerPlugin(FilePondPluginImagePreview);
document.addEventListener("turbo:load", loadFilePond);
function loadFilePond(){
// Get a reference to the file input element
const inputElement = document.querySelector('#files-upload');
// Create a FilePond instance
const pond = FilePond.create(inputElement, {
credits: {},
storeAsFile: true,
allowMultiple: true,
allowReorder: true,
});
}