3
use Drupal\node\Entity\Node;

function abc($v) {
  $node = \Drupal\node\Entity\Node::load($v);
  print_r($node);
}

The array structure of $node is as given below

Drupal\node\Entity\Node Object (
[in_preview] => 

[values:protected] => Array
    (


   [nid] => Array
        (
            [x-default] => 166
        )

    [vid] => Array
        (
            [x-default] => 180
        )

    [type] => Array
        (
            [x-default] => sections
        )

    [uuid] => Array
        (
            [x-default] => 7759efc9-cfff-4d58-b392-8d60b9903323
        )

    [langcode] => Array
        (
            [x-default] => en
        )
1
  • 1
    A node is an object, not an array. Learn how to use OOP
    – Hudri
    Nov 15, 2018 at 8:47

4 Answers 4

7

As mentioned in the comment of @Hudri Node is an object not an array.

In Drupal 8 there are two ways to get the value of a field.

  1. $node->field_name->value
  2. $node->get("field_name")->getValue()

In your case you can get the nid and title like below:

$nid = $node->id();
$title = $node->label();

or

$title = $node->getTitle();

To read about objected-oriented programming conventions In Drupal 8 check this blog article: Drupal 8 API: objected-oriented programming conventions.

1
  • 4
    it's not ideal to use magic methods to get the title. There are two better methods, Node::getTitle() and Entity::label(), that should take precedence
    – Clive
    Nov 15, 2018 at 10:36
2

you can get the node id like this :

$nid = $node->id();

and for the title :

$title = $node->label();
0

You can get the node id and node title values by using Node::load function.

use Drupal\node\Entity\Node;

function abc($v) {

$node = Node::load($v);

$strNodeId =  $node->nid->value;

$strNodeTitle = $node->title->value;

echo 'Id: '.$strNodeId;

echo 'Title: '.$strNodeTitle;
exit();

}

0

For Drupal 8 media items (e.g. Remote Video), use getName()

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.