inlines.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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: https://opensource.org/licenses/bsd-license.php
  17. */
  18. 'use strict';
  19. {
  20. const $ = django.jQuery;
  21. $.fn.formset = function(opts) {
  22. const options = $.extend({}, $.fn.formset.defaults, opts);
  23. const $this = $(this);
  24. const $parent = $this.parent();
  25. const updateElementIndex = function(el, prefix, ndx) {
  26. const id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
  27. const replacement = prefix + "-" + ndx;
  28. if ($(el).prop("for")) {
  29. $(el).prop("for", $(el).prop("for").replace(id_regex, replacement));
  30. }
  31. if (el.id) {
  32. el.id = el.id.replace(id_regex, replacement);
  33. }
  34. if (el.name) {
  35. el.name = el.name.replace(id_regex, replacement);
  36. }
  37. };
  38. const totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off");
  39. let nextIndex = parseInt(totalForms.val(), 10);
  40. const maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off");
  41. const minForms = $("#id_" + options.prefix + "-MIN_NUM_FORMS").prop("autocomplete", "off");
  42. let addButton;
  43. /**
  44. * The "Add another MyModel" button below the inline forms.
  45. */
  46. const addInlineAddButton = function() {
  47. if (addButton === null) {
  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. const 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");
  54. } else {
  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");
  58. }
  59. }
  60. addButton.on('click', addInlineClickHandler);
  61. };
  62. const addInlineClickHandler = function(e) {
  63. e.preventDefault();
  64. const template = $("#" + options.prefix + "-empty");
  65. const row = template.clone(true);
  66. row.removeClass(options.emptyCssClass)
  67. .addClass(options.formCssClass)
  68. .attr("id", options.prefix + "-" + nextIndex);
  69. addInlineDeleteButton(row);
  70. row.find("*").each(function() {
  71. updateElementIndex(this, options.prefix, totalForms.val());
  72. });
  73. // Insert the new form when it has been fully edited.
  74. row.insertBefore($(template));
  75. // Update number of total forms.
  76. $(totalForms).val(parseInt(totalForms.val(), 10) + 1);
  77. nextIndex += 1;
  78. // Hide the add button if there's a limit and it's been reached.
  79. if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
  80. addButton.parent().hide();
  81. }
  82. // Show the remove buttons if there are more than min_num.
  83. toggleDeleteButtonVisibility(row.closest('.inline-group'));
  84. // Pass the new form to the post-add callback, if provided.
  85. if (options.added) {
  86. options.added(row);
  87. }
  88. $(document).trigger('formset:added', [row, options.prefix]);
  89. };
  90. /**
  91. * The "X" button that is part of every unsaved inline.
  92. * (When saved, it is replaced with a "Delete" checkbox.)
  93. */
  94. const addInlineDeleteButton = function(row) {
  95. if (row.is("tr")) {
  96. // If the forms are laid out in table rows, insert
  97. // the remove button into the last table cell:
  98. row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
  99. } else if (row.is("ul") || row.is("ol")) {
  100. // If they're laid out as an ordered/unordered list,
  101. // insert an <li> after the last list item:
  102. row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
  103. } else {
  104. // Otherwise, just insert the remove button as the
  105. // last child element of the form's container:
  106. row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
  107. }
  108. // Add delete handler for each row.
  109. row.find("a." + options.deleteCssClass).on('click', inlineDeleteHandler.bind(this));
  110. };
  111. const inlineDeleteHandler = function(e1) {
  112. e1.preventDefault();
  113. const deleteButton = $(e1.target);
  114. const row = deleteButton.closest('.' + options.formCssClass);
  115. const inlineGroup = row.closest('.inline-group');
  116. // Remove the parent form containing this button,
  117. // and also remove the relevant row with non-field errors:
  118. const prevRow = row.prev();
  119. if (prevRow.length && prevRow.hasClass('row-form-errors')) {
  120. prevRow.remove();
  121. }
  122. row.remove();
  123. nextIndex -= 1;
  124. // Pass the deleted form to the post-delete callback, if provided.
  125. if (options.removed) {
  126. options.removed(row);
  127. }
  128. $(document).trigger('formset:removed', [row, options.prefix]);
  129. // Update the TOTAL_FORMS form count.
  130. const forms = $("." + options.formCssClass);
  131. $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
  132. // Show add button again once below maximum number.
  133. if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
  134. addButton.parent().show();
  135. }
  136. // Hide the remove buttons if at min_num.
  137. toggleDeleteButtonVisibility(inlineGroup);
  138. // Also, update names and ids for all remaining form controls so
  139. // they remain in sequence:
  140. let i, formCount;
  141. const updateElementCallback = function() {
  142. updateElementIndex(this, options.prefix, i);
  143. };
  144. for (i = 0, formCount = forms.length; i < formCount; i++) {
  145. updateElementIndex($(forms).get(i), options.prefix, i);
  146. $(forms.get(i)).find("*").each(updateElementCallback);
  147. }
  148. };
  149. const toggleDeleteButtonVisibility = function(inlineGroup) {
  150. if ((minForms.val() !== '') && (minForms.val() - totalForms.val()) >= 0) {
  151. inlineGroup.find('.inline-deletelink').hide();
  152. } else {
  153. inlineGroup.find('.inline-deletelink').show();
  154. }
  155. };
  156. $this.each(function(i) {
  157. $(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
  158. });
  159. // Create the delete buttons for all unsaved inlines:
  160. $this.filter('.' + options.formCssClass + ':not(.has_original):not(.' + options.emptyCssClass + ')').each(function() {
  161. addInlineDeleteButton($(this));
  162. });
  163. toggleDeleteButtonVisibility($this);
  164. // Create the add button, initially hidden.
  165. addButton = options.addButton;
  166. addInlineAddButton();
  167. // Show the add button if allowed to add more items.
  168. // Note that max_num = None translates to a blank string.
  169. const showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0;
  170. if ($this.length && showAddButton) {
  171. addButton.parent().show();
  172. } else {
  173. addButton.parent().hide();
  174. }
  175. return this;
  176. };
  177. /* Setup plugin defaults */
  178. $.fn.formset.defaults = {
  179. prefix: "form", // The form prefix for your django formset
  180. addText: "add another", // Text for the add link
  181. deleteText: "remove", // Text for the delete link
  182. addCssClass: "add-row", // CSS class applied to the add link
  183. deleteCssClass: "delete-row", // CSS class applied to the delete link
  184. emptyCssClass: "empty-row", // CSS class applied to the empty row
  185. formCssClass: "dynamic-form", // CSS class applied to each form in a formset
  186. added: null, // Function called each time a new form is added
  187. removed: null, // Function called each time a form is deleted
  188. addButton: null // Existing add button to use
  189. };
  190. // Tabular inlines ---------------------------------------------------------
  191. $.fn.tabularFormset = function(selector, options) {
  192. const $rows = $(this);
  193. const reinitDateTimeShortCuts = function() {
  194. // Reinitialize the calendar and clock widgets by force
  195. if (typeof DateTimeShortcuts !== "undefined") {
  196. $(".datetimeshortcuts").remove();
  197. DateTimeShortcuts.init();
  198. }
  199. };
  200. const updateSelectFilter = function() {
  201. // If any SelectFilter widgets are a part of the new form,
  202. // instantiate a new SelectFilter instance for it.
  203. if (typeof SelectFilter !== 'undefined') {
  204. $('.selectfilter').each(function(index, value) {
  205. const namearr = value.name.split('-');
  206. SelectFilter.init(value.id, namearr[namearr.length - 1], false);
  207. });
  208. $('.selectfilterstacked').each(function(index, value) {
  209. const namearr = value.name.split('-');
  210. SelectFilter.init(value.id, namearr[namearr.length - 1], true);
  211. });
  212. }
  213. };
  214. const initPrepopulatedFields = function(row) {
  215. row.find('.prepopulated_field').each(function() {
  216. const field = $(this),
  217. input = field.find('input, select, textarea'),
  218. dependency_list = input.data('dependency_list') || [],
  219. dependencies = [];
  220. $.each(dependency_list, function(i, field_name) {
  221. dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
  222. });
  223. if (dependencies.length) {
  224. input.prepopulate(dependencies, input.attr('maxlength'));
  225. }
  226. });
  227. };
  228. $rows.formset({
  229. prefix: options.prefix,
  230. addText: options.addText,
  231. formCssClass: "dynamic-" + options.prefix,
  232. deleteCssClass: "inline-deletelink",
  233. deleteText: options.deleteText,
  234. emptyCssClass: "empty-form",
  235. added: function(row) {
  236. initPrepopulatedFields(row);
  237. reinitDateTimeShortCuts();
  238. updateSelectFilter();
  239. },
  240. addButton: options.addButton
  241. });
  242. return $rows;
  243. };
  244. // Stacked inlines ---------------------------------------------------------
  245. $.fn.stackedFormset = function(selector, options) {
  246. const $rows = $(this);
  247. const updateInlineLabel = function(row) {
  248. $(selector).find(".inline_label").each(function(i) {
  249. const count = i + 1;
  250. $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
  251. });
  252. };
  253. const reinitDateTimeShortCuts = function() {
  254. // Reinitialize the calendar and clock widgets by force, yuck.
  255. if (typeof DateTimeShortcuts !== "undefined") {
  256. $(".datetimeshortcuts").remove();
  257. DateTimeShortcuts.init();
  258. }
  259. };
  260. const updateSelectFilter = function() {
  261. // If any SelectFilter widgets were added, instantiate a new instance.
  262. if (typeof SelectFilter !== "undefined") {
  263. $(".selectfilter").each(function(index, value) {
  264. const namearr = value.name.split('-');
  265. SelectFilter.init(value.id, namearr[namearr.length - 1], false);
  266. });
  267. $(".selectfilterstacked").each(function(index, value) {
  268. const namearr = value.name.split('-');
  269. SelectFilter.init(value.id, namearr[namearr.length - 1], true);
  270. });
  271. }
  272. };
  273. const initPrepopulatedFields = function(row) {
  274. row.find('.prepopulated_field').each(function() {
  275. const field = $(this),
  276. input = field.find('input, select, textarea'),
  277. dependency_list = input.data('dependency_list') || [],
  278. dependencies = [];
  279. $.each(dependency_list, function(i, field_name) {
  280. dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
  281. });
  282. if (dependencies.length) {
  283. input.prepopulate(dependencies, input.attr('maxlength'));
  284. }
  285. });
  286. };
  287. $rows.formset({
  288. prefix: options.prefix,
  289. addText: options.addText,
  290. formCssClass: "dynamic-" + options.prefix,
  291. deleteCssClass: "inline-deletelink",
  292. deleteText: options.deleteText,
  293. emptyCssClass: "empty-form",
  294. removed: updateInlineLabel,
  295. added: function(row) {
  296. initPrepopulatedFields(row);
  297. reinitDateTimeShortCuts();
  298. updateSelectFilter();
  299. updateInlineLabel(row);
  300. },
  301. addButton: options.addButton
  302. });
  303. return $rows;
  304. };
  305. $(document).ready(function() {
  306. $(".js-inline-admin-formset").each(function() {
  307. const data = $(this).data(),
  308. inlineOptions = data.inlineFormset;
  309. let selector;
  310. switch(data.inlineType) {
  311. case "stacked":
  312. selector = inlineOptions.name + "-group .inline-related";
  313. $(selector).stackedFormset(selector, inlineOptions.options);
  314. break;
  315. case "tabular":
  316. selector = inlineOptions.name + "-group .tabular.inline-related tbody:first > tr.form-row";
  317. $(selector).tabularFormset(selector, inlineOptions.options);
  318. break;
  319. }
  320. });
  321. });
  322. }