All files / web/bundles/pimui/js/product/field multi-select-field.js

97.96% Statements 48/49
90.48% Branches 19/21
100% Functions 17/17
97.96% Lines 48/49

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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                  137x                                                     137x                           311x 311x 311x   311x               2x     2x 2x 2x 2x 2x     2x 2x               311x             311x 311x 311x           47x                   47x 18x   18x     29x       29x 155x     29x       139x             139x         106x 106x         106x     139x 138x 10x     138x 173x 173x 152x     21x     138x           311x                   286x                           33x 33x 5x     33x   33x                     307x                
'use strict';
/**
 * Multi select field
 *
 * @author    Julien Sanchez <julien@akeneo.com>
 * @author    Filips Alpe <filips@akeneo.com>
 * @copyright 2015 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
define(
    [
        'jquery',
        'pim/field',
        'underscore',
        'pim/template/product/field/multi-select',
        'routing',
        'pim/attribute-option/create',
        'pim/security-context',
        'pim/initselect2',
        'pim/user-context',
        'pim/i18n',
        'pim/attribute-manager'
    ],
    function (
        $,
        Field,
        _,
        fieldTemplate,
        Routing,
        createOption,
        SecurityContext,
        initSelect2,
        UserContext,
        i18n,
        AttributeManager
    ) {
        return Field.extend({
            fieldTemplate: _.template(fieldTemplate),
            choicePromise: null,
            promiseIdentifiers: null,
            choiceUrl: null,
            events: {
                'change .field-input:first input.select-field': 'updateModel',
                'click .add-attribute-option': 'createOption'
            },
 
            /**
             * {@inheritdoc}
             */
            getTemplateContext: function () {
                return Field.prototype.getTemplateContext.apply(this, arguments).then(function (templateContext) {
                    var isAllowed = SecurityContext.isGranted('pim_enrich_attribute_edit');
                    templateContext.userCanAddOption = this.editable && isAllowed;
 
                    return templateContext;
                }.bind(this));
            },
 
            /**
             * Create a new option for this multi select field
             */
            createOption: function () {
                Iif (!SecurityContext.isGranted('pim_enrich_attribute_edit')) {
                    return;
                }
                createOption(this.attribute).then(function (option) {
                    Eif (this.isEditable()) {
                        var value = this.getCurrentValue().data;
                        value.push(option.code);
                        this.setCurrentValue(value);
                    }
 
                    this.choicePromise = null;
                    this.render();
                }.bind(this));
            },
 
            /**
             * {@inheritdoc}
             */
            renderInput: function (context) {
                return this.fieldTemplate(context);
            },
 
            /**
             * {@inheritdoc}
             */
            postRender: function () {
                this.$('[data-toggle="tooltip"]').tooltip();
                this.getChoiceUrl().then(function (choiceUrl) {
                    var options = {
                        ajax: {
                            url: choiceUrl,
                            quietMillis: 250,
                            cache: true,
                            data: function (term, page) {
                                return {
                                    search: term,
                                    options: {
                                        limit: 20,
                                        page: page,
                                        catalogLocale: UserContext.get('catalogLocale')
                                    }
                                };
                            }.bind(this),
                            results: function (response) {
                                if (response.results) {
                                    response.more = 20 === _.keys(response.results).length;
 
                                    return response;
                                }
 
                                var data = {
                                    more: 20 === _.keys(response).length,
                                    results: []
                                };
                                _.each(response, function (value) {
                                    data.results.push(this.convertBackendItem(value));
                                }.bind(this));
 
                                return data;
                            }.bind(this)
                        },
                        initSelection: function (element, callback) {
                            var identifiers = AttributeManager.getValue(
                                this.model.attributes.values,
                                this.attribute,
                                UserContext.get('catalogLocale'),
                                UserContext.get('catalogScope')
                            ).data;
 
                            if (
                                null === this.choicePromise
                                || this.promiseIdentifiers !== identifiers
                                || this.choiceUrl !== choiceUrl
                            ) {
                                this.choiceUrl = choiceUrl;
                                this.choicePromise = $.post(choiceUrl, {
                                    options: {
                                        identifiers: identifiers
                                    }
                                });
                                this.promiseIdentifiers = identifiers;
                            }
 
                            this.choicePromise.then(function (results) {
                                if (_.has(results, 'results')) {
                                    results = results.results;
                                }
 
                                var choices = _.map($(element).val().split(','), function (choice) {
                                    var option = _.findWhere(results, {code: choice});
                                    if (option) {
                                        return this.convertBackendItem(option);
                                    }
 
                                    return _.findWhere(results, {id: choice});
                                }.bind(this));
 
                                callback(_.compact(choices));
                            }.bind(this));
                        }.bind(this),
                        multiple: true
                    };
 
                    initSelect2.init(this.$('input.select-field'), options);
                }.bind(this));
            },
 
            /**
             * Get the URL to retrieve the choice list for this select field
             *
             * @returns {Promise}
             */
            getChoiceUrl: function () {
                return $.Deferred().resolve(
                    Routing.generate(
                        'pim_enrich_attributeoption_get',
                        {
                            identifier: this.attribute.code
                        }
                    )
                ).promise();
            },
 
            /**
             * {@inheritdoc}
             */
            updateModel: function () {
                var data = this.$('.field-input:first input.select-field').val().split(',');
                if (1 === data.length && '' === data[0]) {
                    data = [];
                }
 
                this.choicePromise = null;
 
                this.setCurrentValue(data);
            },
 
            /**
             * Convert the item returned from the backend to fit select2 needs
             *
             * @param {object} item
             *
             * @return {object}
             */
            convertBackendItem: function (item) {
                return {
                    id: item.code,
                    text: i18n.getLabel(item.labels, UserContext.get('catalogLocale'), item.code)
                };
            }
        });
    }
);