Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 378
Allex Avatar asked Apr 15 '15 11:04

Allex


People also ask

How do I create a entity reference field in Drupal 8?

Step1: Create settings related to Entity Reference module from backend. Step2: Create Content type. Step3: Add/Edit fields of content type through Home -> Administration -> Structure -> Content Types -> Content type (ie:user) -> Manage fields, Add a new Entity Reference field. Step4: Choose the number of values.

How do I get entity field value in Drupal 8?

You do not need to convert $entity into an array, this would simply work. $entity->get('field_name')->getValue();


2 Answers

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.

like image 133
Christian Avatar answered Nov 11 '22 19:11

Christian


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();
like image 35
sareed Avatar answered Nov 11 '22 18:11

sareed