Test Setup Failed
Push — master ( a95ce8...ffc4eb )
by
unknown
03:12
created

entity-component-view.js ➔ ... ➔ itemRender   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
define(function(require) {
2
    'use strict';
3
4
    var Backbone = require('backbone');
5
    var _ = require('underscore');
6
    var __ = require('orotranslation/js/translator');
7
    var EntityModel = require('./model');
8
    var componentTemplate = require('text!./templates/component.html');
9
    var entityTemplate = require('text!./templates/entity-item.html');
10
    var formTemplate = require('text!./templates/form.html');
11
    var entitySelectResultTemplate = require('text!./templates/select2/result.html');
12
    var entitySelectSelectionTemplate = require('text!./templates/select2/selection.html');
13
    var Select2Component = require('oro/select2-component');
14
15
    require('oroui/js/items-manager/editor');
16
    require('oroui/js/items-manager/table');
17
18
    var modes = {
19
        VIEW_MODE: 1,
20
        EDIT_MODE: 2
21
    };
22
23
    /**
24
     * @class   orochannel.entityManagement.EntityComponentView
25
     * @extends Backbone.View
26
     */
27
    return Backbone.View.extend({
28
        /**
29
         * Widget mode constants
30
         *
31
         * @const
32
         */
33
        MODES: _.clone(modes),
34
35
        /**
36
         * @type {function(Object)}
37
         */
38
        template: _.template(componentTemplate),
39
40
        /**
41
         * @type {function(Object)}
42
         */
43
        itemTemplate: _.template(entityTemplate),
44
45
        /**
46
         * @type {function(Object)}
47
         */
48
        formTemplate: _.template(formTemplate),
49
50
        /**
51
         * @type {object}
52
         */
53
        options: {
54
            data: [],
55
            mode: modes.VIEW_MODE,
56
            entityModel: EntityModel,
57
            metadata: null,
58
            lockedEntities: []
59
        },
60
61
        /**
62
         * @type {Backbone.Collection}
63
         */
64
        collection: null,
65
66
        /**
67
         * @type {jQuery}
68
         */
69
        $formContainer: null,
70
71
        /**
72
         * @type {jQuery}
73
         */
74
        $listContainer: null,
75
76
        /**
77
         * @type {jQuery}
78
         */
79
        $noDataContainer: null,
80
81
        /**
82
         * Initialize view
83
         *
84
         * @param {object} options
85
         */
86
        initialize: function(options) {
87
            this.options = _.defaults(options || {}, this.options);
88
            if (!this.options.metadata) {
89
                throw new Error('Missing "metadata" options for entity selection compoment');
90
            }
91
92
            var models = this.options.data.length > 0 ? _.map(this.options.data, _.bind(this._createModel, this)) : [];
93
            this.collection = this.collection || new (Backbone.Collection)(models, {model: EntityModel});
94
            this.listenTo(this.collection, 'add remove reset', this._onCollectionChange);
95
            this.listenTo(this.collection, 'add', this._onItemAdded);
96
        },
97
98
        /**
99
         * Renders component
100
         */
101
        render: function() {
102
            var templateContext = {__: __};
103
104
            this.$el.html(this.template(_.extend({}, templateContext)));
105
            this.$formContainer = this.$el.find('.form-container');
106
            this.$listContainer = this.$el.find('.grid-container');
107
            this.$noDataContainer = this.$el.find('.no-data');
108
109
            if (this.options.mode === modes.EDIT_MODE) {
110
                this.$formContainer.html(this.formTemplate(_.extend({}, templateContext)));
111
                _.defer(_.bind(this._initializeForm, this));
112
            }
113
114
            _.defer(_.bind(this._initializeList, this));
115
        },
116
117
        /**
118
         * Initialize form component
119
         *
120
         * @private
121
         */
122
        _initializeForm: function() {
123
            var configs = {
124
                placeholder: __('oro.channel.form.entity'),
125
                result_template: entitySelectResultTemplate,
126
                selection_template: entitySelectSelectionTemplate,
127
                data: _.bind(function() {
128
                    var notSelected = _.omit(this.options.metadata, this.collection.pluck('name'));
129
                    var options = _.map(notSelected, function(entityMetadata) {
130
                        return {
131
                            id: entityMetadata.name,
132
                            text: entityMetadata.label,
133
                            icon: entityMetadata.icon,
134
                            type: entityMetadata.type
135
                        };
136
                    });
137
                    var optionGroups = _.groupBy(options, function(entityMetadata) {
138
                        return entityMetadata.type;
139
                    });
140
                    var results = [];
141
142
                    _.each(_.keys(optionGroups).sort().reverse(), function(groupName) {
143
                        results.push({
144
                            text: __('oro.channel.entity_owner.' + groupName),
145
                            icon: null,
146
                            children: optionGroups[groupName]
147
                        });
148
                    });
149
150
                    return {results: results};
151
                }, this)
152
            };
153
            var $el = this.$formContainer.find('[data-purpose="entity-selector"]');
154
            var select2Component = new Select2Component({
155
                configs: configs,
156
                _sourceElement: $el
157
            });
158
            this.pageComponent('entity-selector', select2Component, $el);
159
            this.$formContainer.itemsManagerEditor({
160
                collection: this.collection
161
            });
162
        },
163
164
        /**
165
         * Initialize list component
166
         *
167
         * @private
168
         */
169
        _initializeList: function() {
170
            this.$listContainer.find('tbody').itemsManagerTable({
171
                collection: this.collection,
172
                itemTemplate: this.itemTemplate,
173
                itemRender: function itemRender(template, data) {
174
                    var context = _.extend({__: __}, data);
175
176
                    return template(context);
177
                },
178
                deleteHandler: _.partial(function(collection, model, data) {
0 ignored issues
show
Unused Code introduced by
The parameter data 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...
179
                    collection.remove(model);
180
                }, this.collection),
181
                sorting: false
182
            });
183
            // emulate reset for first time
184
            this._onCollectionChange();
185
        },
186
187
        /**
188
         * Collection change handler. Shows/Hides empty message
189
         *
190
         * @private
191
         */
192
        _onCollectionChange: function() {
193
            if (!this.collection.isEmpty()) {
194
                this.$listContainer.show();
195
                this.$noDataContainer.hide();
196
            } else {
197
                this.$listContainer.hide();
198
                this.$noDataContainer.show();
199
            }
200
        },
201
202
        /**
203
         * Appends single item to list
204
         *
205
         * @param {Object.<orochannel.entityManagement.Model>} model
206
         * @private
207
         */
208
        _onItemAdded: function(model) {
209
            model.set(this._prepareModelAttributes(model));
210
        },
211
212
        /**
213
         * Prepares model attributes
214
         *
215
         * @param   {Object.<orochannel.entityManagement.Model>} model
216
         * @returns {object}
217
         * @private
218
         */
219
        _prepareModelAttributes: function(model) {
220
            var entityName = model.get('name');
221
            var entityMetadata = this.options.metadata[entityName] || {};
222
            var actions = [];
223
            var lockedEntities = this.options.lockedEntities;
224
225
            if ((entityName.indexOf(lockedEntities) === -1) && this.options.mode === modes.EDIT_MODE) {
226
                actions.push({
227
                    collectionAction: 'delete',
228
                    title: 'Delete',
229
                    icon: 'fa-trash-o'
230
                });
231
            } else if (this.options.mode === modes.VIEW_MODE) {
232
                actions.push({
233
                    title: 'View',
234
                    icon: 'fa-eye',
235
                    url: entityMetadata.view_link
236
                });
237
                actions.push({
238
                    title: 'Edit',
239
                    icon: 'fa-pencil-square-o',
240
                    url: entityMetadata.edit_link
241
                });
242
            }
243
244
            return _.defaults(entityMetadata, {name: entityName, label: entityName, actions: actions});
245
        },
246
247
        /**
248
         * Creates model form name
249
         *
250
         * @param   {string} entityName
251
         * @returns {Object.<orochannel.entityManagement.Model>}
252
         * @private
253
         */
254
        _createModel: function(entityName) {
255
            var model = new EntityModel({name: entityName});
256
            model.set(this._prepareModelAttributes(model));
257
258
            return model;
259
        }
260
    });
261
});
262