mod/feedback/amd/src/usetemplate.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * Javascript module for using an existing template
  17. *
  18. * @module mod_feedback/usetemplate
  19. * @copyright 2021 Peter Dias
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import ModalForm from 'core_form/modalform';
  23. import Notification from 'core/notification';
  24. import {getString} from 'core/str';
  25. const selectors = {
  26. modaltrigger: '[data-action="usetemplate"]',
  27. };
  28. let initialized = false;
  29. /**
  30. * Initialize module
  31. */
  32. export const init = () => {
  33. if (initialized) {
  34. // We already added the event listeners (can be called multiple times).
  35. return;
  36. }
  37. document.addEventListener('click', event => {
  38. // Use the template.
  39. const trigger = event.target.closest(selectors.modaltrigger);
  40. if (trigger) {
  41. event.preventDefault();
  42. const modalForm = new ModalForm({
  43. modalConfig: {
  44. title: getString('use_this_template', 'mod_feedback'),
  45. },
  46. formClass: 'mod_feedback\\form\\use_template_form',
  47. args: {
  48. id: trigger.getAttribute('data-dataid'),
  49. templateid: trigger.getAttribute('data-templateid')
  50. },
  51. saveButtonText: getString('save', 'core')
  52. });
  53. // Show a toast notification when the form is submitted.
  54. modalForm.addEventListener(modalForm.events.FORM_SUBMITTED, event => {
  55. if (event.detail.result) {
  56. window.location.assign(event.detail.url);
  57. } else {
  58. Notification.addNotification({
  59. type: 'error',
  60. message: getString('saving_failed', 'mod_feedback')
  61. });
  62. }
  63. });
  64. modalForm.show();
  65. }
  66. });
  67. initialized = true;
  68. };