9

If I've created a node in an install hook, how can I immediately get a reference to the nid property? It doesn't appear to be set on the entity during save.

use Drupal\node\Entity\Node;

function my_frontpage_install() {
    $node = Node::create(array(
        'type' => 'page',
        'title' => t('Welcome'),
        'body' => array(array(
            'value' => 'Hi there'
        )),
    ));

    $node->save();

    $siteConfig = \Drupal::service('config.factory')->getEditable('system.site');
    $pageConfig = $siteConfig->get('page');
    $pageConfig['front'] = 'node/' . $node->getId(); // this returns null
    $siteConfig->set('page', $pageConfig);
    $siteConfig->save();
}

I've tried variations on the theme of getId, getNid(), get('nid'), getOriginalId(), but if I dump out the node object afer saving, the nid property is clearly not set.

4
  • 1
    Have you check $node->nid !
    – DRUPWAY
    Aug 24, 2015 at 6:48
  • 5
    It is $node->id().
    – user21641
    Aug 24, 2015 at 7:00
  • 1
    @IvanJaros that works, you should put it as an answer Aug 24, 2015 at 7:36
  • 4
    Note: the front/404/403 paths require a leading slash now (beta13+). Also, you can simplify your code a lot with $config->set('page.front', '/node/' . $node->id()).
    – Berdir
    Aug 24, 2015 at 18:42

1 Answer 1

11

The nice thing about Drupal 8, is that it's object oriented, with interfaces, abstract classes etc.

This means that all entities share a lot of methods. To get the id of a node, use the id method

$nid = $node->id();

This also works for users, taxonomy terms and any other entities you create yourself or get from contrib modules modules.

For Drupal 8 development, using an IDE becomes really powerfull as it can help you with what available methods, various instances of classes has.

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.