Skip to content

Instantly share code, notes, and snippets.

@michaelesmith
Last active August 29, 2015 14:03
Show Gist options
  • Save michaelesmith/410cf0a514bf1ec62500 to your computer and use it in GitHub Desktop.
Save michaelesmith/410cf0a514bf1ec62500 to your computer and use it in GitHub Desktop.
Symfony2 Form Collection Script
jQuery(document).ready(function() {
$("ul.collection").each(function(index, collection){
var prototype = $(collection).find(".item.prototype").remove().removeClass('hidden');
$(collection).data('prototype', prototype.prop('outerHTML'));
});
$("body").on('click', "ul.collection .add", function(e){
e.preventDefault();
var collection = $(this).parents("ul.collection");
var index = collection.data('index');
var prototype = collection.data('prototype');
var newForm = prototype.replace(/__name__/g, index);
collection.find(".end").before(newForm);
collection.data('index', index + 1);
});
$("body").on('click', "ul.collection .remove", function(e){
e.preventDefault();
$(this).parents("li.item").remove();
});
});
<h3>Query String Parameters</h3>
{% do form.queryParameter.setRendered %}
<ul class="collection list-unstyled" data-index="{{ form.queryParameter | length }}">
<li class="item prototype hidden">
{{ form_widget(form.queryParameter.vars.prototype.key, {attr: {placeholder: 'key'}}) }}
{{ form_widget(form.queryParameter.vars.prototype.value, {attr: {placeholder: 'value'}}) }}
<a href="#" class="remove btn btn-xs btn-danger">
<span class="glyphicon glyphicon-remove"></span>
Remove
</a>
</li>
{% for pair in form.queryParameter %}
<li class="item">
{{ form_widget(pair.key, {attr: {placeholder: 'key'}}) }}
{{ form_widget(pair.value, {attr: {placeholder: 'value'}}) }}
<a href="#" class="remove btn btn-xs btn-danger">
<span class="glyphicon glyphicon-remove"></span>
Remove
</a>
</li>
{% endfor %}
<li class="end">
<a href="#" class="add btn btn-xs btn-success">
<span class="glyphicon glyphicon-plus"></span>
Add
</a>
</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment