4

How do I add an autocomplete field in a class that extends FormBase?

I created a custom module, which uses a class that extends FormBase. I want to programmatically create a form field that autocompletes the username from the user registered in the site.

2 Answers 2

10

You use entity_autocomplete as #type for the form field. CommentForm::form() contains such a form field, for the administrator users to be able to change the author of a comment. This is the code it uses.

  // The uid field is only displayed when a user with the permission
  // 'administer comments' is editing an existing comment from an
  // authenticated user.
  $owner = $comment->getOwner();
  $form['author']['uid'] = [
    '#type' => 'entity_autocomplete',
    '#target_type' => 'user',
    '#default_value' => $owner->isAnonymous() ? NULL : $owner,
    // A comment can be made anonymous by leaving this field empty therefore
    // there is no need to list them in the autocomplete.
    '#selection_settings' => ['include_anonymous' => FALSE],
    '#title' => $this->t('Authored by'),
    '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
    '#access' => $is_admin,
  ];

As you can see from the code, you can also choose to include the anonymous user.

The result is shown in the following screenshot.

screenshot

2

Drupal 8.0 provides a form element specifically for autocomplete with any entity (implemented by the EntityAutocomplete class), and has some changes for custom autocomplete.

Look at the Drupal Change Records and search for autocomplete in the Keyword field; you will get a list of changes for Drupal 8. There is a change record that lists the changes for a custom autocomplete functionality by using the form properties #autocomplete_route_name and #autocomplete_parameters.

So with that information you should be able to add an entity autocomplete element in your form for users.

1
  • +1 on documenting your way of finding this but you might to include a code sample too from the last link otherwise someone will comment that you should do so. Which I just did ;)
    – Berdir
    Commented Nov 5, 2015 at 23:05

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.