CTOlet / yii2-attachments

Yii2 extension for uploading and attaching the files to the models
66 stars 57 forks source link

onclick method working only locally #13

Closed maxxer closed 9 years ago

maxxer commented 9 years ago

I was trying the suggested method to upload files on form submit but it doesn't seem to work. At least it does not on production server.

When I submit a form locally, even with a rather large file (5MB), the upload is very fast so it completes within milliseconds, even before the form submit.

When I do the same on the production server, which is much slower in bandwidth, the file upload starts but the form is submitted at the same time, so when the file send reaches say 5% the page is changed and upload interrupted.

The upload should probably be handled by returning false to the submit, and attach to file-input's filebatchuploadcomplete event in order to finally submit the form.

I tried this solution:

'onclick' => "function (e) {
    e.preventDefault();
    var element = this;
    $('#file-input').on('filebatchuploadcomplete', function(event, files, extra, element) {
        console.log('File batch upload complete');
        $(element).closest("form").submit();
    });

    $('#file-input').fileinput('upload');
};

But it won't work anyway. The upload seems to complete but it's not attached to the model. More details on the forum

CTOlet commented 9 years ago

I have no free time to help for you now. But I think that you go right way, problem is in onclick event.

maxxer commented 9 years ago

I ended up with something like this in the form:

<?php 
$this->registerJs("
    var formbutton = $('#formsubmit');
    formbutton.on('click', function(e) {
        $('#formsubmit').prop('disabled', true);
        e.preventDefault();
        $('#file-input').fileinput('upload');
    }); 

    $('#file-input').on('filebatchuploadcomplete', function(event, files, extra) {
        document.mioform.submit();
    });
");

Being formbutton the ID of the submit button, and mioform the name of the form. It still needs some enhancements, upload and validation errors are not handled

CTOlet commented 9 years ago

Fixed just now, please update and check how does it work

maxxer commented 9 years ago

working great, thanks! a little improvement: disable the submit button while uploading, and reenable in case of errors

maxxer commented 9 years ago

Error check is not perfect... For example if the uploaded files are bigger than max_post_size or max_upload_size an error is displayed in the widget, but the form is submitted anyway

CTOlet commented 9 years ago

Fixed on https://github.com/Nemmo/yii2-attachments/commit/f45842cdc6479affa0a06255b5a8f13b6e32d9f9, please test it