Chris Muench
Chris Muench

Reputation: 18318

How can I get the node id within the submit handler defined in hook form alter

Is there a different hook I can use to get the node_id of a NEW node that is submitted?

function dc_project_management_form_bug_request_node_form_alter(&$form, &$form_state, $form_id)
{
    $form['#submit'][] = 'dc_project_management_process_bug_request_milestone_submit';
}

function dc_project_management_process_bug_request_milestone_submit($form, &$form_state)
{
    //NULL when submitting new node
    $form_state['values']['nid'];
}

Upvotes: 2

Views: 5388

Answers (2)

Nick Daugherty
Nick Daugherty

Reputation: 2822

The only way to retrieve the node id is to use hook_node_insert. However, if you wish to make modifications to the node object from inside this hook, you must notify Drupal of the alteration, otherwise the changes won't make it into the database transaction and will be lost.

After you're done modifying the node, call field_attach_updates('node', $node). For example:

function mymodule_node_insert($node){
    $node->field_myfield['und'][0]['value'] = 'a new value';

    field_attach_update('node', $node);
}

See http://timonweb.com/how-save-yourself-some-hair-when-manipulating-node-fields for more information.

Upvotes: 2

Clive
Clive

Reputation: 36956

The node hasn't actually been saved at that point, you need to implement hook_node_insert:

function dc_project_management_node_insert($node) {
  $nid = $node->nid;
}

Upvotes: 5

Related Questions