1

I am trying to create an autocomplete field for users. The following code is fine for username searches but the requirement is for a search by any part of the user's first and last name.

$form['user'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#selection_settings' => [
    'include_anonymous' => FALSE,
  ],
];

I am wondering what the best way to filter by first and last name is. Is it even possible to use 'entity_autocomplete'? It doesn't look like any of the EntityAutocomplete class methods would make this possible and I'm not clear on whether or not the '#selection_handler' and '#selection_settings' properties could be helpful.

5

The selection_handler element property allows to specify a plugin id of a class that would override the default selection handler for EntityAutocompleteMatcher. A separate plugin would be able to build a different Entity Query.

Create a plugin of EntityReferenceSelection type. This should be a derivative of the DefaultSelection plugin similar to TermSelection.

Then you can override entityQueryAlter to add additional conditions to the entity query.

  • 1
    Instead of a custom class, you could also configure a view the way you want it. If you're not sure about the exact selection handler id and way to structure the configuration for it, just set up an entity reference field in the UI using a view and then look at the generated config in the field. – Berdir Apr 20 '16 at 23:26
  • I successfully created an 'EntityReferenceSelection' plugin and modified the default behavior of the UserSelection class to a limited degree. I'm trying to modify the results returned to the autocomplete textfield to show user first and last names with a table join but 'entityQueryAlter' is executed after 'getReferenceableEntities'. Trying to add table joins in 'getReferenceableEntities' and 'buildEntityQuery' results in an error. So, I have been able to implement part of the intended functionality. Thank you for your help guys! – user320691 Apr 27 '16 at 15:25

Your Answer

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

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