Completed
Push — master ( fb754a...2a3626 )
by Antonio
03:49
created

BaseForm.extend.getPostRoute   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
'use strict';
2
3
define(
4
    [
5
        'jquery',
6
        'underscore',
7
        'oro/translator',
8
        'backbone',
9
        'routing',
10
        'pim/form',
11
        'pim/form-builder',
12
        'pim/user-context',
13
        'oro/loading-mask',
14
        'pim/router',
15
        'oro/messenger',
16
        'flagbit/template/product/clone-modal'
17
    ],
18
    function (
19
        $,
20
        _,
21
        __,
22
        Backbone,
23
        Routing,
24
        BaseForm,
25
        FormBuilder,
26
        UserContext,
27
        LoadingMask,
28
        router,
29
        messenger,
30
        template
31
    ) {
32
        return BaseForm.extend({
33
            config: {},
34
            template: _.template(template),
35
            globalErrors: [],
36
            /**
37
             * {@inheritdoc}
38
             */
39
            initialize(meta) {
40
                this.config = meta.config;
41
                this.globalErrors = [];
42
                BaseForm.prototype.initialize.apply(this, arguments);
43
            },
44
            getFieldsFormName() {
45
                if (this.getRoot().model.has('parent')) {
46
                    return this.config.variantFormName;
47
                }
48
                else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
49
                    return this.config.productFormName;
50
                }
51
            },
52
53
            render() {
54
                this.$el.html(this.template({
55
                    modalTitle: __(this.config.labels.title),
56
                    subTitle: __(this.config.labels.subTitle),
57
                    content: __(this.config.labels.content),
58
                    picture: this.config.picture,
59
                    errors: this.globalErrors
60
                }));
61
62
                return FormBuilder.build(this.getFieldsFormName()).then(form => {
63
                    this.addExtension(
64
                        form.code,
65
                        form,
66
                        'fields-container',
67
                        10000
68
                    );
69
                    form.configure();
70
                    this.renderExtensions();
71
                    return this;
72
                });
73
            },
74
75
            /**
76
             * Opens the modal then instantiates the creation form inside it.
77
             * This function returns a rejected promise when the popin
78
             * is canceled and a resolved one when it's validated.
79
             *
80
             * @return {Promise}
81
             */
82
            open() {
83
84
                const deferred = $.Deferred();
85
                const modal = new Backbone.BootstrapModal({
86
                    content: '',
87
                    cancelText: __('pim_enrich.entity.create_popin.labels.cancel'),
88
                    okText: __('pim_enrich.entity.create_popin.labels.save'),
89
                    okCloses: false
90
                });
91
92
                modal.open();
93
                modal.$el.addClass('modal--fullPage');
94
95
                const modalBody = modal.$('.modal-body');
96
                modalBody.addClass('creation');
97
98
                this.setElement(modalBody);
99
                this.render();
100
101
                modal.on('cancel', () => {
102
                    deferred.reject();
103
                    modal.remove();
104
                });
105
106
                modal.on('ok', this.confirmModal.bind(this, modal, deferred));
107
108
                return deferred.promise();
109
            },
110
111
            /**
112
             * Confirm the modal and redirect to route after save
113
             * @param  {Object} modal    The backbone view for the modal
114
             * @param  {Promise} deferred Promise to resolve
115
             */
116
            confirmModal(modal, deferred) {
117
                this.save().done(entity => {
0 ignored issues
show
Unused Code introduced by
The parameter entity is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
118
                    modal.close();
119
                    modal.remove();
120
                    deferred.resolve();
121
122
                    router.redirectToRoute(this.config.editRoute);
123
                    messenger.notify('success', __(this.config.successMessage));
124
                });
125
            },
126
127
            /**
128
             * Save the form content by posting it to backend
129
             *
130
             * @return {Promise}
131
             */
132
            save() {
133
                const loadingMask = new LoadingMask();
134
                this.$el.empty().append(loadingMask.render().$el.show());
135
136
                let data = $.extend(this.getFormData(),
137
                    this.config.defaultValues || {});
138
139
                if (this.config.excludedProperties) {
140
                    data = _.omit(data, this.config.excludedProperties)
141
                }
142
143
                return $.ajax({
144
                    url: Routing.generate(this.getPostRoute()),
145
                    type: 'POST',
146
                    data: JSON.stringify(data)
147
                }).fail(function (response) {
148
                    if (response.responseJSON) {
149
                        this.globalErrors = response.responseJSON.values;
150
                        this.render();
151
                    }
152
                }.bind(this))
153
                    .always(() => loadingMask.remove());
154
            },
155
            getPostRoute() {
156
                if (this.getFormData().type === 'model') {
157
                    return this.config.postProductModelRoute;
158
                } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
159
                    return this.config.postProductRoute;
160
                }
161
            }
162
        });
163
    }
164
);
165