Get field value of a Node / Entity

Submitted by editor on Wed, 12/02/2015 - 14:06
Question

How to get the field value of a node / Entity ?

Methode 1 : Example:

$value = $node->get($field)->value;

Methode 2 Example:

$field = 'field_thefieldname';
$index = 0;  
$a = $node->toArray();
if (isset($a[$field][$index]['value'])) {
    $value = $a[$field][$index]['value'];
}

Example 3 : Get / Render image (Show current user's picture)

$userCurrent = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($userCurrent->id());
$renderd_image = $user->get('user_picture')->first()->view();

Or for multiple values
foreach ($node->get('field_images')->getValue() as $key => $image) {
    $image = $node->field_images[$key]->view($settings);
}
//Example Of $settings
$settings = ['settings' => ['image_style' => 'thumbnail']];

 

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.