DEV Community

Süleyman Özgür Özarpacı
Süleyman Özgür Özarpacı

Posted on

How to Trigger Upload Started/Finished Event in Component (FilamentPHP)

When writing custom components in Filament, it is sometimes necessary to interact with upload events. For example, you may want to deactivate the save button and display a "File Uploading" button. In the following code, I am using Alpine.js due to its compatibility with the TALL stack and its simplicity.

Firstly, we need to locate the form element. Since we are using Alpine.js, we perform this task within the init function. The code snippet below finds the closest form element and assigns it to the form variable in our Alpine.js data.

form: null,
init(){
    this.form = this.$el.closest('form');
},
Enter fullscreen mode Exit fullscreen mode

Next, we define two functions responsible for triggering the upload started and upload finished events.

setFormUploadStarted(){
    this.form.dispatchEvent(new Event('file-upload-started'))
},
setFormUploadFinished(){
    this.form.dispatchEvent(new Event('file-upload-finished'))
},
Enter fullscreen mode Exit fullscreen mode

Now we are ready to use these functions. For example, you can use them as follows:

async uploadVideoHandler(){
    this.setFormUploadStarted(); // Start upload
    try{
        ... // Perform Upload
    }
    catch(e) {
        ...
    }
    finally {
        this.setFormUploadFinished(); // Finish upload
    }
},
Enter fullscreen mode Exit fullscreen mode

You can effortlessly interact with upload events, providing better control over the upload process and enhancing the user experience. Customize the code snippets to suit your specific needs and enjoy.

Top comments (0)