I’m trying to setup a custom module which clones the content from NODETYPE_A to NODETYPE_B. For most part, both nodetypes use the same fields, but NODETYPE_B has a few additional ones. For example:
NODETYPE_A:
- Title (title)
- Body (body)
- Date (field_date_agenda)
NODETYPE_B:
- Title (title)
- Body (body)
- Date (field_date_agenda)
- Number of items (field_int_how_many)
- Reference to NodeTypeA (field_noderef_nta)
Now, with the build in functionality “$cloned_node = $node->createDuplicate()” I am able to clone all fields from NODETYPE_A to NODETYPE_B, as well as the ability to change the nodetype from NODETYPE_A to NODETYPE_B.
Since NODETYPE_A doesn’t have the extra fields (field_int_how_many and, field_noderef_nta) attached to it to begin with, createDuplicate() obviously won’t copy them to NODETYPE_B.
Now, what I would like to do, is programmatically adding the other fields (which I will be populating with some custom values) to $cloned_node. When these actions are completed, $cloned_node->save(); will be called to finalize the cloning process.
Simply adding the value via $cloned_node->set("field_int_how_many", $value) doesn’t seem to to the trick; an php-error gets triggered, with the following watchdog entry:
InvalidArgumentException: Field field_int_how_many is unknown. in DrupalCoreEntityContentEntityBase->getTranslatedField() (rule 587 of /home/username/domains/domainname.com/public_html/devsite/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).
Does anyone has an idea how to add those “extra/custom” fields to the cloned object?