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.


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


  • 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?

1 Answer 1


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 */
  • Thank you very much for your quick and clear answer. I will give it a go.
    – Piet
    Commented Feb 19, 2022 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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