Set default/selected item in drop-down list (and some thoughts)

Set default/selected item in drop-down list (and some thoughts)

by Richard Jones -
Number of replies: 1
Picture of Plugin developers Picture of Testers

Hi

I know there is documentation and a previous thread on this which I believe I have followed but I still can't figure it what the issue is from those sources.  The code I have is this: 

        // Drop-down lists for page linking.
        $pagetitles = $this->_customdata['pagetitles'];
        $sequence = $this->_customdata['sequence'];
        // setSelect needs an associative array of items?
        $titles = [];
        foreach($pagetitles as $p) {
                $titles[$p] = $p;
        }
        $setprevelement = $mform->addElement('select', 'prevpageid', get_string('prev', 'mod_simplelesson'), $titles);
        $setnextelement = $mform->addElement('select', 'nextpageid', get_string('next', 'mod_simplelesson'), $titles);
        // Attempt to set the page titles drop-down to reflect current structure.
        // Find the current title and the next and previous in the array.
        $setprev = $pagetitles[$sequence - 1];  // If 0 will be string 'none'.
        $setnext = ($sequence < count($pagetitles)) ? $pagetitles[$sequence + 1] : get_string('none', 'mod_simplelesson');
        $setprevelement->setSelected($setprev);
        $setnextelement->setSelected($setnext);
        $mform->setType('nextpageid', PARAM_TEXT);
        $mform->setType('prevpageid', PARAM_TEXT);
An echo statement prints the title strings correctly but the setDefault doesn't set them in the drop-down list. This is intended only for Moodle 4.

Another question might be, should we continue with Moodleforms or simply use Bootstrap forms and/or the new Component Library as available for Moodle 4 if re-factoring code?  In the above case I could probably use a class to prepare the data for a Mustache template using html to set the selected/default item (eg https://getbootstrap.com/docs/4.0/components/forms/).

Thoughts welcome.

Average of ratings: -
In reply to Richard Jones

Re: Set default/selected item in drop-down list (and some thoughts)

by Richard Jones -
Picture of Plugin developers Picture of Testers
*An echo statement prints the title strings correctly but the setSelected (or equally using setDefault on $mform object) doesn't set them in the drop-down list.