Entity Clone | Drupal
Blog

Changing of Cloned Reference values while Cloning the Entity in Drupal 8

Recently, I came across a unique situation in Employee experience portal project that I was working on.

As in any enterprise, there were multiple departments in the company generating content for specific departments with varying levels of access as well as security.

To increase synergy as well as collaboration between departments, they had decided to allow authors to clone content from different departments. This was also to enable them to reutilize the design layout as well as content created by others.
 

We realized that this is not an option available within the Drupal ecosystem. We do have an  Entity Clone module available. But it was not solving our issue. The challenge was that we needed to clone an entity which was having existing references and these values should be changed in cloned entity based on certain conditions e.g. security groups assigned to a specific department.

These references were paragraphs, widgets as well as other custom entity types. If we clone the node using create duplicate function, it creates a duplicate node. But then, we have to attach all the field definition from the original node manually.

Challenge was in the entity clone process

  • Base field definitions are already available from the original content. Original content is referencing to existing entities.
  • While creating the duplicate, we have an ID (of an entity) only which is not saved yet and we are trying to attach that definition to newly created duplicated content.

Because of this, the content was not being saved with the new modified value.

We found a workaround by reviewing the entity clone module process further.

During the Entity clone process, it saves the duplicate node twice

  • At first, it creates an exact duplicate of the original content and saves it. On saving, ID gets created and then, attach all the reference fields.
  • And it saves the 2nd time with all the references of original content.

We have modified the references of cloned content while saving it the 2nd time. And we have implemented necessary business logic to modify the references.

The following snippet will help in understanding the solution.

 

To perform any alter operation, we have to implement hook_presave

$entity gives you clone entity during entity clone process.

$original_content gives you the values from parent content from where we are initiating the clone of the new content.

Now, you can implement your business logic inside hook_presave to modify the cloned node reference field value.

With the above code, we can change the clone reference values while cloning the entity. I would love to learn from others if there are any other ways to implement the same.