How to create an entity reference field in Drupal 8 programmatically

drupaldrupal-8

I want to create an entity reference field in Drupal 8 using my custom module. Like when someone clicks a link on a Drupal page, an entity reference field would be created in the page node type automatically.

Can anyone help me with this?

Best Answer

This will create an entity reference field for node content types with the article bundle.

$form['node_id'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => $this->t('Node'),
    '#target_type' => 'node',
    '#selection_settings' => ['target_bundles' => ['article']],
    '#tags' => TRUE,
    '#size' => 30,
    '#maxlength' => 1024,
  );

Note you can change target_type for other entities like taxonomy_term.

Related Topic