Drupal 8 - Entity Autocomplete

10.06.2017

Drupal 8 has included an Entity Autocomplete element, which can be extremely useful when referencing entities within a form.

Render Array

The basic render array syntax is as follows:

<?php

$form['my_entity_autocomplete'] = array(
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node'
);

This will simply display a text field which will autocomplete after a certain amount of characters are entered.

Targeting Entities

You can target different entities with #target_type, like so:

<?php

$entity = 'node';

$form['my_entity_autocomplete'] = array(
  '#type' => 'entity_autocomplete',
  '#target_type' => $entity
);

Targeting Bundles

You can target different bundles with target_bundles, like so:

<?php

$entity = 'node';
$bundles = ['page'];

$form['my_entity_autocomplete'] = array(
  '#type' => 'entity_autocomplete',
  '#target_type' => $entity,
  '#selection_settings' => [
    'target_bundles' => $bundles
  ]
);

Default Values

To display the default value, you will need to assign the loaded entity:

<?php

$nid = $config->get('my_entity_autocomplete');
$node = \Drupal\node\Entity\Node::load($nid);

$form['my_entity_autocomplete'] = array(
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
  '#default_value' => $node
);

Further Reading

You can find more information on Drupal.org.