How to create an entity reference field in Drupal 8 programmatically?

Allex picture Allex · Apr 15, 2015 · Viewed 9.1k times · Source

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?

Answer

sareed picture sareed · Nov 28, 2017

So I can hopefully find this faster if I need to again...

Create field storage:

 if (!$field_storage = FieldStorageConfig::loadByName($entity_type, $field_name)) {
   FieldStorageConfig::create([
     'field_name' => $field_name,
     'entity_type' => $entity_type,
     'type' => $type,
     'cardinality' => -1,

     // Optional to target entity types.
     'settings' => [
       'target_type' => $entity_target_type, // Ex: node, taxonomy_term.
     ],
   ])->save();
 }

Create field:

FieldConfig::create([
  'field_name' => $field_name,
  'entity_type' => $entity_type,
  'bundle' => $bundle,
  'label' => $label,
  'cardinality' => -1,

  // Optional to target bundles.
  'settings' => [
    'handler' => 'default',
    'handler_settings' => [
      'target_bundles' => [
        $vid1,
        $vid2,
      ],
    ],
  ],
])->save();