Hi,
In a plugin I'm developing, I needed to have a select act on change the same way as a nosubmit button does, so that it reloads the updated form without going through validation. The form layout needed to be updated on reload based on the newly selected option.
What I have so far:
In my mod_form's definition, I turned my select into a noSubmitButton emulator like so:
$mform->addElement('select', 'id_source', get_string('source', 'polyvideo'), $sourcetypes, $attributes);
$mform->addHelpButton('id_source', 'source', 'polyvideo');
$mform->registerNoSubmitButton('id_source');
Then I placed a handler to submit the form on change in my amd module.
I don't think it's going to be up for a best practice award but it works just like a noSubmitButton, skipping validation and reloading the updated form.
I then use the $_POST variable to use the submitted data as a condition in the definition() method to build my form accordingly as such:
$source = '1';
if (isset($_POST['id_source'])) {
$source = $_POST['id_source'];
}
if ($source === '1') {
//Using repeat elements to build the form
);
} else {
if ($source === '2' || $source === '3') {
//Using conventional addElement to build the form
}
}
I know we're not supposed to use $_POST in Moodle, but I haven't found a way to access this data from the definition with the other methods so if anyone can help me on that...
I also have some JS in the background to delete elements dynamically.
I was getting a warning from the browser everytime I changed the selected option:
Leave site?
Changes you made may not be saved.
They were saved though. So I added this little bit of code in JS to get rid of that:
window.onbeforeunload = function(e) {
e.preventDefault();
e.stopPropagation();
};
Now I think this is not the cleanest nor most efficent code in a Moodle environement but I'm pretty new to Moodle and I might have missed some fairly obvious better alternatives.
If anyone has concerns, reserve, (anger?) about this code and can think of a more Moodle appropriate way of doing this I'd really like your input!