Drupal 8: Form API Autocomplete Filtering By Role

Michalak Drupal Commerce Developer

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'],
        ],
      ],
    );

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.