Backwards compatible collapsible forms

If you are lucky enough to be running Moodle 2.5 the chances are you will have encountered the wonderful new collapsible forms. I’m really excited to get these onto our production server as they remove the user fear factor which can result from displaying a form with too many options

Collapsible Form Sections

If you are coding a new Moodle form and you want to take advantage of this, the sections can be collapsed or expanded like this:

$mform->addElement('header', 'generalsection', 'General Header');
//expanded
$mform->setExpanded('generalsection');
//collapsed
$mform->setExpanded('generalsection', false);

Great! But what about if you want this form to work with Moodle 2.4 or earlier? The best solution to this is just to check that the setExpanded method exists within the mform class, and then to wrap your code with an if statement.

$mform->addElement('header', 'generalsection', 'General Header');
if(method_exists($mform, 'setExpanded')){
        $mform->setExpanded('generalsection');
}

Hope that helps someone out there!

One thought on “Backwards compatible collapsible forms”

  1. hii,

    I added the setExpanded method in the mform class yet i am unable to make my form headers collapsible. i am working with moodle 2.3. can you please help me out.

Leave a Reply