2

I have created a form field with user autocomplete as below.

$form['user_list'] = [
      '#title' => ('Select User'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#required' => TRUE,
      '#selection_settings' => [
        'include_anonymous' => FALSE,
        'roles' => ['sales'],
      ],
    ];

I used "#selection_settings" with roles specific, but this is not working. I want to filter user with "sales" only.

1
  • 1
    Not a full answer because I haven't verified it works yet: Based on the plugin code, it looks like what you want is ['#selection_settings']['filter']['role'] = [...];. The relevant code is in Drupal\user\Plugin\EntityReferenceSelection\UserSelection. Commented Nov 20, 2017 at 7:28

1 Answer 1

5

The selection settings array is passed to the plugin options, which in this case is Drupal\user\Plugin\EntityReferenceSelection\UserSelection.

In that class, you can see that the relevant array key is $options['filter']['role'], which is an array.

Therefore, the correct code here is:

$form['user_list'] = [
  '#title' => ('Select User'),
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#required' => TRUE,
  '#selection_settings' => [
    'include_anonymous' => FALSE,
    'filter' => [
      'role' => ['sales'],
    ],
  ],
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.