Guys, I need a validation in moodle using mform. I need to check whether a check box checked in button click. I am new to mform validation please help.
public function validation($data, $files) {
$errors = parent::validation($data, $files);
if($data['checkbox'] == false) {
$errors['checkbox'] ="The check box was not selected";
}
return $errors;
}
Yael - developer in OPENAPP
Yael, suppose I need to call this javascript function on a button click on the following mform given below:
$this->add_action_buttons(false, 'submit');
How can call the function on action button, just like onclick() method. How can I do it here?
Could you explain a little more clearly what you are trying to achieve with this?
For example, if you are just wanting someone to be forced to tick a checkbox, before the form can be submitted, then:
$mform->addRule('NAME OF CHECKBOX', null, 'required');
will work.
Alternatively, as already described, you can check if the checkbox has been ticked after the page has been submitted, via the form's 'validation' function.
If you really need to add javascript to the page, then https://docs.moodle.org/dev/JavaScript_guidelines is a good starting point - there is no particular support in Moodle forms for inserting custom javascript (mostly because there is no need to do this in most situations).
Dear Friend Davo ,
I am creating a group of dynamic radiobuttons like the following:
for ($i = 1; $i <= 4; $i++) {
$ansgroup = array(
$mform->createElement('radio', 'answercorrect', '', '', $i,
array('class' => "mock_answerradio")),
$mform->createElement('text', "answertext[$i]", '', array('size' => 30)),
);
$mform->addGroup($ansgroup, 'answer', get_string('answer','questionpool').$i, array(' '), false);
$mform->setType("answertext[$i]", PARAM_RAW);
}
How can add rule to these radio buttons in such a button it should check whether atleast one of the radio button selected before submission. Please help buddy!!
I've already answered your question (more or less):
$mform->addRule('answercorrect', null, 'required');
(Not that I've tested this code, but it should work).
Dear Davo,
I am getting error like the following:
QuickForm Error: nonexistent html element Element 'answercorrect' does not exist in HTML_QuickForm::addRule()
Please take a look buddy!!
Hello all!
I faced with a same situation In my code. Error has been shown for "addRule" . Sample:
$radioarray[] =& $mform->createElement('radio', 'yesno', '', get_string('yes'), 1);
$radioarray[] =& $mform->createElement('radio', 'yesno', '', get_string('no'), 0);
$mform->addGroup($radioarray, 'radioarr', '', array(' '), false);
$mform->addRule('yesno', get_string('missinanswer', 'enrol_survey'), 'required');
Change third row solved the problem:
$mform->addGroup($radioarray, 'yesno', '', array(' '), false);
(In addGroup and createElement must be the same name)
I will be glad if my example will help someone