Skip to content

Instantly share code, notes, and snippets.

@jjsaunier
Created October 8, 2013 15:47
Show Gist options
  • Save jjsaunier/6886801 to your computer and use it in GitHub Desktop.
Save jjsaunier/6886801 to your computer and use it in GitHub Desktop.
Javascript part for Symfony2 form collection handling. Written with jQuery
$(document).ready(function() {
var $container = $('div#container');
var $addLink = $('<a href="#" id="add-link-' + $container.attr('id') +'" class="btn">Add document</a>');
$container.append($addLink);
$addLink.click(function(e) {
addElement($container);
e.preventDefault();
return false;
});
var index = $container.find(':input').length;
if (index == 0) {
addElement($container);
} else {
$container.children('div').each(function() {
addDeleteLink($(this));
});
}
function addElement($container) {
var $prototype = $($container.attr('data-prototype').replace(/__name__label__/g, 'Document n°' + (index+1))
.replace(/__name__/g, index));
addDeleteLink($prototype);
$container.append($prototype);
index++;
}
function addDeleteLink($prototype) {
$deleteLink = $('<a href="#" class="btn btn-danger">Delete</a>');
$prototype.append($deleteLink);
$deleteLink.click(function(e) {
$prototype.remove();
e.preventDefault();
return false;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment