Score:0

How to programmatically append fields to node object when cloning with createDuplicate()

in flag

I am trying to setup a custom module which copies values from a node whose content type is A to a node whose content type is B. For the most part, the content types have the same fields, but B has a few additional fields.

A

  • Title (title)
  • Body (body)
  • Date (field_date_agenda)

B

  • Title (title)
  • Body (body)
  • Date (field_date_agenda)
  • Number of items (field_int_how_many)
  • Reference to A (field_noderef_nta)

With $cloned_node = $node->createDuplicate() I am able to copy all the fields from A, as well as being able to change the content type to B.
Since A doesn't have the extra fields attached to it, createDuplicate() won't copy them.

Now, what I would like to do is to programmatically add the other fields (which I will populate with some custom values) to $cloned_node. When these actions are completed, $cloned_node->save() will be used to finalize the cloning process.

Simply adding the value via $cloned_node->set("field_int_how_many", $value) doesn't seem to do the trick: A PHP error is thrown.

InvalidArgumentException: Field field_int_how_many is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 587 of /home/username/domains/domainname.com/public_html/devsite/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Does anyone have an idea how to add those extra fields to the cloned node?

Score:3
us flag

If the content type of $node is A, the content type of the node returned by $node->createDuplicate() is still A. That's why $node->createDuplicate()->set("field_int_how_many", $value) returns an error saying that field_int_how_many is an unknown field: Content type A doesn't have that field.

What you are trying to obtain isn't a clone of $node, but to copy the values from a node whose content type is A to a node whose content type is B.
For that, you need to create a new node, passing the values of the existing node field as values for the new node fields.

$new_node = Node::create(
  'type' => 'B',
  'title' => $node->title,
  'body' => $node->body,
  'field_date_agenda' => $node->field_data_agenda,
  'field_int_how_many' => /* the value to assign to the field */
);
in flag
Thank you very much for your quick and clear answer. I will give it a go.
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.