5

Essentially I want to take a node and duplicate it. Take a node ID and programmatically create a copy of the node.
I want to be able to edit the newly created node, and maintain the data on the old node.

  • I am aware of creating new nodes on the fly, and populating the values. example: timonweb.com/posts/… Just seeing if there was slicker way of going about it. – SoundCheese Jan 28 '16 at 22:46
6

On entities, you can use is_new to signify a new entity to save, but you still need to unset nid (iirc), vid, and tnid manually. This saves unsetting log.

$new = clone $node;
$new->is_new = true;
unset($new->nid);
unset($new->vid);
unset($new->tnid);
node_save($new);

Interestingly, the node_clone module incorrectly sets the properties to null, which is significant for databases that support NULL and DEFAULT separately (e.g. PostgreSQL).

5

You may be happy with the replicate module which provides an API to do just that for any entity.

As stated in its README file (You'll find more in it) :

Very basic usage example:

/**
 * Replicate Basic test function.
 *
 * In this example we will suppose that there is a node with nid = 1 we want
 * to replicate.
 */
function replicate_test_function() {
  // Load a newly created node as an entity.
  $entity = array_shift(entity_load('node', array(1)));

  // Duplicate the entity and save the replica.
  replicate_entity('node', $entity);

  // You can use replicate_clone_entity() instead, alter the replica afterward
  // and manually save the entity, but if you want to implement a generic
  // code like adding ' [Replicate]' to the end of every replicated node title,
  // use the API hook hook_replicate_entity_ENTITY_TYPE().
}
2

You can load your node with node_load() and unset the nid and vid and then save the new node with node_save()

  $nid = 4;
  $node = node_load($nid);
  $new_node = $node;
  unset($new_node->nid);
  unset($new_node->vid);
  node_save($new_node);
  • @ThroneDigital and again a pleasure ;-) good luck in your projects – Adrian Cid Almaguer Jan 28 '16 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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