Note:

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

lib/formslib.php Select all or none

From MoodleDocs
Revision as of 15:22, 3 December 2007 by Nicolas Connault (talk | contribs)

Moodle1.9

A new form element, selectallornone, enables developers to effortlessly group checkboxes together and add a link/button controller to check or uncheck all the checkboxes at once. You can add as many of these groups of checkboxes as you want, the only rule is that they must be named differently, and the name must be an integer. Here is a sample code:

       $mform->addElement('advcheckbox', 'test1', 'Test 1', null, array('group' => 1));
       $mform->addElement('advcheckbox', 'test2', 'Test 2', null, array('group' => 1));
       $mform->addElement('selectallornone', 1);
       $mform->addElement('advcheckbox', 'test3', 'Test 3', null, array('group' => 2));
       $mform->addElement('advcheckbox', 'test4', 'Test 4', null, array('group' => 2));
       $mform->addElement('selectallornone', 2, get_string("checkallornone"), array('style' => 'font-weight: bold;'), 1);
       $mform->setDefault('test3', 1);
       $mform->setDefault('test4', 1);

This creates 4 checkboxes and 2 links, one below each group of 2 checkboxes. The API is as follows:

void constructor HTML_QuickForm_selectallornone::HTML_QuickForm_selectallornone ([mixed $elementName = NULL [, string $text = NULL [, mixed $attributes = NULL [, int $originalValue]]]]]])

mixed  $elementName This also serves as the checkbox group name. It must be a unique integer (unique per selectallornone element)
string $text (optional) Link display text. Defaults to get_string('selectallornone', 'form')
mixed  $attributes (optional) Either a typical HTML attribute string or an associative array 
int    $originalValue (optional) Defaults to 0; The general original value of the checkboxes being controlled by this element. 

To explain the last parameter, original value: Imagine that you have 50 checkboxes in your form, which are all unchecked when the form first loads, except 5 or 6 of them. The logical choice here would be to set the "select all/select none" link to check all the checkboxes upon first click, then to uncheck them all upon the next click and so on. If the situation was reversed, with most of the checkboxes already checked by default, then it would make more sense to have the first action uncheck all the checkboxes. The last param of this element lets you decide which is the overall state of your group of checkboxes.