Skip to main content
  1. Posts/

Drupal 8: Form API Autocomplete Filtering By Role

·92 words·1 min·
Drupal Drupal 8 Form API

I have been creating a lot of custom forms for purchase order creation and custom shipping methods, using Drupal 8’s form API.

For the latest form, I needed to add an autocomplete field for user accounts that filtered by a specific role.

In the example below I only needed to show users with the role of ‘Supplier’

Example:

    $form['group']['field_user'] = array(
      '#type' => 'entity_autocomplete',
      '#title' => t('Add User'),
      '#description' => t('Example text goes here'),
      '#target_type' => 'user',
      '#selection_settings' => [
        'include_anonymous' => FALSE,
        'filter' => [
          'role' => ['supplier'],
        ],
      ],
    );
Michael Michalak
Author
Michael Michalak
Experienced Drupal consultant and Fractional CTO with over 13 years of expertise in backend development, optimization, and securing Drupal applications, specializing in custom module development, migrations, and enterprise integrations across various industries.