Author - Pawandeep Kaur Post Views - 6 views

Moodle Checkbox Validation: Require One Checkbox Selection

When working with Moodle forms (mform), a common requirement is to ensure that at least one checkbox is selected from a group of options. Many developers try to use addRule() for this, but Totara/Moodle does NOT support addRule() directly on checkbox groups.

Why this problem happens

:Checkbox groups in Totara/Moodle are stored as arrays. The addRule() method only works with single form elements, not grouped arrays. Because of this limitation, addRule() cannot validate that at least one checkbox is selected.

Example: Checkbox group

Suppose we are creating a form where users must select at least one cancellation reason. For this, we have a checkbox group named cancellation_reasons:

$reasons = [];$reasons[] = $mform->createElement(‘checkbox’,‘cancellation_reasons[leave]’,,‘Leave’);$reasons[] = $mform->createElement(‘checkbox’,‘cancellation_reasons[equipment_delay]’,,‘Equipment Delay’);$reasons[] = $mform->createElement(‘checkbox’,‘cancellation_reasons[reschedule]’,,‘Reschedule’);$reasons[] = $mform->createElement(‘checkbox’,‘cancellation_reasons[other]’,,‘Other’);

$mform->addGroup($reasons,‘cancellation_reasons’,‘Cancellation Reasons’,html_writer::empty_tag(‘br’),false);

Now, when the form is submitted, the data will be sent like this:

$data[‘cancellation_reasons’] = [

    ‘leave’ => 1,

    ‘equipment_delay’ => 0,

    …

];

At this stage, the UI is complete, but the form will still submit even if no checkbox is selected.

To enforce the “at least one checkbox selected” rule, we must override the validation() method in the form class.

 public function validation($data, $files) {

    $errors = parent::validation($data, $files);

    if (empty($data[‘cancellation_reasons’]) ||

        !array_filter($data[‘cancellation_reasons’])) {

        $errors[‘cancellation_reasons’] =

            ‘Please select at least one cancellation reason.’;

    }

    return $errors;

}

So, in the end, to validate group-level elements in Moodle, we need to use the validation() method rather than the addRule() method

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri