0

Hi team i have some isssues.

I'm creating a node and i would like to set a content reference by name not by id, i'm doing this but this is not working: 'field_content_type_items' is referenced to another content type

$node = \Drupal\node\Entity\Node::create([
    'type' => 'items',
    'status' => $status,
    'title' => $title,
    'field_content_type_items' =>  "CUN",
]);

Also i tried with this example 'field_content_type_items' => [['target_id' => 12]], but i dont know the id for CUN so i cant use target_id also i've tried:

$node->set('field_content_type_items', 'CUN');

could you please help me?

How can i set a content name when i create a node?

Regards Mario

2

Entity reference fields expect an entity ID, so unless you want to extend the field type (which could get unnecessarily messy), you'll need to get the ID of the target content.

One method to do this is EntityStorageBase::loadByProperties(), e.g.

$target_nodes = \Drupal::entityTypeManager()->getStorage('node')
  ->loadByProperties(['title' => 'CUN', 'type' => 'foo']);

if (count($target_nodes)) {
  // For the sake of example assume the first node is the right one.
  $target_id = reset($target_nodes)->id();

  // ...
}

Bear in mind that node titles aren't unique, so you might need to add some extra filtering logic to get the exact node you need.

1
  • yes that's what i thought, to get id node using some query and then using in target_id, thanks
    – mxr10
    Oct 20 '21 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.