Autocomplete form with preselection

Autocomplete form with preselection

by Andreas Stephan -
Number of replies: 1

Hello,

maybe anyone can help me with the autocomplete form using Ajax. Sofar I've managed to fetch the data from a service und save the selected data into the db.  It also sets the right preselection from the db, when the form is initialized., using valuehtmlcallback. Here's a small snippet from the code:

$attributes = array(
'multiple' => false,
'noselectionstring' => get_string('no_categories', 'tool_webanalytics'),
'ajax' => 'tool_webanalytics/categories',
'valuehtmlcallback' => function ($value) {
global $OUTPUT, $DB;
$rec = $DB->get_record('course_categories', array('id' => $value), 'name');
if (!$rec) {
return;
}
$categories = [
'label' => $rec->name,
'value' => $value
];
return $OUTPUT->render_from_template('tool_webanalytics/form-categories', $categories);
}
);

$mform->addElement('autocomplete', 'categories', get_string('categories', 'tool_webanalytics'), [], $attributes);
$mform->addHelpButton('categories', 'categories', 'tool_webanalytics');

The problem I have is, I am failing to preselect multiple entries. So for example:

$attributes = array(
'multiple' => true,
'noselectionstring' => get_string('no_categories', 'tool_webanalytics'),
'ajax' => 'tool_webanalytics/categories',
'valuehtmlcallback' => function ($value) {
global $OUTPUT;

$categories =
'label' => "My 1st label",
'value' => 2
], [
'label' => "My 2nd label",
'value' => 3
;

// WHAT COMES IN HERE???
}
);

Any advice is appreciated smile

Average of ratings: -
In reply to Andreas Stephan

Re: Autocomplete form with preselection

by Andreas Stephan -
Got it, actually it was very easy. You don't have to use valuehtmlcallback. Just pass in your selection inside addElement:

$mform->addElement('autocomplete', 'categories', get_string('categories', 'tool_webanalytics'), $selection, $attributes);

... where $selection is an associative Array, where key is your value and the array value is your label:
[
"your_value" = "your_label"
]
Average of ratings: Useful (1)