0

I am trying to get the node ID that I have just created. If I do the following code from this answer.

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

I implemented hook_ENTITY_TYPE_view() (just to test the code), but it gets the ID for all the nodes, while I want the ID of the node that has been created to modify a field value for that node. Is this possible?

Should I use the code I shown in a hook_form_alter() implementation or maybe inside a form submission handler?

4
  • 1
    You have to use some kind of event, like hook_node_insert() to set a session value or a custom form submit handler to redirect to a page with the node id as parameter, which you then can get from the route match like in your code example.
    – 4uk4
    Commented Dec 24, 2019 at 12:31
  • 1
    Welcome to Drupal Answers! :-) Where have you placed that snippet exactly? And what are you trying to achieve exactly? What do you want to do with this node ID then? Please edit your question for clarification. Many thanks
    – leymannx
    Commented Dec 24, 2019 at 12:35
  • @leymannx Thanks, just edited the question
    – Robgher
    Commented Dec 24, 2019 at 12:41
  • @Robgher, it depends on which field you want to modify and how. If you want to modify it when it's created no matter what, you should use hook_node_insert, as Leymannx suggests. If you only want to modify it when created through the form, a form alter may do the trick (keep into account that you'll have to manage when the node is edited, because the form is the same). I think it's better if you provide more info: what kind of field, what modification you want to apply, when (only on creation? that field is editable after is created), etc.
    – sanzante
    Commented Dec 24, 2019 at 12:50

1 Answer 1

1

If you need to alter the value of a node field right after the node has been created, you don't need that code. You just need to implement hook_ENTITY_TYPE_presave() and verify the node is new.

function mymodule_node_presave(EntityInterface $entity) {
  if ($entity->isNew()) {
    // The node has been created.
    // Access the node field using $entity.
  }
}

If then, for any reason, you need the node ID, you can access it with $entity->id().

I used hook_ENTITY_TYPE_presave(), assuming the node needs to be saved with the new field value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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