Create a custom form field for entity reference with auto complete in Drupal 8.

The Entity reference module provides a auto complete field widget and this has been changed to a Form API element as 'entity_autocomplete'. This can be used in normal custom forms. Form element type can be used as 'entity_autocomplete' for entity reference fields. Following is a sample code structure to create a entity reference fields with in custom form.

$form['form_element'] = array(
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
  '#selection_handler' => 'default',
  '#selection_settings' => array(
    'target_bundles' => array('article'),
  ),
);

'target_bundles' can be used to restrict type of content which needs to be added for node reference.

If we want to allow an input of an entity using views entity reference, Below code will populate views entity reference results in auto complete field. Make sure you create the view and display and use the respective Ids under 'view_name', 'display_name'. Only views with a display of type "Entity Reference" are eligible.

$form['form_element'] = array(
    '#type' => 'entity_autocomplete',
    '#target_type' => 'node',
    '#selection_handler' => 'views',
    '#selection_settings' => array(
        'view' => array(
            'view_name' => 'view_id',
            'display_name' => 'entity_reference_display_id',
            'arguments' => array(),
        ),
    ),
);

 

Category: