General developer forum

Custom Profile Fields - Multiple Checkboxes.

Picture of Evan Glicakis
Custom Profile Fields - Multiple Checkboxes.

Hello, I am fairly new to Moodle and am working on a project to extend Moodle courses, I've been using a plugin that "transfers" the user profile fields into course fields and it's working fairly well.

My task at hand is to have a field that would allow the course creator to select multiple values from a list of checkboxes. I know there exists MultiSelect menu's and I do have one working, however, the UX would be much better with multiple checkboxes.

I tried changing the method that adds the elements to the form, however advcheckbox.

This is how my form looks:

$options = explode("\n", $this->field->param1);
        foreach($options as $key => $option){
            $this->options[$key] = format_string($option);
            $mform->addElement('advcheckbox',$this->inputname.'[]',$this->options[$key], null, array('group'=>1),array(0,1));

Average of ratings: -
Picture of Evan Glicakis
Re: Custom Profile Fields - Multiple Checkboxes.

Alright so I figured out how to do it 

in the edit_field_add function you would create your checkbox elements, i use the var $i to give the array key's values however, it can be 'name[]' 

options is an array of strings containing the list of checkbox options. I use these as my values.

$i = 1;
$checkboxes = array();
foreach ($this->options as $key) {
     $checkboxes[] = &$mform->createElement('advcheckbox', $this->inputname . "[$i]", '', $key, array('group' => 1), array('',$key));

to retrieve the values of this form simply call $_POST['name] and it will return either the $key or '' depending if the box is ticked or not. 

To save these values to the database, I iterate through the values that were ticked an store them. With the edit_save_data_preprocess method. I'm not too sure if this is the preferred way of doing it, but it works.

Average of ratings: -