node_add_copy-1.0.0-beta4/node_add_copy.module
node_add_copy.module
<?php
/**
* @file
* Node Add Copy module.
*/
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
/**
* Implements hook_help().
*/
function node_add_copy_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.node_add_copy':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Creates a form of the same node type with info preloaded with another node values') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_form_alter().
*/
function node_add_copy_form_alter(&$form, $form_state, $form_id) {
if (\Drupal::routeMatch()->getRouteName() === 'node.add' && empty($form_state->getUserInput())) {
$nid = \Drupal::request()->query->get('copy');
if (!$nid) {
return;
}
$isWorkflowEdit = str_contains($form_id, $nid);
$isEdit = str_contains($form_id, 'edit');
if ($nid && !$isEdit && !$isWorkflowEdit) {
// Load the edit form of the node to be copied.
$node = Node::load($nid);
$entity_form_builder = \Drupal::service('entity.form_builder');
$editForm = $entity_form_builder->getForm($node, 'edit');
foreach ($form as $key => $value) {
if (strpos($key, 'field_') !== FALSE) {
$field_type = $node->getFieldDefinition($key)?->getType();
if ($field_type === 'entity_reference_revisions') {
continue;
}
$form[$key] = $editForm[$key];
}
}
}
}
}
/**
* Implements hook_entity_operation().
*/
function node_add_copy_entity_operation(EntityInterface $entity) {
$operations = [];
$node_content_type = $entity->bundle();
$nid = $entity->id();
$copyUrl = Url::fromUri('internal:/node/add/' . $node_content_type . '?copy=' . $nid);
if ($entity->getEntityTypeId() === 'node' && \Drupal::currentUser()->hasPermission('allow to copy nodes')) {
$operations['copy'] = [
'title' => t('Copy'),
'weight' => 100,
'url' => $copyUrl,
];
}
return $operations;
}
/**
* Implements hook_menu_local_tasks_alter().
*/
function node_add_copy_menu_local_tasks_alter(&$data, $route_name) {
if ($route_name == 'entity.node.edit_form' || $route_name == 'entity.node.canonical') {
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->id();
if ($node && \Drupal::currentUser()->hasPermission('allow to copy nodes')) {
$node_content_type = $node->bundle();
$copy_link = Url::fromUri('internal:/node/add/' . $node_content_type . '?copy=' . $nid);
$data['tabs'][0]['entity.node.copy'] = [
'#theme' => 'menu_local_task',
'#link' => [
'title' => t('Copy'),
'url' => $copy_link,
],
'#weight' => 100,
];
}
}
}
