Skip to content

Instantly share code, notes, and snippets.

@kunicmarko20
Created May 4, 2017 16:27
Show Gist options
  • Save kunicmarko20/d1fcb622bda26f9707f6ff96297f2090 to your computer and use it in GitHub Desktop.
Save kunicmarko20/d1fcb622bda26f9707f6ff96297f2090 to your computer and use it in GitHub Desktop.
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');
}
}
@piridium
Copy link

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