1 /*global DateTimeShortcuts, SelectFilter*/
5 * Based on jQuery Formset 1.1
6 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
7 * @requires jQuery 1.2.6 or later
9 * Copyright (c) 2009, Stanislaus Madueke
10 * All rights reserved.
12 * Spiced up with Code from Zain Memon's GSoC project 2009
13 * and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip.
15 * Licensed under the New BSD License
16 * See: http://www.opensource.org/licenses/bsd-license.php
20 $.fn.formset = function(opts) {
21 var options = $.extend({}, $.fn.formset.defaults, opts);
23 var $parent = $this.parent();
24 var updateElementIndex = function(el, prefix, ndx) {
25 var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
26 var replacement = prefix + "-" + ndx;
27 if ($(el).prop("for")) {
28 $(el).prop("for", $(el).prop("for").replace(id_regex, replacement));
31 el.id = el.id.replace(id_regex, replacement);
34 el.name = el.name.replace(id_regex, replacement);
37 var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off");
38 var nextIndex = parseInt(totalForms.val(), 10);
39 var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off");
40 // only show the add button if we are allowed to add more items,
41 // note that max_num = None translates to a blank string.
42 var showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0;
43 $this.each(function(i) {
44 $(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
46 if ($this.length && showAddButton) {
48 if ($this.prop("tagName") === "TR") {
49 // If forms are laid out as table rows, insert the
50 // "add" button in a new table row:
51 var numCols = this.eq(-1).children().length;
52 $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
53 addButton = $parent.find("tr:last a");
55 // Otherwise, insert it immediately after the last form:
56 $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
57 addButton = $this.filter(":last").next().find("a");
59 addButton.click(function(e) {
61 var template = $("#" + options.prefix + "-empty");
62 var row = template.clone(true);
63 row.removeClass(options.emptyCssClass)
64 .addClass(options.formCssClass)
65 .attr("id", options.prefix + "-" + nextIndex);
67 // If the forms are laid out in table rows, insert
68 // the remove button into the last table cell:
69 row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
70 } else if (row.is("ul") || row.is("ol")) {
71 // If they're laid out as an ordered/unordered list,
72 // insert an <li> after the last list item:
73 row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
75 // Otherwise, just insert the remove button as the
76 // last child element of the form's container:
77 row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
79 row.find("*").each(function() {
80 updateElementIndex(this, options.prefix, totalForms.val());
82 // Insert the new form when it has been fully edited
83 row.insertBefore($(template));
84 // Update number of total forms
85 $(totalForms).val(parseInt(totalForms.val(), 10) + 1);
87 // Hide add button in case we've hit the max, except we want to add infinitely
88 if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
89 addButton.parent().hide();
91 // The delete button of each row triggers a bunch of other things
92 row.find("a." + options.deleteCssClass).click(function(e1) {
94 // Remove the parent form containing this button:
97 // If a post-delete callback was provided, call it with the deleted form:
98 if (options.removed) {
101 $(document).trigger('formset:removed', [row, options.prefix]);
102 // Update the TOTAL_FORMS form count.
103 var forms = $("." + options.formCssClass);
104 $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
105 // Show add button again once we drop below max
106 if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
107 addButton.parent().show();
109 // Also, update names and ids for all remaining form controls
110 // so they remain in sequence:
112 var updateElementCallback = function() {
113 updateElementIndex(this, options.prefix, i);
115 for (i = 0, formCount = forms.length; i < formCount; i++) {
116 updateElementIndex($(forms).get(i), options.prefix, i);
117 $(forms.get(i)).find("*").each(updateElementCallback);
120 // If a post-add callback was supplied, call it with the added form:
124 $(document).trigger('formset:added', [row, options.prefix]);
130 /* Setup plugin defaults */
131 $.fn.formset.defaults = {
132 prefix: "form", // The form prefix for your django formset
133 addText: "add another", // Text for the add link
134 deleteText: "remove", // Text for the delete link
135 addCssClass: "add-row", // CSS class applied to the add link
136 deleteCssClass: "delete-row", // CSS class applied to the delete link
137 emptyCssClass: "empty-row", // CSS class applied to the empty row
138 formCssClass: "dynamic-form", // CSS class applied to each form in a formset
139 added: null, // Function called each time a new form is added
140 removed: null // Function called each time a form is deleted
144 // Tabular inlines ---------------------------------------------------------
145 $.fn.tabularFormset = function(options) {
147 var alternatingRows = function(row) {
148 $($rows.selector).not(".add-row").removeClass("row1 row2")
149 .filter(":even").addClass("row1").end()
150 .filter(":odd").addClass("row2");
153 var reinitDateTimeShortCuts = function() {
154 // Reinitialize the calendar and clock widgets by force
155 if (typeof DateTimeShortcuts !== "undefined") {
156 $(".datetimeshortcuts").remove();
157 DateTimeShortcuts.init();
161 var updateSelectFilter = function() {
162 // If any SelectFilter widgets are a part of the new form,
163 // instantiate a new SelectFilter instance for it.
164 if (typeof SelectFilter !== 'undefined') {
165 $('.selectfilter').each(function(index, value) {
166 var namearr = value.name.split('-');
167 SelectFilter.init(value.id, namearr[namearr.length - 1], false);
169 $('.selectfilterstacked').each(function(index, value) {
170 var namearr = value.name.split('-');
171 SelectFilter.init(value.id, namearr[namearr.length - 1], true);
176 var initPrepopulatedFields = function(row) {
177 row.find('.prepopulated_field').each(function() {
179 input = field.find('input, select, textarea'),
180 dependency_list = input.data('dependency_list') || [],
182 $.each(dependency_list, function(i, field_name) {
183 dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
185 if (dependencies.length) {
186 input.prepopulate(dependencies, input.attr('maxlength'));
192 prefix: options.prefix,
193 addText: options.addText,
194 formCssClass: "dynamic-" + options.prefix,
195 deleteCssClass: "inline-deletelink",
196 deleteText: options.deleteText,
197 emptyCssClass: "empty-form",
198 removed: alternatingRows,
199 added: function(row) {
200 initPrepopulatedFields(row);
201 reinitDateTimeShortCuts();
202 updateSelectFilter();
203 alternatingRows(row);
210 // Stacked inlines ---------------------------------------------------------
211 $.fn.stackedFormset = function(options) {
213 var updateInlineLabel = function(row) {
214 $($rows.selector).find(".inline_label").each(function(i) {
216 $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
220 var reinitDateTimeShortCuts = function() {
221 // Reinitialize the calendar and clock widgets by force, yuck.
222 if (typeof DateTimeShortcuts !== "undefined") {
223 $(".datetimeshortcuts").remove();
224 DateTimeShortcuts.init();
228 var updateSelectFilter = function() {
229 // If any SelectFilter widgets were added, instantiate a new instance.
230 if (typeof SelectFilter !== "undefined") {
231 $(".selectfilter").each(function(index, value) {
232 var namearr = value.name.split('-');
233 SelectFilter.init(value.id, namearr[namearr.length - 1], false);
235 $(".selectfilterstacked").each(function(index, value) {
236 var namearr = value.name.split('-');
237 SelectFilter.init(value.id, namearr[namearr.length - 1], true);
242 var initPrepopulatedFields = function(row) {
243 row.find('.prepopulated_field').each(function() {
245 input = field.find('input, select, textarea'),
246 dependency_list = input.data('dependency_list') || [],
248 $.each(dependency_list, function(i, field_name) {
249 dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
251 if (dependencies.length) {
252 input.prepopulate(dependencies, input.attr('maxlength'));
258 prefix: options.prefix,
259 addText: options.addText,
260 formCssClass: "dynamic-" + options.prefix,
261 deleteCssClass: "inline-deletelink",
262 deleteText: options.deleteText,
263 emptyCssClass: "empty-form",
264 removed: updateInlineLabel,
265 added: function(row) {
266 initPrepopulatedFields(row);
267 reinitDateTimeShortCuts();
268 updateSelectFilter();
269 updateInlineLabel(row);
276 $(document).ready(function() {
277 $(".js-inline-admin-formset").each(function() {
278 var data = $(this).data(),
279 inlineOptions = data.inlineFormset;
280 switch(data.inlineType) {
282 $(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options);
285 $(inlineOptions.name + "-group .tabular.inline-related tbody tr").tabularFormset(inlineOptions.options);