inlines.js 13.7 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*global DateTimeShortcuts, SelectFilter*/
/**
 * Django admin inlines
 *
 * Based on jQuery Formset 1.1
 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
 * @requires jQuery 1.2.6 or later
 *
 * Copyright (c) 2009, Stanislaus Madueke
 * All rights reserved.
 *
 * Spiced up with Code from Zain Memon's GSoC project 2009
 * and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip.
 *
 * Licensed under the New BSD License
 * See: http://www.opensource.org/licenses/bsd-license.php
 */
(function($) {
    'use strict';
    $.fn.formset = function(opts) {
        var options = $.extend({}, $.fn.formset.defaults, opts);
        var $this = $(this);
        var $parent = $this.parent();
        var updateElementIndex = function(el, prefix, ndx) {
            var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
            var replacement = prefix + "-" + ndx;
27

Administrator committed
28
            if ($(el).prop("for")) {
29 30
                $(el).prop("for", $(el).prop("for")
                    .replace(id_regex, replacement));
Administrator committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44
            }
            if (el.id) {
                el.id = el.id.replace(id_regex, replacement);
            }
            if (el.name) {
                el.name = el.name.replace(id_regex, replacement);
            }
        };
        var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off");
        var nextIndex = parseInt(totalForms.val(), 10);
        var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off");
        // only show the add button if we are allowed to add more items,
        // note that max_num = None translates to a blank string.
        var showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0;
45

Administrator committed
46
        $this.each(function(i) {
47 48
            $(this).not("." + options.emptyCssClass)
                .addClass(options.formCssClass);
Administrator committed
49 50 51
        });
        if ($this.length && showAddButton) {
            var addButton = options.addButton;
52

Administrator committed
53 54 55 56 57
            if (addButton === null) {
                if ($this.prop("tagName") === "TR") {
                    // If forms are laid out as table rows, insert the
                    // "add" button in a new table row:
                    var numCols = this.eq(-1).children().length;
58

Administrator committed
59 60 61 62 63
                    $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
                    addButton = $parent.find("tr:last a");
                } else {
                    // Otherwise, insert it immediately after the last form:
                    $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
64 65
                    addButton = $this.filter(":last").next()
                        .find("a");
Administrator committed
66 67 68 69 70 71
                }
            }
            addButton.click(function(e) {
                e.preventDefault();
                var template = $("#" + options.prefix + "-empty");
                var row = template.clone(true);
72

Administrator committed
73
                row.removeClass(options.emptyCssClass)
74 75
                    .addClass(options.formCssClass)
                    .attr("id", options.prefix + "-" + nextIndex);
Administrator committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
                if (row.is("tr")) {
                    // If the forms are laid out in table rows, insert
                    // the remove button into the last table cell:
                    row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
                } else if (row.is("ul") || row.is("ol")) {
                    // If they're laid out as an ordered/unordered list,
                    // insert an <li> after the last list item:
                    row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
                } else {
                    // Otherwise, just insert the remove button as the
                    // last child element of the form's container:
                    row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
                }
                row.find("*").each(function() {
                    updateElementIndex(this, options.prefix, totalForms.val());
                });
                // Insert the new form when it has been fully edited
                row.insertBefore($(template));
                // Update number of total forms
                $(totalForms).val(parseInt(totalForms.val(), 10) + 1);
                nextIndex += 1;
                // Hide add button in case we've hit the max, except we want to add infinitely
                if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
                    addButton.parent().hide();
                }
                // The delete button of each row triggers a bunch of other things
                row.find("a." + options.deleteCssClass).click(function(e1) {
                    e1.preventDefault();
                    // Remove the parent form containing this button:
                    row.remove();
                    nextIndex -= 1;
                    // If a post-delete callback was provided, call it with the deleted form:
                    if (options.removed) {
                        options.removed(row);
                    }
111 112 113 114
                    $(document).trigger('formset:removed', [
                        row,
                        options.prefix
                    ]);
Administrator committed
115 116
                    // Update the TOTAL_FORMS form count.
                    var forms = $("." + options.formCssClass);
117

Administrator committed
118 119 120 121 122 123 124 125 126 127 128
                    $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
                    // Show add button again once we drop below max
                    if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
                        addButton.parent().show();
                    }
                    // Also, update names and ids for all remaining form controls
                    // so they remain in sequence:
                    var i, formCount;
                    var updateElementCallback = function() {
                        updateElementIndex(this, options.prefix, i);
                    };
129

Administrator committed
130 131
                    for (i = 0, formCount = forms.length; i < formCount; i++) {
                        updateElementIndex($(forms).get(i), options.prefix, i);
132 133
                        $(forms.get(i)).find("*")
                            .each(updateElementCallback);
Administrator committed
134 135 136 137 138 139
                    }
                });
                // If a post-add callback was supplied, call it with the added form:
                if (options.added) {
                    options.added(row);
                }
140 141 142 143
                $(document).trigger('formset:added', [
                    row,
                    options.prefix
                ]);
Administrator committed
144 145
            });
        }
146

Administrator committed
147 148 149 150 151
        return this;
    };

    /* Setup plugin defaults */
    $.fn.formset.defaults = {
152 153 154 155 156 157 158 159 160 161
        prefix: "form", // The form prefix for your django formset
        addText: "add another", // Text for the add link
        deleteText: "remove", // Text for the delete link
        addCssClass: "add-row", // CSS class applied to the add link
        deleteCssClass: "delete-row", // CSS class applied to the delete link
        emptyCssClass: "empty-row", // CSS class applied to the empty row
        formCssClass: "dynamic-form", // CSS class applied to each form in a formset
        added: null, // Function called each time a new form is added
        removed: null, // Function called each time a form is deleted
        addButton: null // Existing add button to use
Administrator committed
162 163 164 165 166 167 168
    };


    // Tabular inlines ---------------------------------------------------------
    $.fn.tabularFormset = function(options) {
        var $rows = $(this);
        var alternatingRows = function(row) {
169 170 171 172 173 174 175
            $($rows.selector).not(".add-row")
                .removeClass("row1 row2")
                .filter(":even")
                .addClass("row1")
                .end()
                .filter(":odd")
                .addClass("row2");
Administrator committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        };

        var reinitDateTimeShortCuts = function() {
            // Reinitialize the calendar and clock widgets by force
            if (typeof DateTimeShortcuts !== "undefined") {
                $(".datetimeshortcuts").remove();
                DateTimeShortcuts.init();
            }
        };

        var updateSelectFilter = function() {
            // If any SelectFilter widgets are a part of the new form,
            // instantiate a new SelectFilter instance for it.
            if (typeof SelectFilter !== 'undefined') {
                $('.selectfilter').each(function(index, value) {
                    var namearr = value.name.split('-');
192

Administrator committed
193 194 195 196
                    SelectFilter.init(value.id, namearr[namearr.length - 1], false);
                });
                $('.selectfilterstacked').each(function(index, value) {
                    var namearr = value.name.split('-');
197

Administrator committed
198 199 200 201 202 203 204 205 206 207 208
                    SelectFilter.init(value.id, namearr[namearr.length - 1], true);
                });
            }
        };

        var initPrepopulatedFields = function(row) {
            row.find('.prepopulated_field').each(function() {
                var field = $(this),
                    input = field.find('input, select, textarea'),
                    dependency_list = input.data('dependency_list') || [],
                    dependencies = [];
209

Administrator committed
210
                $.each(dependency_list, function(i, field_name) {
211 212
                    dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea')
                        .attr('id'));
Administrator committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
                });
                if (dependencies.length) {
                    input.prepopulate(dependencies, input.attr('maxlength'));
                }
            });
        };

        $rows.formset({
            prefix: options.prefix,
            addText: options.addText,
            formCssClass: "dynamic-" + options.prefix,
            deleteCssClass: "inline-deletelink",
            deleteText: options.deleteText,
            emptyCssClass: "empty-form",
            removed: alternatingRows,
            added: function(row) {
                initPrepopulatedFields(row);
                reinitDateTimeShortCuts();
                updateSelectFilter();
                alternatingRows(row);
            },
            addButton: options.addButton
        });

        return $rows;
    };

    // Stacked inlines ---------------------------------------------------------
    $.fn.stackedFormset = function(options) {
        var $rows = $(this);
        var updateInlineLabel = function(row) {
244 245 246 247 248 249 250
            $($rows.selector).find(".inline_label")
                .each(function(i) {
                    var count = i + 1;

                    $(this).html($(this).html()
                        .replace(/(#\d+)/g, "#" + count));
                });
Administrator committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        };

        var reinitDateTimeShortCuts = function() {
            // Reinitialize the calendar and clock widgets by force, yuck.
            if (typeof DateTimeShortcuts !== "undefined") {
                $(".datetimeshortcuts").remove();
                DateTimeShortcuts.init();
            }
        };

        var updateSelectFilter = function() {
            // If any SelectFilter widgets were added, instantiate a new instance.
            if (typeof SelectFilter !== "undefined") {
                $(".selectfilter").each(function(index, value) {
                    var namearr = value.name.split('-');
266

Administrator committed
267 268 269 270
                    SelectFilter.init(value.id, namearr[namearr.length - 1], false);
                });
                $(".selectfilterstacked").each(function(index, value) {
                    var namearr = value.name.split('-');
271

Administrator committed
272 273 274 275 276 277 278 279 280 281 282
                    SelectFilter.init(value.id, namearr[namearr.length - 1], true);
                });
            }
        };

        var initPrepopulatedFields = function(row) {
            row.find('.prepopulated_field').each(function() {
                var field = $(this),
                    input = field.find('input, select, textarea'),
                    dependency_list = input.data('dependency_list') || [],
                    dependencies = [];
283

Administrator committed
284
                $.each(dependency_list, function(i, field_name) {
285 286
                    dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea')
                        .attr('id'));
Administrator committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
                });
                if (dependencies.length) {
                    input.prepopulate(dependencies, input.attr('maxlength'));
                }
            });
        };

        $rows.formset({
            prefix: options.prefix,
            addText: options.addText,
            formCssClass: "dynamic-" + options.prefix,
            deleteCssClass: "inline-deletelink",
            deleteText: options.deleteText,
            emptyCssClass: "empty-form",
            removed: updateInlineLabel,
            added: function(row) {
                initPrepopulatedFields(row);
                reinitDateTimeShortCuts();
                updateSelectFilter();
                updateInlineLabel(row);
            },
            addButton: options.addButton
        });

        return $rows;
    };

    $(document).ready(function() {
        $(".js-inline-admin-formset").each(function() {
            var data = $(this).data(),
                inlineOptions = data.inlineFormset;
318 319

            switch (data.inlineType) {
Administrator committed
320 321 322 323 324 325 326 327 328 329
            case "stacked":
                $(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options);
                break;
            case "tabular":
                $(inlineOptions.name + "-group .tabular.inline-related tbody:first > tr").tabularFormset(inlineOptions.options);
                break;
            }
        });
    });
})(django.jQuery);