Modal and AJAX forms

From MoodleDocs
Revision as of 14:45, 27 January 2021 by Marina Glancy (talk | contribs) (Created page with "== Modal and AJAX forms == Important: This documentation is for Moodle 3.11 and above, for previous versions please use MForm Modal tutorial on how to create your own mod...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Modal and AJAX forms

Important: This documentation is for Moodle 3.11 and above, for previous versions please use MForm Modal tutorial on how to create your own modal form.

Modal forms

To display a moodleform in a modal popup you need to: - create a class with the form definition extending \core_form\modal , do not add submit/cancel buttons to the form definition; - initialize the form in the listener to some javascript event (for example, a click on the "Add" or "Edit" link)

Example of the JS code: document.querySelectorAll('[data-role=editfield][data-id]').addEventListener('click', e => {

       e.preventDefault();
       const modal = new ModalForm({
           // Pass the name of your class here:
           formClass: "core_customfield\\field_config_form", 
           // Add as many arguments as you need (or no arguments):
           args: {id: element.getAttribute('data-id')},
           // Pass any settings to the modal dialogue config, for example, the title of the dialogue:
           modalConfig: {title: Str.get_string('editingfield', 'core_customfield', element.getAttribute('data-name'))},
           // Pass the element that should get the focus after the modal dialogue is closed:
           returnFocus: element
       });
       // Override onSubmitSuccess() method if you want to execute something on form submit:
       modal.onSubmitSuccess = (response) => {
           console.log(response);
       }; 

});

AJAX forms

To load and submit a moodleform dynamically via AJAX requests you need to: - create a class with the form definition extending \core_form\modal , for AJAX forms you will need to add the regular submit/cancel buttons; - create a container element in your HTML where the form should be loaded; - initialize the form in the javascript; - load the form in the listener to some javascript event (or do it on page load)

.... TBC