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