Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
    
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. – ThroneDigital Jan 28 at 22:46
up vote 5 down vote accepted

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).

share|improve this answer

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().
}
share|improve this answer

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);
share|improve this answer
    
To the rescue again. Thank you Adrian. – ThroneDigital Jan 28 at 23:04
    
@ThroneDigital and again a pleasure ;-) good luck in your projects – Adrian Cid Almaguer Jan 28 at 23:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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