Can I add rules to a moodle form element (or not) depending on the users input?

Can I add rules to a moodle form element (or not) depending on the users input?

by Luis de la Torre -
Number of replies: 2

Here is the thing.

I have two elements in my module moodle form:

$mform->addElement('selectyesno', 'myconditionalelement', get_string('myconditionalelement', 'ejsapp'));

$mform->addElement('text', 'dependentelement', get_string('dependentelement', 'ejsapp'));

If the user selects "yes" in the first element (myconditionalelement), I would like to use addRule to set the second element as a required param in the form in order to be accepted.

Something like:

if($mform->get_element_value('myconditionalelement') == 1) {

$mform->addRule('dependentelement', null, 'required', null, 'client');

}

I know the previous code is not right, but I think it gives an idea about what I want to do. Is this possible? And if it is, could someone please tell me how to do it?

Thanks! smile

Average of ratings: Useful (1)
In reply to Luis de la Torre

Re: Can I add rules to a moodle form element (or not) depending on the users input?

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Add a function 'validation' to your form:

public function validation($data, $files) {

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

if ($data['myconditionalelement']) {

if (empty($data['dependentelement'])) {

$errors['dependentelement'] = get_string('required');

}

}

 

This doesn't do dynamic validation within the client browser, but should still be good enough.

Average of ratings: Useful (2)
In reply to Davo Smith

Re: Can I add rules to a moodle form element (or not) depending on the users input?

by Luis de la Torre -

Yup that did the trick.

Thanks once again, Davo.