TransWikia.com

How to programmatically reference entities?

Drupal Answers Asked by sveggen on October 26, 2021

I am trying to reference an entity within my hook, so that every time a new entity is inserted, I create another entity referencing the first entity. I have not yet found a working way to reference an existing entity in my "field_content" when creating a new entity.
My code looks like the below excerpt:

function ost_notifications_entity_insert(EntityInterface $entity) {
  if ($entity->bundle() == 'deadline' || $entity->bundle() == 'message') {
    $new_entity = Drupal::entityTypeManager()->getStorage('node')->create([
      'type' => 'notification',
      'title' => $entity->label(),
      'field_content' => "referenced entity goes here"
    ]);
    $new_entity->save();
  }
}

One Answer

As pointed out by 4k4 in the comments, the most robust way is assign an entity object to the field like so:

$new_entity = Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'notification',
  'title' => $entity->label(),
  'field_content' => [
    'entity' => $entity,
  ],
]);

For posterity, you can also do it by setting the field column (target_id) directly, but this is only useful if you have a saved entity. The first example will work for both new and existing entities.

$new_entity = Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'notification',
  'title' => $entity->label(),
  'field_content' => [
    'target_id' => $entity->id(),
  ],
]);

Answered by Clive on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP