5

I am modifying the node content on hook_form_alter() as follows.

  $node = \Drupal\node\Entity\Node::load($nid);
  if ($node) {
    $node->field_p_frontip = $availableip[0];
    $node->save();
  }

I need to clone the node and save it in the hook_form_alter() submission. How could I do this?

UPDATE


In D6 the node was cloned using the function clone_node_save which uses the node id to clone as clone_node_save($nid,false);, what is the corresponding function in D8 ??

4
  • 2
    Question has been updated for clarity, but I can't add an answer to a question on hold. In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned_node = $node->createDuplicate(). Calling $cloned_node->save() will save a new node with a different ID.
    – jhedstrom
    Oct 31, 2016 at 22:13
  • Thanks @jhedstrom :) . Here $node is the node id right ?
    – KTM
    Nov 1, 2016 at 8:05
  • Thanks man , it worked :)) . I dont know why its put on hold . CRAP
    – KTM
    Nov 1, 2016 at 8:33
  • I've added this comment as a proper answer now that this is not on hold.
    – jhedstrom
    Nov 4, 2016 at 18:56

2 Answers 2

18

In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned_node = $node->createDuplicate(). Calling $cloned_node->save() will save a new node with a different ID.

2
  • Hi @jhedstrom, is there any way to get the nid of recently cloned node ? Dec 21, 2021 at 12:00
  • 1
    @innovativekundan indeed. After calling $cloned_node->save(), you would simply call $cloned_node->id() to get the new node ID.
    – jhedstrom
    Dec 22, 2021 at 18:50
3
<!-- The below solution works for me. (Drupal - 9.4.1)
1. It perfectly clones all paragraphs.
2. It does not clone files.
3. It does not clone terms. -->

$nid = 17; // Example node id
$node = Node::load($nid);

if (is_object($node)) {
  $clonednode = $node->createDuplicate();
  // Loop over entity fields and duplicate nested paragraphs.
  foreach ($clonednode->getFields() as $field) {
    if ($field->getFieldDefinition()->getType() == 'entity_reference_revisions') {
      if ($field->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type') == "paragraph") {
        $paragraphs = [];
        foreach ($field as $item) {
          $paragraphs[] = $item->entity->createDuplicate();
        }
        $fieldname = $field->getFieldDefinition()->getName();
        $clonednode->$fieldname =  $paragraphs;
      }
    }
  }

  $clonednode->changed->value = time();

  // Append cloned in the title.
  $clonednode->set('title', 'Cloned - ' . $node->getTitle());

  // Cloned node should be unpublished.
  $clonednode->set('status', 0);

  $clonednode->save();
}

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.