Form syntax for repeating fields

Form syntax for repeating fields

by François Gannaz -
Number of replies: 0

Hello

I'm looking for an advice on the forms API in Moodle 2.2. In one sentence: "moodleform::repeat_elements()" seems weird because the fields are grouped by element name, not by repeating number. Is there a workaround?

Now in details:

I'm currently developing a new activity module. I used "mod_form" to set up the form of an instance. There are static fields, and also some repeating fields in varying number. So I looked at the code of "mod/choice". I saw there was a dedicated method called "moodleform::repeat_elements()". But the code that added and updated instances was a bit ugly. Each option for a choice was built field by field from the the posted form. Something like (simplified code):

foreach ($formresult->options as $key => $value) {
    $option = new StdClass;
    $option->field1 = $formresult->field1[$key];
    $option->field2 = $formresult->field2[$key];
    $option->field3 = $formresult->field3[$key];
    $DB->insert_record("choice_options", $option);
}

Is there a way to produce a better structured form? That is a HTML form where the repeated fields would be named "option[0][field]" instead of "option[field][0]" (cf l. 1000-1001 of "lib/formslib.php"). The PHP code would then be much prettier:

foreach ($formresult->options as $option) {
    $option = (object) $option;
    $DB->insert_record("choice_options", $option);
}

If this is not possible now, I'd like to suggest this change of API on the long term. I know it would break compatibility, but IMHO it would simplify the code of Moodle.

Thanks for any help or comment on this subject.

Average of ratings: -