All files / web/bundles/pimui/js/form/common/creation modal.js

95.65% Statements 44/46
83.33% Branches 15/18
83.33% Functions 5/6
95.65% Lines 44/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188    73x                                                             73x                 80x   80x             144x         144x   144x                     79x   79x               79x 79x     79x   79x         79x   79x                 79x 60x 60x 60x   60x   60x 1x         59x 17x   42x     60x   60x                         20x   20x 21x 3x     21x                   81x   81x 81x   81x     81x 8x     81x         20x 20x           20x       20x   81x          
'use strict';
 
define(
    [
        'jquery',
        'underscore',
        'oro/translator',
        'backbone',
        'routing',
        'pim/form',
        'pim/form-builder',
        'pim/user-context',
        'oro/loading-mask',
        'pim/router',
        'oro/messenger',
        'pim/template/form/creation/modal',
        'pim/common/property'
    ],
    function (
        $,
        _,
        __,
        Backbone,
        Routing,
        BaseForm,
        FormBuilder,
        UserContext,
        LoadingMask,
        router,
        messenger,
        template,
        propertyAccessor
    ) {
        return BaseForm.extend({
            config: {},
            template: _.template(template),
            validationErrors: [],
 
            /**
             * {@inheritdoc}
             */
            initialize(meta) {
                this.config = meta.config;
 
                BaseForm.prototype.initialize.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            render() {
                this.$el.html(this.template({
                    innerDescription: __(this.config.labels.content),
                    fields: null
                }));
 
                this.renderExtensions();
 
                return this;
            },
 
            /**
             * Opens the modal then instantiates the creation form inside it.
             * This function returns a rejected promise when the popin
             * is canceled and a resolved one when it's validated.
             *
             * @return {Promise}
             */
            open() {
                const deferred = $.Deferred();
 
                const modal = new Backbone.BootstrapModal({
                    title: __(this.config.labels.title),
                    subtitle: __(this.config.labels.subTitle),
                    picture: this.config.picture,
                    content: '',
                    okText: __('pim_common.save'),
                    okCloses: false,
                });
                modal.open();
                this.setElement(modal.$('.modal-body')).render();
 
                // TODO Find why this is used. Probably behats.
                modal.$('.modal-body').addClass('creation');
 
                modal.on('cancel', () => {
                    deferred.reject();
                    modal.remove();
                });
 
                modal.on('ok', this.confirmModal.bind(this, modal, deferred));
 
                return deferred.promise();
            },
 
            /**
             * Confirm the modal and redirect to route after save
             * @param  {Object} modal    The backbone view for the modal
             * @param  {Promise} deferred Promise to resolve
             */
            confirmModal(modal, deferred) {
                this.save().done(entity => {
                    modal.close();
                    modal.remove();
                    deferred.resolve();
 
                    let routerParams = {};
 
                    if (this.config.routerKey && this.config.entityIdentifierParamName) {
                        routerParams[this.config.routerKey] = propertyAccessor.accessProperty(
                            entity,
                            this.config.entityIdentifierParamName,
                            ''
                        );
                    } else if (this.config.routerKey) {
                        routerParams[this.config.routerKey] = entity[this.config.routerKey];
                    } else {
                        routerParams = {id: entity.meta.id};
                    }
 
                    messenger.notify('success', __(this.config.successMessage));
 
                    router.redirectToRoute(
                      this.config.editRoute,
                      routerParams
                  );
                });
            },
 
            /**
             * Normalize the path property for validation errors
             * @param  {Array} errors
             * @return {Array}
             */
            normalize(errors) {
                const values = errors.values || [];
 
                return values.map(error => {
                    if (!error.path) {
                        error.path = error.attribute;
                    }
 
                    return error;
                })
            },
 
            /**
             * Save the form content by posting it to backend
             *
             * @return {Promise}
             */
            save() {
                this.validationErrors = {};
 
                const loadingMask = new LoadingMask();
                this.$el.empty().append(loadingMask.render().$el.show());
 
                let data = $.extend(this.getFormData(),
                this.config.defaultValues || {});
 
                if (this.config.excludedProperties) {
                    data = _.omit(data, this.config.excludedProperties)
                }
 
                return $.ajax({
                    url: Routing.generate(this.config.postUrl),
                    type: 'POST',
                    data: JSON.stringify(data)
                }).fail(function (response) {
                    Eif (response.responseJSON) {
                        this.getRoot().trigger(
                            'pim_enrich:form:entity:bad_request',
                            {'sentData': this.getFormData(), 'response': response.responseJSON.values}
                        );
                    }
 
                    this.validationErrors = response.responseJSON ?
                        this.normalize(response.responseJSON) : [{
                            message: __('pim_enrich.entity.fallback.generic_error')
                        }];
                    this.render();
                }.bind(this))
                .always(() => loadingMask.remove());
            }
        });
    }
);