Score:0

How do I programmatically set a content reference by name for a node?

id flag

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

Score:2
cn flag

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.

mxr10 avatar
id flag
yes that's what i thought, to get id node using some query and then using in target_id, thanks
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.