2

I want programatically create a new node of type B (status message), immediately after a node of type A (e.g. gallery post) is added (or updated).

Looking at this recipe, I see that I will have to add hook_node_insert inside my module and call node_save to save the new node. But on the comments to the hook_node_insert docs ndvo claims I can't call node_save in the middle of another node_save operation. So what is the best approach to use?

1

There is no hook which is called AFTER the node is saved. No POST-SAVE hook.

But calling node_save within hook_insert actually works. The warnings were false:

So I ended up with something like:

function MYMODULE_node_insert($node) {
  if ( $node->type == 'blog_post') {
    MYMODULE_insert_statuspost($node);
  }
}

function MYMODULE_insert_statuspost($n) {
  global $user;
  $node = new stdClass();
  $node->title = "New blog post $n->title";
  $node->type = "statuspost";
  node_object_prepare($node); /* Sets some defaults. 
     Invokes hook_prepare() and hook_node_prepare(). */
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->body[$node->language][0]['value'] = 
    "New blog post: " . l($n->title, "node/$n->nid") . " has been posted");
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 2; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  drupal_set_message( "Status post with nid " . $node->nid . " saved!\n");
}

Here is a full commented code to programatically create a node.

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.