3

I want to create duplicate nodes of a content type programmatically.

Is there any way to do this?

Note: I don't want to use any module to do this.

3

You can read the values from the original node in an array and create a new node with the data:

$storage = \Drupal::entityTypeManager()->getStorage('node');

$node = $storage->load($nid);

$original_values = $node->toArray();

// assign content type as string, the array causes an error when creating a new node
$original_values['type'] = $node->bundle();

// change title
$original_values['title'] = $node->label() . ' (cloned)';

// remove nid and uuid, the cloned node is assigned new ones when saved
unset($original_values['nid']);
unset($original_values['uuid']);

// remove revision data, the latest revision becomes the only one in the new node
unset($original_values['vid']);
unset($original_values['revision_translation_affected']);
unset($original_values['revision_uid']);
unset($original_values['revision_log']);
unset($original_values['revision_timestamp']);

$node_cloned = $storage->create($original_values);
$node_cloned->save();
2

Yes, we can duplicate a node in Drupal 8 as well. Check example below:

NOTE: I've not tested this code thoroughly, and not sure if this will affect on node being cloned as well.

use Drupal\node\Entity\Node;

$node_clone = Node::load($id);
$node_clone->nid = NULL;
$node_clone->vid = NULL;
$node_clone->tnid = NULL;
$node_clone->log = NULL;
// Also handle modules that attach a UUID to the node.
$node_clone->uuid = \Drupal::service('uuid')->generate();
$node_clone->vuuid = NULL;

// Anyonmymous users don't have a name.
$node_clone->name = 'Anonymous';
$node_clone->uid = 0;

$node_clone->created = time();
$node_clone->path = NULL;
$node_clone->files = array();
$node_clone->setTitle('Clone Node');
$node_clone->save();
  • It's not working as it reflect changes on the old node only, no new node is cloned from it. – Ashish Deynap Dec 26 '16 at 14:18
  • Are you getting any error while running above code? – Yogesh Dec 27 '16 at 4:39
  • My original node has been changed through this code. It's not working – Ashish Deynap Dec 27 '16 at 5:20
  • Ok, did you also tried the solution provided by @4k4. I'll try out the above example and see what is causing this issue. – Yogesh Dec 27 '16 at 5:34

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.