All files / web/bundles/pimui/js/form/common/fields simple-select-async.js

89.74% Statements 35/39
77.78% Branches 14/18
83.33% Functions 5/6
89.74% Lines 35/39

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 217              159x                                           159x     77x 77x 77x                       917x 917x   917x   917x 618x   917x                     704x             689x                     689x                 689x                                               103x                                   103x 103x     103x 8x   8x       95x               95x   605x                     216x 216x 216x         216x   216x 26x   190x   216x                         753x             753x                       77x        
/**
 * @author    Yohan Blain <yohan.blain@akeneo.com>
 * @copyright 2017 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 */
'use strict';
 
define([
  'jquery',
  'underscore',
  'pim/form/common/fields/field',
  'oro/translator',
  'pim/i18n',
  'pim/initselect2',
  'pim/user-context',
  'pim/template/form/common/fields/simple-select-async',
  'routing'
],
function (
  $,
  _,
  BaseField,
  __,
  i18n,
  initSelect2,
  UserContext,
  template,
  Routing
) {
  return BaseField.extend({
    events: {
        'change input': function (event) {
            this.errors = [];
            this.updateModel(this.getFieldValue(event.target));
            this.getRoot().render();
        }
    },
    template: _.template(template),
    choiceUrl: null,
    resultsPerPage: 20,
    allowClear: false,
 
    /**
     * {@inheritdoc}
     */
    initialize() {
      this.choiceUrl = null;
      this.choiceVerb = 'GET';
 
      BaseField.prototype.initialize.apply(this, arguments);
 
      if (undefined !== this.config.choiceRoute) {
        this.setChoiceUrl(Routing.generate(this.config.choiceRoute));
      }
      Iif (undefined !== this.config.choiceVerb) {
        this.choiceVerb = this.config.choiceVerb;
      }
    },
 
    /**
     * Sets the URL that will be used by select2 to fetch choices from the backend.
     *
     * @param {String} choiceUrl
     */
    setChoiceUrl(choiceUrl) {
      this.choiceUrl = choiceUrl;
    },
 
    /**
     * {@inheritdoc}
     */
    renderInput: function(templateContext) {
      return this.template(
        _.extend(templateContext, {
          value: this.getModelValue(),
        })
      );
    },
 
    /**
     * {@inheritdoc}
     */
    postRender(templateContext) {
      initSelect2.init(this.$('.select2'), this.getSelect2Options(templateContext));
    },
 
    /**
     * Returns the options for Select2 library
     *
     * @returns {Object}
     */
    getSelect2Options() {
      return {
        ajax: {
          url: this.choiceUrl,
          cache: true,
          data: this.select2Data.bind(this),
          results: this.select2Results.bind(this),
          type: this.choiceVerb,
        },
        initSelection: this.select2InitSelection.bind(this),
        placeholder: undefined !== this.config.placeholder ? __(this.config.placeholder) : ' ',
        dropdownCssClass: '',
        allowClear: this.allowClear,
      };
    },
 
    /**
     * Formatting callback for select2 choices.
     *
     * @param {String} term
     * @param {Number} page
     *
     * @returns {Object}
     */
    select2Data(term, page) {
      return {
        search: term,
        options: {
          limit: this.resultsPerPage,
          page: page,
          catalogLocale: UserContext.get('catalogLocale'),
        },
      };
    },
 
    /**
     * Select2 customization for pagination.
     *
     * @param response
     *
     * @returns {Object}
     */
    select2Results(response) {
      const nbResults = response.results ? Object.keys(response.results).length : Object.keys(response).length;
      const more = this.resultsPerPage === nbResults;
 
      // The result is already formatted for select2
      if (response.results) {
        response.more = more;
 
        return response;
      }
 
      // The result is an array
      Iif (response.isArray) {
        return {
          more: more,
          results: response.map(item => this.convertBackendItem(item)),
        };
      }
 
      // The result is an object
      return {
        more: more,
        results: Object.values(response).map(item => this.convertBackendItem(item)),
      };
    },
 
    /**
     * Select2 callback to fetch the initial value and display it properly.
     *
     * @param {Element} element
     * @param {Function} callback
     */
    select2InitSelection(element, callback) {
      const id = $(element).val();
      Eif ('' !== id) {
        $.ajax({
          url: this.choiceUrl,
          data: {options: {identifiers: [id]}},
          type: this.choiceVerb,
        }).then(response => {
          let selected = _.findWhere(response, {code: id});
 
          if (!selected) {
            selected = _.findWhere(response.results, {id: id});
          } else {
            selected = this.convertBackendItem(selected);
          }
          callback(selected);
        });
      }
    },
 
    /**
     * Converts the item returned from the backend to fit select2 needs.
     *
     * @param {Object} item
     *
     * @returns {Object}
     */
    convertBackendItem(item) {
      Iif (undefined !== item.label) {
        return {
          id: item.code,
          text: item.label,
        };
      }
 
      return {
        id: item.code,
        text: i18n.getLabel(item.labels, UserContext.get('catalogLocale'), item.code),
      };
    },
 
    /**
     * @param {Element} field
     *
     * @returns {String}
     */
    getFieldValue(field) {
      return $(field).val();
    },
  });
});