2

When creating a new node, I need to populate/fill a custom field with a value of the current node's id. What hook should I use to fill my custom field with newly created nid ($node->nid)?

I tried to use hook_node_presave but it was NULL, currently I am thinking to use hook_node_insert but as documentation says :

after the node is inserted into the node table in the database,

Does that mean if I assign the new value to my custom field it will be/not be saved to database?

  • 1
    Editing or Changing Drupal nid's are not allowed since they are unique and generated by Drupal to keep track of content. What is the reason you are looking for to change the nid's ? – Anil Sagar Sep 14 '12 at 2:22
  • i am not trying to change the nid i am just trying to copy its value after creating a new node to my costum field – Mouad Sep 14 '12 at 11:33
  • It might help if you explain a bit more about what you are trying to achieve, since although we can probably tell you how to do what you're asking, there is most likely a better way to get there. – Chris Cohen Sep 14 '12 at 11:53
  • Are you trying to reference one node with another ? Or do you want to display the node id in custom field which will be visible when you edit node ? Or something else ? – Anil Sagar Sep 14 '12 at 11:55
  • what is your drupal version ? – Yusef Mohamadi Sep 14 '12 at 11:55
1

I guess I found a solution for this problem:

function mymodule_node_insert($node) {
  $node->field_custom_field['und'][0]['nid'] = $node->nid;
  node_save($node)
}

I saved the changes to database with node_save()

0

if you are drupal 6 use hook_nodeapi

function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      $nid=$node->nid;
       // $nid  is exist and you can put it in your field
       //something like this 
       $node->field_yourfieldname['und'][0]['value'] = $node->nid;
       // this parameters related your field name and field type I suggest you in here ou print $node first and according it accompolish
      break;
   }
  }

and if you are using drupal 7 use hook_node_insert

function hook_node_insert($node) {
    $nid = $node->nid;
   // $nid  is exist and you can put it in your field
              //something like this 
       $node->field_yourfieldname['und'][0]['value'] = $node->nid;
       // this parameters related your field name and field type I suggest you in here ou print $node first and according it accompolish
   }
  • if i make any changes to the node with hook_node_insert, are the changes that are made to custom field saved to the database or i need to invoke some function to save it to database? – Mouad Sep 15 '12 at 15:52
  • no need any additional function. – Yusef Mohamadi Sep 16 '12 at 5:09

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.