Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I want to get hold of the nid of the newly created node whenever a new node or comment is created by a user by pressing "Save" (and only when the user press "Save" - not when the node is created or saved by other means).

I've tried to create a custom submit handler to intercept the save by means of a custom submit handler:

$form['#submit'][] = 'mymodule_node_submit';

This handler intercepts the press on the "Save" button, but it is invoked too early. The nid of the node it is not yet available inside the submit handler.

What is the correct way of getting the nid whenever a new node is created by an interactive user?

I know there is a similar question here: Get node id of saved node - but the accepted solution (use hook_node_update()) is not correct. hook_node_update() will also intercept calls when nodes are created programatically (for instance by the Feeds module), when there is no real user involved.

share|improve this question
    
Don't have the time to code it, but drupal_static is a convent way to create a global variable. Using $form['#submit'] set a static variable to be TRUE and then inside of hook_node_update() check that static to see if the node update came from a form submit. Good luck :) –  mikeytown2 Jun 26 at 18:34

2 Answers 2

up vote 2 down vote accepted

If you read through node_form() you will see that the Submit button has its own submit handler:

$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);

so you need to add your own submit handler to this

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] = 'MYMODULE_node_form_submit';
}

Then inside that $form_state['nid'] or $form_state['node'] should have what you need.

share|improve this answer

You can use hook_node_submit($node, $form, &$form_state) and check $node->op == 'Save'.

This hook is invoked when a node form is submitted with either the "Save" or 
"Preview" button, after form values have been copied to the form state's node
object, but before the node is saved or previewed.

Update: You can use hook_node_insert() itself, if you check the $node object it will contain $node->op only when creating through UI, it won't be present when creating through code.

share|improve this answer

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.