Allow multiple values for data parameter when select2 is multiple

Created on 8 May 2025, about 2 months ago

Problem/Motivation

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).

Steps to reproduce

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.

Proposed resolution

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:

✨ Feature request
Status

Active

Version

2.0

Component

Field widgets

Created by

πŸ‡ͺπŸ‡ΈSpain cmarrufo

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024