Skip to content

Instantly share code, notes, and snippets.

@martiis
Created October 12, 2016 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martiis/c2ed11f8ae79c5790aeb23c6e5166bd2 to your computer and use it in GitHub Desktop.
Save martiis/c2ed11f8ae79c5790aeb23c6e5166bd2 to your computer and use it in GitHub Desktop.
For displaying symfony collections
(function () {
function SymfonyCollection(listId, addBtnId, count) {
this.list = $('#' + listId);
this.count = count;
this.widget = this.list.attr('data-prototype');
var _self = this;
$('#' + addBtnId).on('click', function () {
_self.add();
});
this.list.find('.form-group').each(function () {
_self.addRemoveButton($(this));
});
}
SymfonyCollection.prototype.list = undefined;
SymfonyCollection.prototype.count = undefined;
SymfonyCollection.prototype.widget = undefined;
SymfonyCollection.prototype.add = function () {
this.list.append(this.getWidget());
};
SymfonyCollection.prototype.getWidget = function () {
var widget = $(this.widget.replace(/__name__/g, this.count));
this.addRemoveButton(widget);
this.count++;
return widget;
};
SymfonyCollection.prototype.addRemoveButton = function ($formGroup) {
$formGroup.addClass('input-group');
var $rmBtn = $('<span class="input-group-btn"><button type="button" class="btn btn-danger"><i class="glyphicon glyphicon-remove"></i></button></span>');
$formGroup.append($rmBtn);
$rmBtn.on('click', function (e) {
e.preventDefault();
$formGroup.remove();
})
};
var length = '{{ form.ips|length }}';
$collection = new SymfonyCollection('sandbox_form_ips', 'js-add-ip', length);
if (length == 0) {
$collection.add();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment