Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 - auto submit form after file upload with managed_file type

I got a form with only one field. This field is of the type 'managed_field'. When you click the "Upload" button a progress bar will show you the progress of the file upload. After that you will need to submit the form to save the file.

Since the progress bar won't show up when you select a file and then click the form submit button instead of the "Upload" button. I would like to trigger a form submit after the upload (via the "Upload" button) has completed.

My current form looks like this:

$form['#attributes'] = array('enctype' => "multipart/form-data");

$form['pdf_upload'] = array(
    '#title' => t('Upload PDF'),
    '#type' => 'managed_file',
    '#required' => TRUE,
    '#progress_message' => t('Please wait...'),
    '#progress_indicator' => 'bar',
    '#upload_validators' => array(
        'file_validate_extensions' => array('pdf'),
    )

);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
);

The file module handles the files via an ajax callback to the file/ajax/* uri. The callback returns ajax commands.

Basically i want to add an extra ajax command that triggers the form submit after the upload of the file has completed.

like image 237
J Schut Avatar asked Nov 03 '22 19:11

J Schut


1 Answers

@Clive That wasn't an option for me since I wanted the users to start the upload themselves. You answer gave me some ideas though and I came up with the following solution.

Drupal.behaviors.fileUpload = {
    attach: function(context, settings) {
        jQuery("body").ajaxComplete(function(event,request, settings){
            // Only do something when on the orders page of a user
            // This is where I use the upload functionality
            if(window.location.pathname.match(/user\/\d+\/orders/)) {
                // Check if the AjaxComplete was triggered by the managed file upload
                // pdf_upload_XXX is my form name
                // Get the form-build-id from the URL
                if (form_build_id = settings.url.match(/file\/ajax\/pdf_upload_\d*\/(.*)$/)) {
                    // Check if the upload has completed by checking if there is a Delete button in the form that has the form-build-id
                    if(jQuery('[value="'+form_build_id[1]+'"]').closest('form').find('[id$=remove-button]').length) {
                        // Click the submit button
                        jQuery('[value="'+form_build_id[1]+'"]').closest('form').find('[id^=edit-submit]').click();
                    }
                }
            }   
        });

    }
}

Hope this is usefull for other users also.

Thnx Clive for setting me on the right path.

like image 55
J Schut Avatar answered Nov 15 '22 09:11

J Schut