custom_nodeformactions-8.x-1.x-dev/custom_nodeformactions.module
custom_nodeformactions.module
<?php
/**
* @file
*/
use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
/**
* Implements hook_form_alter().
*/
function custom_nodeformactions_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form['#node']) {
$config = \Drupal::config('custom_nodeformactions.settings');
$addmorebuttonlabel = $config->get('custom_nodeformactions.addmorebuttonlabel');
$addcopybuttonlabel = $config->get('custom_nodeformactions.addcopybuttonlabel');
$node_typeslist = $config->get('custom_nodeformactions.node_types');
if (empty($addmorebuttonlabel)) {
$addmorebuttonlabel = "Add More";
}
if (empty($addcopybuttonlabel)) {
$addcopybuttonlabel = "Copy Node";
}
// Adding custom validation for the welcome page type field.
if (preg_match('/node/', $form_id)) {
// Do some stuff.
$node_type = $form['#process'][1][0]->getTargetBundle();
if ($node_typeslist[$node_type] !== 0) {
// If ($form_id == 'node_'.$node_type.'_edit_form'){.
$form['actions']['saveandanother'] = [
'#type' => 'submit',
'#value' => t($addmorebuttonlabel),
'#validate' => ['node_form_validate'],
// Use default and an additional submit handler.
'#submit' => ['node_form_submit', 'custom_nodeformactions_node_form_submit_saveandanother'],
];
// }
if ($form_id == 'node_' . $node_type . '_edit_form') {
$form['actions']['saveandandcopy'] = [
'#type' => 'submit',
'#value' => t($addcopybuttonlabel),
'#validate' => ['node_form_validate'],
// Use default and an additional submit handler.
'#submit' => ['node_form_submit', 'custom_nodeformactions_node_form_submit_saveandandcopy'],
];
}
}
}
}
}
/**
*
*/
function custom_nodeformactions_node_form_submit_saveandanother($form, FormStateInterface $form_state) {
$node_type = $form['#process'][1][0]->getTargetBundle();
$url = Url::fromRoute('node.add', ['node_type' => $node_type]);
return $form_state->setRedirectUrl($url);
}
/**
*
*/
function custom_nodeformactions_node_form_submit_saveandandcopy($form, FormStateInterface $form_state) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof NodeInterface) {
// You can get nid and anything else you need from the node object.
$nid = $node->id();
$node = Node::load($nid);
$nodeDuplicate = $node->createDuplicate();
// Edit title or something so you can find cloned.
$nodeDuplicate->save();
\Drupal::messenger()->addStatus(t("Node has been created. <a href='/node/@id/edit' target='_blank'>Edit now</a>", [
'@id' => $nodeDuplicate->id(),
'@title' => $nodeDuplicate->getTitle(),
]
));
}
}
