Score:1

Entity autocomplete form API field with ViewsSelection handler

us flag

I'm trying to get an implementation of the Entity Autocomplete Form API field with a view selection handler working in Drupal 9.

I have seen some examples in New 'entity_autocomplete' form element added, but it shows how to use a default selection handler and they only appear to work in Drupal 8. Specifically it was possible to pass the view_name and display_name via the #selection_settings:

$form['user'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#selection_handler' => 'views',
  '#selection_settings' => [
    'view' => [
      'view_name' => 'users_view',
      'display_name' => 'users',
      'arguments' => []
    ], 
    'match_operator' => 'CONTAINS'
  ],
];

Starting with Drupal 9.x as per this Entity reference selection handlers should extend a base class change record, I noticed that the ViewsSelection::initializeView() method no longer does a lookup from $config['handler_settings'], but here isn't any reference to what the alternative is in Drupal 9 going forward and whether the ViewsSelection plugin was intended to support #selection_settings.

Score:1
cn flag

It's still possible to pass the options exactly as you have - a lookup from $config['handler_settings'] isn't needed in ViewsSelection::initializeView().

The #selection_settings are merged into the $configuration array provided to the plugin when it's initialised in EntityAutocomplete::validateEntityAutocomplete()

Using your code verbatim I can see the settings you're passing where expected:

enter image description here

baikho avatar
us flag
I see indeed that does pull through the Views details, I might have something else disrupting the behaviour. Will come back and confirm, thanks!
baikho avatar
us flag
Confirmed this to work on a fresh Drupal 9.3.0 installation, so something else is wrong in my setup. Thanks
liquidcms avatar
us flag
But this doesn't actually work does it? I have tried this even though no documentation suggesting this form element supports views. Regardless of what i set for view or display; output is the same as for default.
cn flag
It worked for me and the OP a year ago, on drupal >=9.3.0, that's the best I can tell you
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.