1

I have a Drupal 9 website with number of nodes that I use as templates, I clone them to create nodes with the same body text.

However, I want to make this process simpler by prepopulating the body field using a token that fetches the node ID from the URL parameter.

I checked the modules:

but as far as I can see, they don't support fetching a field from another node? Entity Prepopulate comes close I'm not sure how the URL parameter can be used by a token to pre-populate the body field.

1
  • Your question got me thinking and I have another question: Is there a way to have multiple "Default value" options in field settings, that seems to be the perfect fit for the templating case.
    – prkos
    Mar 24 at 19:56

2 Answers 2

5

If you add the template node ID as URL query parameter

/node/add/product?template=123

this code adds the body content of the template:

mymodule.module:

use Drupal\node\Entity\Node;

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(Node $node) {
  if ($node->getType() == 'product') {
    if (\Drupal::routeMatch()->getRouteName() == 'node.add') {
      $nid = \Drupal::request()->query->get('template');
      if ($template = Node::load($nid)) {
        # add access check for $template if necessary
        $node->body->value = $template->body->value;
        $node->body->format = $template->body->format;
      }
    }
  }
}

If the node add form is accessible to untrusted users, you need to add an access check to identify the node as a template. Without a hacker could use the node add form to read unpublished content simply by guessing node IDs.

3

The Field clone module can do this without custom code: Example usage: node/add/page?fieldclone=node:17:body

This module adds an option to clone fields to entity create/edit pages via get parameters. After installation you can use links like this (should be self-explanatory): node/add/page?fieldclone=node:17:field_common|node:23:field_source:field_target

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.