Skip to content

Instantly share code, notes, and snippets.

@merk
Created November 12, 2011 09:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merk/1360318 to your computer and use it in GitHub Desktop.
Save merk/1360318 to your computer and use it in GitHub Desktop.
A way to deal with collections
{% block address_form %}
{% spaceless %}
<div class="address">
<a href="#" class="remove_item btn danger right">Remove</a>
{{ form_row(address.unitNumber, { "label": "Unit Number" }) }}
{{ form_row(address.streetNumber, { "label": "Street Number" }) }}
{{ form_row(address.street, { "label": "Street" }) }}
{{ form_row(address.city, { "label": "City" }) }}
{{ form_row(address.postcode, { "label": "Postcode" }) }}
{{ form_row(address.state, { "label": "State" }) }}
{{ form_row(address.country, { "label": "Country" }) }}
<hr />
</div>
{% endspaceless %}
{% endblock address_form %}
/**
* Copyright Infinite Networks Pty Ltd
*/
/**
* Find and add functionality to any forms with prototypes.
*
* This probably wont work if we dont allow deletion.
*/
var deleteFromCollection = function ($element) {
$element.find('.remove_item').each(function () {
$(this).unbind('click');
$(this).bind('click', function (e) {
e.preventDefault();
e.stopPropagation();
$element.remove();
});
});
};
$('.collection').each(function () {
var $collection = $(this);
var counter = $collection.children('div').length;
$collection.find('.add_item').each(function () {
var $add = $(this);
var dataPrototype = $add.attr('data-prototype');
$add.unbind('click');
$add.bind('click', function (e) {
e.preventDefault();
e.stopPropagation();
// Will include the add <a> element.
var nextNumeral = counter++;
var $form = $(dataPrototype.replace('$$name$$', nextNumeral, 'gi'));
deleteFromCollection($form);
var last = $collection.children('div').last();
if (!last.length) {
last = $collection.prepend($form);
} else {
$form.insertAfter($collection.children('div').last());
}
});
});
$collection.children().each(function () {
deleteFromCollection($(this));
});
});
<div class="span12 columns">
<fieldset>
<legend>Company Locations</legend>
{{ form_row(form.primaryAddress, {'label': 'Primary Address'}) }}
<hr />
<div class="collection">
{% for address in form.addresses %}{{ block('address_form') }}{% endfor %}
{% set address = form.addresses.get('prototype') %}
<a href="#" class="add_item btn primary right" data-prototype="{{ block('address_form')|escape }}">Add Address</a>
</div>
</fieldset>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment