- Issue created by @cmarrufo
Hi everyone. I open this issue because I think that allow multiple values through data
parameter could be a good idea. In my case, I'm developing a job alert system notification, the user can edit its preferences through a form.
My idea is preselected the current user preferences on each field, that is, mark default values ββin each field. For single fields (not multiple) the #default_code
of the Drupal Form API it's sufficient but non for #multiple
select2 fields. Reading the official documentation, the data
parameter allow multiple values: https://select2.org/data-sources/formats. But when I try to use it, doesn't work and I see that select2.js do not accept multiple values (array).
To reproduce this you can create two form fields. One as single select2 and another one as multiple (#multiple => TRUE)
For single select2, you can set a preselected value through #default_value property but this don't work for a multiple select.
I propose make some changes on select2.js to allow multiple values in data
parameter.
Usage example:
If our options key are numbers:
$build['country'] = [
'#type' => 'select2',
'#title' => $this->t('Country'),
'#options' => $country_options,
'#empty_option' => $this->t('Select Country'),
'#multiple' => TRUE,
'#select2' => [
'allowClear' => TRUE,
'data' => [
['id' => 13],
['id' => 14]
],
],
];
Or when our option key it's a string:
$build['country'] = [
'#type' => 'select2',
'#title' => $this->t('Country'),
'#options' => $country_options,
'#empty_option' => $this->t('Select Country'),
'#multiple' => TRUE,
'#select2' => [
'allowClear' => TRUE,
'data' => [
['id' => 'all'],
],
],
];
Result for numbers:
Result for text:
Active
2.0
Field widgets