javascript.txt 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. ======================================
  2. JavaScript customizations in the admin
  3. ======================================
  4. .. _admin-javascript-inline-form-events:
  5. Inline form events
  6. ==================
  7. You may want to execute some JavaScript when an inline form is added or removed
  8. in the admin change form. The ``formset:added`` and ``formset:removed`` events
  9. allow this. ``event.detail.formsetName`` is the formset the row belongs to.
  10. For the ``formset:added`` event, ``event.target`` is the newly added row.
  11. .. versionchanged:: 4.1
  12. In older versions, the event was a ``jQuery`` event with ``$row`` and
  13. ``formsetName`` parameters. It is now a JavaScript ``CustomEvent`` with
  14. parameters set in ``event.detail``.
  15. In your custom ``change_form.html`` template, extend the
  16. ``admin_change_form_document_ready`` block and add the event listener code:
  17. .. code-block:: html+django
  18. {% extends 'admin/change_form.html' %}
  19. {% load static %}
  20. {% block admin_change_form_document_ready %}
  21. {{ block.super }}
  22. <script src="{% static 'app/formset_handlers.js' %}"></script>
  23. {% endblock %}
  24. .. code-block:: javascript
  25. :caption: app/static/app/formset_handlers.js
  26. document.addEventListener('formset:added', (event) => {
  27. if (event.detail.formsetName == 'author_set') {
  28. // Do something
  29. }
  30. });
  31. document.addEventListener('formset:removed', (event) => {
  32. // Row removed
  33. });
  34. Two points to keep in mind:
  35. * The JavaScript code must go in a template block if you are inheriting
  36. ``admin/change_form.html`` or it won't be rendered in the final HTML.
  37. * ``{{ block.super }}`` is added because Django's
  38. ``admin_change_form_document_ready`` block contains JavaScript code to handle
  39. various operations in the change form and we need that to be rendered too.