---
title: "Drupal 8: Form API Autocomplete Filtering By Role"
url: "https://michalak.world/posts/drupal-8-form-api-autocomplete-filtering-by-role/"
description: "Form API Autocomplete Filtering By Role"
summary: "Custom filtering on autocomplete fields by user role."
date: 2019-03-14
lastmod: 2026-08-19
tags: ["Drupal","Drupal 8","Form API"]
section: "posts"
author: "Michael Michalak"
site: "https://michalak.world/"
---

# Drupal 8: Form API Autocomplete Filtering By Role

Form API Autocomplete Filtering By Role

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

