Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Modal and AJAX forms

From MoodleDocs

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 element = e.target;
       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