Create a gist now

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.

Show comment
Hide comment
@ClemensSahs

ClemensSahs Jul 5, 2018

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

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

ClemensSahs commented Jul 5, 2018

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

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

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