Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drupal 8 Clone Nodes
name: Clone Nodes
description: 'Creates clone of node.'
type: module
core: 8.x
package: Custom
<?php
function clone_nodes_pages_entity_operation(\Drupal\Core\Entity\EntityInterface $entity)
{
$operations = [];
if ($entity instanceof \Drupal\node\Entity\Node) {
$operations['clone'] = [
'title' => t('Clone'),
'url' => \Drupal\Core\Url::fromRoute('clone_nodes',['id' => $entity->id()]),
'weight' => 150,
];
}
return $operations;
}
clone_nodes:
path: '/cnodes/node/{id}/clone'
defaults:
_controller: '\Drupal\clone_nodes\Controller\CloneController::clone'
requirements:
_permission: 'access content'
<?php
namespace Drupal\clone_nodes\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\node\Entity\Node;
class CloneController extends ControllerBase
{
public function clone($id)
{
$node = Node::load($id);
if ($node === null) {
drupal_set_message(t('Node with id @id does not exist.', ['@id' => $id]), 'error');
} else {
$nodeDuplicate = $node->createDuplicate();
foreach ($nodeDuplicate->field_paragraphs as $field) {
$field->entity = $field->entity->createDuplicate();
}
//edit title or something so you can find cloned
$nodeDuplicate->save();
drupal_set_message(
t("Node has been created. <a href='/node/@id/edit' target='_blank'>Edit now</a>", [
'@id' => $nodeDuplicate->id(),
'@title' => $nodeDuplicate->getTitle()]
), 'status');
}
return new RedirectResponse('/admin/content');
}
}
@ClemensSahs

This comment has been minimized.

ClemensSahs commented Jul 5, 2018

It seems like the module "Entitry Clone" is a better alternative

https://www.drupal.org/project/entity_clone

@piridium

This comment has been minimized.

piridium commented Nov 28, 2018

Hello Marco
The EntityClone module proposed by Clemens doesn't seem to clone the referenced paragraphs.
So I created a module with your code and basically it works. The problem is that if I clone multiple times, the clones I already created will be cloned again. I can neither find the cause nor the solution for this problem. Can you help me?
Best regards Patrick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment