validate-store.js 2.48 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
    'jquery',
    'jquery/ui',
    'mage/dataPost',
    'mage/backend/validation',
    'Magento_Ui/js/modal/confirm'
], function ($, jqueryUi, dataPost, validation, modalConfirm) {
    'use strict';

    $.widget('mage.storeValidation', {

        /**
         * Validation creation
         * @protected
         */
        _create: function () {
            var form = this.element[0],
                validator = $.data(form, 'validator');

            if (validator && validator.settings) {
                validator.settings.submitHandler = this._saveHandler;
                validator.settings.confirmCallback = this._needConfirm;
                $.extend(validator.settings, this.options);
                $.data(form, 'validator', validator);
            }
        },

        /**
         * Check is it need to show confirmation popup
         *
         * @returns {Boolean}
         */
        _needConfirm: function () {
            return true;
        },

        /**
         * Save form with confirmation if needed
         *
         * @param {Object} form
         * @private
         */
        _saveHandler: function (form) {
            var formData = {},
                requestData = {},
                options = $.data(form, 'validator').settings;

            if ($(form).validation('isValid')) {
                $.each($(form).serializeArray(), function () {
                    formData[this.name] = this.value || '';
                });
                requestData = {
                    action: $(form).attr('action'),
                    data: formData
                };

                if (options.confirmCallback.call(this)) {
                    modalConfirm({
                        title: $.mage.__('Warning message'),
                        content: $.mage.__('This operation can take a long time'),
                        actions: {
                            /**
                             * 'Confirm' action handler.
                             */
                            confirm: function () {
                                $('body').trigger('processStart');
                                dataPost().postData(requestData);
                            }
                        }
                    });
                } else {
                    dataPost().postData(requestData);
                }
            }
        }
    });

    return $.mage.storeValidation;
});