Score:0

Trying to filter the results of the entity autocomplete form element

tw flag

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.

beltouche avatar
cn flag
See https://drupal.stackexchange.com/questions/250574/how-to-use-entity-autocomplete-for-user-target-type-with-specific-roles
Quetzcodecoatl avatar
tw flag
I didn't research this one thoroughly enough. Thanks, @beltouche!
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.