Currently, I am working on a module that offers the function for users that belong to specific user roles to be able to write private messages to each other.
In order for the sender to be able to add a recipient to his message, I used Drupal's EntityAutocomplete
class and as the #target_type
I chose user
so that the sender gets to choose his recipient(s) from an automatically generated list of users (autocompletion).
The code I used to build the form and create the recipient textfield that contains the autocompletion list of the users looks something like the following:
public function buildForm(array $form, FormStateInterface $form_state){
$form['recipient'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#title' => t('Recipient:'),
'#required' => TRUE,
];
}
How can I filter the autocompletion list that is being automatically generated by the EntityAutocomplete
class so that only those users appear in the list that belong to a certain role (e. g., if a user belongs to the role "Therapist" they should appear in the autocompletion list, but other users that don't belong to that role should not).
So far, any user appears in the autocompletion list of results. Any thoughts on this will be highly appreciated — thank you very much in advance.