1

There is the entity_autocomplete field type which I expect should just work for core entities. I have created my own entity using Drupal console and would like to query those entities with an autocomplete field. I understand that you need some sort of callback to query the correct field and return the response.

I've had a good search but can't find any good examples of how to do this. Is there somewhere in core, contrib module or elsewhere that has a good example?

  • 1
    The entity reference field and autocomplete widgets work for any entity type (custom or not). You can extend the functionality for your custom entity type, by providing a custom #selection_handler in the render array, but it's not mandatory. See drupal.org/node/2418529 for some examples – Clive Jan 22 at 11:45
  • Thank you for your reply. Is there more about the #selection_handler anywhere? Do I need to specify the fields to query for the autocomplete? I did try creating the field and it kicks off the request which I can see in the network tab of developer tools but when I visit the URL directly the response is an empty array. – Oliver P Jan 22 at 11:56
  • 1
    That's up to your really, the default selection handler (Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection) covers a lot of use cases so you might not need to. If you do need to, create a plugin based on that class, like Drupal\node\Plugin\EntityReferenceSelection\NodeSelection, and just make the changes you need to in there. But I'd try without specifying a selection handler first, just a sensible #target_type, and see if you even need to extend – Clive Jan 22 at 12:01
  • I've just dumped the conditions of the query and found it's only querying the "name" field in the database. If I manually fill out the "name" field in the database then all works fine. I'm happy to set the "name" field and call it job done but I'm curious as to how to get it to query additional/other fields. – Oliver P Jan 22 at 12:57
  • See the previous comment - you'll need to write your own selection handler with your own solution for ::getReferenceableEntities(), ::countReferenceableEntities(), ::validateReferenceableEntities(), etc – Clive Jan 22 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.