inlines.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*global DateTimeShortcuts, SelectFilter*/
  2. /**
  3. * Django admin inlines
  4. *
  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
  8. *
  9. * Copyright (c) 2009, Stanislaus Madueke
  10. * All rights reserved.
  11. *
  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.
  14. *
  15. * Licensed under the New BSD License
  16. * See: http://www.opensource.org/licenses/bsd-license.php
  17. */
  18. (function($) {
  19. 'use strict';
  20. $.fn.formset = function(opts) {
  21. var options = $.extend({}, $.fn.formset.defaults, opts);
  22. var $this = $(this);
  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));
  29. }
  30. if (el.id) {
  31. el.id = el.id.replace(id_regex, replacement);
  32. }
  33. if (el.name) {
  34. el.name = el.name.replace(id_regex, replacement);
  35. }
  36. };
  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);
  45. });
  46. if ($this.length && showAddButton) {
  47. var addButton;
  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="javascript:void(0)">' + options.addText + "</a></tr>");
  53. addButton = $parent.find("tr:last a");
  54. } else {
  55. // Otherwise, insert it immediately after the last form:
  56. $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="javascript:void(0)">' + options.addText + "</a></div>");
  57. addButton = $this.filter(":last").next().find("a");
  58. }
  59. addButton.click(function(e) {
  60. e.preventDefault();
  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);
  66. if (row.is("tr")) {
  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="javascript:void(0)">' + 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="javascript:void(0)">' + options.deleteText + "</a></li>");
  74. } else {
  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="javascript:void(0)">' + options.deleteText + "</a></span>");
  78. }
  79. row.find("*").each(function() {
  80. updateElementIndex(this, options.prefix, totalForms.val());
  81. });
  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);
  86. nextIndex += 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();
  90. }
  91. // The delete button of each row triggers a bunch of other things
  92. row.find("a." + options.deleteCssClass).click(function(e1) {
  93. e1.preventDefault();
  94. // Remove the parent form containing this button:
  95. row.remove();
  96. nextIndex -= 1;
  97. // If a post-delete callback was provided, call it with the deleted form:
  98. if (options.removed) {
  99. options.removed(row);
  100. }
  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();
  108. }
  109. // Also, update names and ids for all remaining form controls
  110. // so they remain in sequence:
  111. var i, formCount;
  112. var updateElementCallback = function() {
  113. updateElementIndex(this, options.prefix, i);
  114. };
  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);
  118. }
  119. });
  120. // If a post-add callback was supplied, call it with the added form:
  121. if (options.added) {
  122. options.added(row);
  123. }
  124. $(document).trigger('formset:added', [row, options.prefix]);
  125. });
  126. }
  127. return this;
  128. };
  129. /* Setup plugin defaults */
  130. $.fn.formset.defaults = {
  131. prefix: "form", // The form prefix for your django formset
  132. addText: "add another", // Text for the add link
  133. deleteText: "remove", // Text for the delete link
  134. addCssClass: "add-row", // CSS class applied to the add link
  135. deleteCssClass: "delete-row", // CSS class applied to the delete link
  136. emptyCssClass: "empty-row", // CSS class applied to the empty row
  137. formCssClass: "dynamic-form", // CSS class applied to each form in a formset
  138. added: null, // Function called each time a new form is added
  139. removed: null // Function called each time a form is deleted
  140. };
  141. // Tabular inlines ---------------------------------------------------------
  142. $.fn.tabularFormset = function(options) {
  143. var $rows = $(this);
  144. var alternatingRows = function(row) {
  145. $($rows.selector).not(".add-row").removeClass("row1 row2")
  146. .filter(":even").addClass("row1").end()
  147. .filter(":odd").addClass("row2");
  148. };
  149. var reinitDateTimeShortCuts = function() {
  150. // Reinitialize the calendar and clock widgets by force
  151. if (typeof DateTimeShortcuts !== "undefined") {
  152. $(".datetimeshortcuts").remove();
  153. DateTimeShortcuts.init();
  154. }
  155. };
  156. var updateSelectFilter = function() {
  157. // If any SelectFilter widgets are a part of the new form,
  158. // instantiate a new SelectFilter instance for it.
  159. if (typeof SelectFilter !== 'undefined') {
  160. $('.selectfilter').each(function(index, value) {
  161. var namearr = value.name.split('-');
  162. SelectFilter.init(value.id, namearr[namearr.length - 1], false);
  163. });
  164. $('.selectfilterstacked').each(function(index, value) {
  165. var namearr = value.name.split('-');
  166. SelectFilter.init(value.id, namearr[namearr.length - 1], true);
  167. });
  168. }
  169. };
  170. var initPrepopulatedFields = function(row) {
  171. row.find('.prepopulated_field').each(function() {
  172. var field = $(this),
  173. input = field.find('input, select, textarea'),
  174. dependency_list = input.data('dependency_list') || [],
  175. dependencies = [];
  176. $.each(dependency_list, function(i, field_name) {
  177. dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
  178. });
  179. if (dependencies.length) {
  180. input.prepopulate(dependencies, input.attr('maxlength'));
  181. }
  182. });
  183. };
  184. $rows.formset({
  185. prefix: options.prefix,
  186. addText: options.addText,
  187. formCssClass: "dynamic-" + options.prefix,
  188. deleteCssClass: "inline-deletelink",
  189. deleteText: options.deleteText,
  190. emptyCssClass: "empty-form",
  191. removed: alternatingRows,
  192. added: function(row) {
  193. initPrepopulatedFields(row);
  194. reinitDateTimeShortCuts();
  195. updateSelectFilter();
  196. alternatingRows(row);
  197. }
  198. });
  199. return $rows;
  200. };
  201. // Stacked inlines ---------------------------------------------------------
  202. $.fn.stackedFormset = function(options) {
  203. var $rows = $(this);
  204. var updateInlineLabel = function(row) {
  205. $($rows.selector).find(".inline_label").each(function(i) {
  206. var count = i + 1;
  207. $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
  208. });
  209. };
  210. var reinitDateTimeShortCuts = function() {
  211. // Reinitialize the calendar and clock widgets by force, yuck.
  212. if (typeof DateTimeShortcuts !== "undefined") {
  213. $(".datetimeshortcuts").remove();
  214. DateTimeShortcuts.init();
  215. }
  216. };
  217. var updateSelectFilter = function() {
  218. // If any SelectFilter widgets were added, instantiate a new instance.
  219. if (typeof SelectFilter !== "undefined") {
  220. $(".selectfilter").each(function(index, value) {
  221. var namearr = value.name.split('-');
  222. SelectFilter.init(value.id, namearr[namearr.length - 1], false);
  223. });
  224. $(".selectfilterstacked").each(function(index, value) {
  225. var namearr = value.name.split('-');
  226. SelectFilter.init(value.id, namearr[namearr.length - 1], true);
  227. });
  228. }
  229. };
  230. var initPrepopulatedFields = function(row) {
  231. row.find('.prepopulated_field').each(function() {
  232. var field = $(this),
  233. input = field.find('input, select, textarea'),
  234. dependency_list = input.data('dependency_list') || [],
  235. dependencies = [];
  236. $.each(dependency_list, function(i, field_name) {
  237. dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
  238. });
  239. if (dependencies.length) {
  240. input.prepopulate(dependencies, input.attr('maxlength'));
  241. }
  242. });
  243. };
  244. $rows.formset({
  245. prefix: options.prefix,
  246. addText: options.addText,
  247. formCssClass: "dynamic-" + options.prefix,
  248. deleteCssClass: "inline-deletelink",
  249. deleteText: options.deleteText,
  250. emptyCssClass: "empty-form",
  251. removed: updateInlineLabel,
  252. added: function(row) {
  253. initPrepopulatedFields(row);
  254. reinitDateTimeShortCuts();
  255. updateSelectFilter();
  256. updateInlineLabel(row);
  257. }
  258. });
  259. return $rows;
  260. };
  261. })(django.jQuery);