edit_form.php saved array of saved array element is changing

edit_form.php saved array of saved array element is changing

by sebastian seitz -
Number of replies: 2

Hi,

i hope i can explain what i mean...

My Plugin has following edit_form.php 

[code lang]

  protected function specific_definition($mform) {

        // Section header title according to language file.

        $mform->addElement('header', 'config_header', get_string('blocksettings', 'block'));

        $allusercourses = array();

        $courses = enrol_get_my_courses(); 

        foreach ($courses as $c) {

            $allusercourses[] = $c->fullname;

        }

        $mform->addElement('select', 'config_cid', 'choose your course', $allusercourses);

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

[/code]

Problem:

The user can choose a course he is enrolled in at the configuration page of the plugin.
When the user hit the "save changes" button the number of the choosed array element is saved.

The problem is, if the enrolled course list from the user is changing (maybe he is no longer in some courses), the saved number of the array element is then pointing to another array element, because the array of enrolled courses has changed. 

It is a simple block plugin which is showing the coursename which the user has choosen in the configuration. But after the users enrolled course list has changed, there is a wrong coursename in the block, not the initially choosen one.


Question:
How can i save the course id when choosing coursename in the plugin configuration? I think the form will only store the array number and not the name or id of the course.

best regards
basti

Average of ratings: -
In reply to sebastian seitz

Re: edit_form.php saved array of saved array element is changing

by Andreas Grabs -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers Picture of Translators

Hi Sebastian,

it looks like your problem is the 0-based array you are using:

$allusercourses[] = $c->fullname;

If your array is changed, by altering the order or number of courses, the saved id points to the wrong element.
You can avoid this by using real ids instead:

$allusercourses[$c->id] = $c->fullname;

Maybe it helps.

Best regards
Andreas

In reply to Andreas Grabs

Re: edit_form.php saved array of saved array element is changing

by sebastian seitz -
wow, that`s so easy smile

Why programmers are so intelligent and i am not!? but i am happy that i understand your post and that this was the solution! Big thanks!