10 Jul.2017

Drupal 8 & 9: Make a redirect to "Edit" mode after replication any node

Redirect to edit mode after cloning the node.

While Replicating Nodes using Replicate and Replicate UI Module, I found that the module will publish a node immediately (shows  "view" mode) after replication. What I would like is when it is replicated the replicated node opens in edit mode so that a content manager can make the necessary changes before publishing it. Otherwise, it creates too many steps for them to go through.

For our project, I've implemented this with a custom event subscriber, which unpublishes any replicated node and makes the redirect to edit mode.

UPD: Actually, this functionality was implemented in the Replicate Actions module.

Have a fun.

File
alex_tweaks.services.yml
services:
  alex_tweaks.replicate_node_edit:
    class: Drupal\alex_tweaks\EventSubscriber\ReplicateSetNodeEdit
    tags:
      - { name: event_subscriber }
File
src/EventSubscriber/ReplicateSetNodeEdit.php
<?php
 
namespace Drupal\alex_tweaks\EventSubscriber;
 
use Drupal\node\Entity\Node;
use Drupal\replicate\Events\ReplicateAlterEvent;
use Drupal\replicate\Events\AfterSaveEvent;
use Drupal\replicate\Events\ReplicatorEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
 
/**
 * Makes replicated nodes unpublished and redirect to edit mode.
 */
class ReplicateSetNodeEdit implements EventSubscriberInterface {
 
  /**
   * Sets the status of a replicated node to unpublished.
   *
   * @param \Drupal\replicate\Events\ReplicateAlterEvent $event
   *  The event fired by the replicator.
   */
  public function setUnpublished(ReplicateAlterEvent $event) {
    $cloned_entity = $event->getEntity();
 
    if (!$cloned_entity instanceof Node) {
      return;
    }
 
    $cloned_entity->set('status', Node::NOT_PUBLISHED);
  }
 
  /**
   * Make a redirect to "edit" mode.
   *
   * @param \Drupal\replicate\Events\AfterSaveEvent $event
   *  The event fired by the replicator.
   */
  public function makeRedirect(AfterSaveEvent $event) {
    $cloned_entity = $event->getEntity();
 
    if (!$cloned_entity instanceof Node) {
      return;
    }
 
    $response = new RedirectResponse('/node/' . $cloned_entity->id() . '/edit');
    $response->send();
 
  }
 
  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[ReplicatorEvents::REPLICATE_ALTER][] = 'setUnpublished';
    $events[ReplicatorEvents::AFTER_SAVE][] = 'makeRedirect';
 
    return $events;
  }
 
}

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.

Versions