Search code examples
javascriptmeteormeteor-autoformsweetalert

How to wait for user response on Meteor AutoForm submission?


I am using Meteor and Aldeed's Autoform. I want to check that the user is certain before submission takes place. I have tried many things but when I press the button, the form submits anyway. Here's what I have now, which produces a modal nicely (with SweetAlert) even though submission occurs in the background anyway:

AutoForm.hooks({
    createEventForm: {
        before: function() {
            this.event.preventDefault();
        },
        beginSubmit: function() {
            this.event.preventDefault();
            swal({
                title: "Are you sure?",
                text: "You will not be able to recover this imaginary file!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: true },
                function(){
                swal("Deleted!", "Your imaginary file has been deleted.", "success"); });
        },

How can I make the form wait for the user to confirm or cancel the operation?

Thanks!


Solution

  • The beginSubmit is called at the beginning of the form submission. As the documentation states, it can be used to disable/enable buttons or showing a wait message when submitting longer requests. If you want to display a confirmation message and submit the form depending on the user's decision, you need to use the before hook.

    For example:

    AutoForm.hooks({
      createEventForm: hooksObject
    });
    
    var hooksObject = {
      before: {
        insert: function(doc) {
          var self = this;
          swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: true
          }, function(isConfirm) {
            if (isConfirm) {
              /* Submit form: */
              self.result(doc);
              swal("Deleted!", "Your imaginary file has been deleted.", "success");
            } else {
              /* Async cancel form submission: */
              self.result(false);
            }
          });
        }
      }
    }