General developer forum

setting a checkbox unchecked in a form

 
6
setting a checkbox unchecked in a form
 

hi

I'm creating a checkbox like this:
$elementgroup[] = $mform->createElement('checkbox', 'mycheckbox', '',  checkboxLabel);

and I want to set that checkbox to be unchecked (e.g: have value  = 0)

I tried this and it doesn't work:

$mform->setDefault('mycheckbox', 0);

and

$mform->setDefault('mycheckbox', 1);


I tried this too:

$attributes = array('value' => '0');

$elementgroup[] = $mform->createElement('checkbox', 'mycheckbox', '',  checkboxLabel, $attributes);


any suggestions?

I want to be always false when printed to the user and prevent anything in the form from overriding it's false state.


I'm using moodle 3.1

 
Average of ratings: -
Picture of Marcus Green
Re: setting a checkbox unchecked in a form
Core developersParticularly helpful MoodlersPlugin developersTesters

Unfortunately the standard HTML checkbox does not not send a value if a checkbox is unchecked, this is an HTML thing not a Moodle thing.

However if you use the advanced checkbox it will work as you would expect. The syntax is more like

$elementgroup[] = $mform->createElement('advcheckbox', 'mycheckbox', '',  checkboxLabel, $attributes);

However it looks to me like there are too many quote marks in that example,

Here is some code copied from one of my plugins

 /* sets all gaps to the size of the largest gap, avoids giving clues to the correct answer */
 $mform->addElement('advcheckbox', 'fixedgapsize', get_string('fixedgapsize', 'qtype_gapfill'));
 $mform->addHelpButton('fixedgapsize', 'fixedgapsize', 'qtype_gapfill');


 
Average of ratings: -
6
Re: setting a checkbox unchecked in a form
 

I'm not talking about after the form is submitted but before
I'm talking about the first time it is presented to the user.

the form is producing this:

<input name="myCheckboxName" type="checkbox" value="1" checked="checked" id="id_myCheckboxName">

something is explicitly telling the checkbox to be checked


 
Average of ratings: -
Picture of Dave Emsley
Re: setting a checkbox unchecked in a form
Particularly helpful Moodlers

You do need the advanced check box. 

Have a look at https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#advcheckbox

In particular the part about the optional 6th parameter which indicates the default for checked or not.

Hope this helps.


Dave

 
Average of ratings: Useful (1)