templates/js/library/entity_collection/entity_collection.js.twig line 1

Open in your IDE?
  1. function EntityCollection(element) {
  2.     this.$element = $(element);
  3.     this.$itemsContainer = this.$element.find('.js-entity-collection-items');
  4.     this.prototypeName = this.$element.data('prototype-name') || '__name__';
  5.     this.prototypeHtml = this.$element.data('prototype') || null;
  6.     this.itemClass = this.$element.data('item-class') || 'entity-collection__item';
  7.     this.index = this.$itemsContainer.find('.' + this.itemClass).length || this.$itemsContainer.children().length;
  8.     this.init();
  9. }
  10. EntityCollection.prototype.init = function() {
  11.     var self = this;
  12.     this.$element.on('click', '.js-entity-collection-add', function() {
  13.         self.addItem();
  14.     });
  15.     // Поддерживаем разные селекторы кнопки удаления (в шаблонах мог использоваться старый класс)
  16.     this.$element.on('click', '.js-entity-collection-remove', function() {
  17.         var $item = $(this).closest('.' + self.itemClass);
  18.         if ($item.length) {
  19.             $item.remove();
  20.         }
  21.     });
  22. };
  23. EntityCollection.prototype.addItem = function() {
  24.     if (!this.prototypeHtml) {
  25.         console.warn('EntityCollection: prototypeHtml is missing');
  26.         return;
  27.     }
  28.     var newForm = this.prototypeHtml.replace(new RegExp(this.prototypeName, 'g'), this.index);
  29.     var $wrapper = $("<div></div>").addClass(this.itemClass + ' mb-3 p-3 border rounded');
  30.     $wrapper.html(newForm + "<div><button type=\"button\" class=\"btn btn-sm btn-danger mt-2 js-entity-collection-remove\">Удалить</button></div>");
  31.     this.$itemsContainer.append($wrapper);
  32.     this.index++;
  33. };