Useful form snippets for multiple selections

When building forms it is useful to have widgets that select multiple values for you and enhance UI, if you have large select list I would recommend to use select2 module to make custom form use its widget you should first get an array of elements in a variable, like 

 $countries = $this->countryManager->getList();

then use that in form

    // Build excluded countries.
    $form['general']['excluded_countries'] = [
      '#type' => 'select2',
      '#multiple' => TRUE,
      '#options' => $countries,
      '#title' => $this->t('Shipping countries excluded from Auto Approval'),
      '#default_value' => $config->get('general.excluded_countries'),

so putting this array in  '#options' => $countries,  will make a nice widget for you to select multiple elements from long list.


If you have long list ot items which could slow down the widget, then don't use options part, leave it out and just add

      '#type' => 'select2',
      '#autocomplete' => TRUE,

so this way it will always make ajax request and search for the item, instead of preloading thousands of them.


Other useful tip is to use drupal core entity_autocomplete type of form field, which will make an autocomplete field where you can select any entity from autocomplete

    $form['terms'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#title' => $this->t('Terms'),
      '#description' => $this->t('Enter terms'),
      '#maxlength' => 128,
      '#size' => 128,
      '#default_value' => $config->get('terms'),

this will search all nodes with autocomplete and offer you to select ones you want.