summaryrefslogtreecommitdiff
path: root/docs/ref/contrib/admin/javascript.txt
blob: ce94176691ca08faaee81b8312b5112fe02f5813 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
======================================
JavaScript customizations in the admin
======================================

.. _admin-javascript-inline-form-events:

Inline form events
==================

You may want to execute some JavaScript when an inline form is added or removed
in the admin change form. The ``formset:added`` and ``formset:removed`` events
allow this. ``event.detail.formsetName`` is the formset the row belongs to.
For the ``formset:added`` event, ``event.target`` is the newly added row.

.. versionchanged:: 4.1

    In older versions, the event was a ``jQuery`` event with ``$row`` and
    ``formsetName`` parameters. It is now a JavaScript ``CustomEvent`` with
    parameters set in ``event.detail``.

In your custom ``change_form.html`` template, extend the
``admin_change_form_document_ready`` block and add the event listener code:

.. code-block:: html+django

    {% extends 'admin/change_form.html' %}
    {% load static %}

    {% block admin_change_form_document_ready %}
    {{ block.super }}
    <script src="{% static 'app/formset_handlers.js' %}"></script>
    {% endblock %}

.. code-block:: javascript
    :caption: app/static/app/formset_handlers.js

    document.addEventListener('formset:added', (event) => {
        if (event.detail.formsetName == 'author_set') {
            // Do something
        }
    });
    document.addEventListener('formset:removed', (event) => {
        // Row removed
    });

Two points to keep in mind:

* The JavaScript code must go in a template block if you are inheriting
  ``admin/change_form.html`` or it won't be rendered in the final HTML.
* ``{{ block.super }}`` is added because Django's
  ``admin_change_form_document_ready`` block contains JavaScript code to handle
  various operations in the change form and we need that to be rendered too.