inlines.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 = options.addButton;
  48. if (addButton === null) {
  49. if ($this.prop("tagName") === "TR") {
  50. // If forms are laid out as table rows, insert the
  51. // "add" button in a new table row:
  52. var numCols = this.eq(-1).children().length;
  53. $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
  54. addButton = $parent.find("tr:last a");
  55. } else {
  56. // Otherwise, insert it immediately after the last form:
  57. $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
  58. addButton = $this.filter(":last").next().find("a");
  59. }
  60. }
  61. addButton.click(function(e) {
  62. e.preventDefault();
  63. var template = $("#" + options.prefix + "-empty");
  64. var row = template.clone(true);
  65. row.removeClass(options.emptyCssClass)
  66. .addClass(options.formCssClass)
  67. .attr("id", options.prefix + "-" + nextIndex);
  68. if (row.is("tr")) {
  69. // If the forms are laid out in table rows, insert
  70. // the remove button into the last table cell:
  71. row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
  72. } else if (row.is("ul") || row.is("ol")) {
  73. // If they're laid out as an ordered/unordered list,
  74. // insert an <li> after the last list item:
  75. row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
  76. } else {
  77. // Otherwise, just insert the remove button as the
  78. // last child element of the form's container:
  79. row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
  80. }
  81. row.find("*").each(function() {
  82. updateElementIndex(this, options.prefix, totalForms.val());
  83. });
  84. // Insert the new form when it has been fully edited
  85. row.insertBefore($(template));
  86. // Update number of total forms
  87. $(totalForms).val(parseInt(totalForms.val(), 10) + 1);
  88. nextIndex += 1;
  89. // Hide add button in case we've hit the max, except we want to add infinitely
  90. if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
  91. addButton.parent().hide();
  92. }
  93. // The delete button of each row triggers a bunch of other things
  94. row.find("a." + options.deleteCssClass).click(function(e1) {
  95. e1.preventDefault();
  96. // Remove the parent form containing this button:
  97. row.remove();
  98. nextIndex -= 1;
  99. // If a post-delete callback was provided, call it with the deleted form:
  100. if (options.removed) {
  101. options.removed(row);
  102. }
  103. $(document).trigger('formset:removed', [row, options.prefix]);
  104. // Update the TOTAL_FORMS form count.
  105. var forms = $("." + options.formCssClass);
  106. $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
  107. // Show add button again once we drop below max
  108. if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
  109. addButton.parent().show();
  110. }
  111. // Also, update names and ids for all remaining form controls
  112. // so they remain in sequence:
  113. var i, formCount;
  114. var updateElementCallback = function() {
  115. updateElementIndex(this, options.prefix, i);
  116. };
  117. for (i = 0, formCount = forms.length; i < formCount; i++) {
  118. updateElementIndex($(forms).get(i), options.prefix, i);
  119. $(forms.get(i)).find("*").each(updateElementCallback);
  120. }
  121. });
  122. // If a post-add callback was supplied, call it with the added form:
  123. if (options.added) {
  124. options.added(row);
  125. }
  126. $(document).trigger('formset:added', [row, options.prefix]);
  127. });
  128. }
  129. return this;
  130. };
  131. /* Setup plugin defaults */
  132. $.fn.formset.defaults = {
  133. prefix: "form", // The form prefix for your django formset
  134. addText: "add another", // Text for the add link
  135. deleteText: "remove", // Text for the delete link
  136. addCssClass: "add-row", // CSS class applied to the add link
  137. deleteCssClass: "delete-row", // CSS class applied to the delete link
  138. emptyCssClass: "empty-row", // CSS class applied to the empty row
  139. formCssClass: "dynamic-form", // CSS class applied to each form in a formset
  140. added: null, // Function called each time a new form is added
  141. removed: null, // Function called each time a form is deleted
  142. addButton: null // Existing add button to use
  143. };
  144. // Tabular inlines ---------------------------------------------------------
  145. $.fn.tabularFormset = function(options) {
  146. var $rows = $(this);
  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");
  151. };
  152. var reinitDateTimeShortCuts = function() {
  153. // Reinitialize the calendar and clock widgets by force
  154. if (typeof DateTimeShortcuts !== "undefined") {
  155. $(".datetimeshortcuts").remove();
  156. DateTimeShortcuts.init();
  157. }
  158. };
  159. var updateSelectFilter = function() {
  160. // If any SelectFilter widgets are a part of the new form,
  161. // instantiate a new SelectFilter instance for it.
  162. if (typeof SelectFilter !== 'undefined') {
  163. $('.selectfilter').each(function(index, value) {
  164. var namearr = value.name.split('-');
  165. SelectFilter.init(value.id, namearr[namearr.length - 1], false);
  166. });
  167. $('.selectfilterstacked').each(function(index, value) {
  168. var namearr = value.name.split('-');
  169. SelectFilter.init(value.id, namearr[namearr.length - 1], true);
  170. });
  171. }
  172. };
  173. var initPrepopulatedFields = function(row) {
  174. row.find('.prepopulated_field').each(function() {
  175. var field = $(this),
  176. input = field.find('input, select, textarea'),
  177. dependency_list = input.data('dependency_list') || [],
  178. dependencies = [];
  179. $.each(dependency_list, function(i, field_name) {
  180. dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
  181. });
  182. if (dependencies.length) {
  183. input.prepopulate(dependencies, input.attr('maxlength'));
  184. }
  185. });
  186. };
  187. $rows.formset({
  188. prefix: options.prefix,
  189. addText: options.addText,
  190. formCssClass: "dynamic-" + options.prefix,
  191. deleteCssClass: "inline-deletelink",
  192. deleteText: options.deleteText,
  193. emptyCssClass: "empty-form",
  194. removed: alternatingRows,
  195. added: function(row) {
  196. initPrepopulatedFields(row);
  197. reinitDateTimeShortCuts();
  198. updateSelectFilter();
  199. alternatingRows(row);
  200. },
  201. addButton: options.addButton
  202. });
  203. return $rows;
  204. };
  205. // Stacked inlines ---------------------------------------------------------
  206. $.fn.stackedFormset = function(options) {
  207. var $rows = $(this);
  208. var updateInlineLabel = function(row) {
  209. $($rows.selector).find(".inline_label").each(function(i) {
  210. var count = i + 1;
  211. $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
  212. });
  213. };
  214. var reinitDateTimeShortCuts = function() {
  215. // Reinitialize the calendar and clock widgets by force, yuck.
  216. if (typeof DateTimeShortcuts !== "undefined") {
  217. $(".datetimeshortcuts").remove();
  218. DateTimeShortcuts.init();
  219. }
  220. };
  221. var updateSelectFilter = function() {
  222. // If any SelectFilter widgets were added, instantiate a new instance.
  223. if (typeof SelectFilter !== "undefined") {
  224. $(".selectfilter").each(function(index, value) {
  225. var namearr = value.name.split('-');
  226. SelectFilter.init(value.id, namearr[namearr.length - 1], false);
  227. });
  228. $(".selectfilterstacked").each(function(index, value) {
  229. var namearr = value.name.split('-');
  230. SelectFilter.init(value.id, namearr[namearr.length - 1], true);
  231. });
  232. }
  233. };
  234. var initPrepopulatedFields = function(row) {
  235. row.find('.prepopulated_field').each(function() {
  236. var field = $(this),
  237. input = field.find('input, select, textarea'),
  238. dependency_list = input.data('dependency_list') || [],
  239. dependencies = [];
  240. $.each(dependency_list, function(i, field_name) {
  241. dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
  242. });
  243. if (dependencies.length) {
  244. input.prepopulate(dependencies, input.attr('maxlength'));
  245. }
  246. });
  247. };
  248. $rows.formset({
  249. prefix: options.prefix,
  250. addText: options.addText,
  251. formCssClass: "dynamic-" + options.prefix,
  252. deleteCssClass: "inline-deletelink",
  253. deleteText: options.deleteText,
  254. emptyCssClass: "empty-form",
  255. removed: updateInlineLabel,
  256. added: function(row) {
  257. initPrepopulatedFields(row);
  258. reinitDateTimeShortCuts();
  259. updateSelectFilter();
  260. updateInlineLabel(row);
  261. },
  262. addButton: options.addButton
  263. });
  264. return $rows;
  265. };
  266. $(document).ready(function() {
  267. $(".js-inline-admin-formset").each(function() {
  268. var data = $(this).data(),
  269. inlineOptions = data.inlineFormset;
  270. switch(data.inlineType) {
  271. case "stacked":
  272. $(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options);
  273. break;
  274. case "tabular":
  275. $(inlineOptions.name + "-group .tabular.inline-related tbody tr").tabularFormset(inlineOptions.options);
  276. break;
  277. }
  278. });
  279. });
  280. })(django.jQuery);