Work with fields in Drupal

The right way to get fields in Drupal

Drupal has a few ways how to get a value from an entity field.

And sometimes pro developers do it with wrong way. So, let's have a look for right way how to get field values.

<?php

use Drupal\node\Entity\Node;

$node = Node::load(123);

$field = $node->get('field_name');

I guess, a lot of us use this way:

<?php

$value = $field->getValue();

dump($value);

It returns an array with values and you have to do some extra manipulation with it like some loop and do some staff.

Well, the best way to get a single value from the field is:

<?php

$value = $field->getString();

dump($value);

This is a good approach to get a value for field type "Text" and it will return just a value of the field like a string.

Also, if you try use it for field type like "Reference" (node, taxonomy and etc.) it will return a string with IDs of the referenced entities like "1, 2, 3". But I don't recommend use it in case of field type "Reference".

Second case is a multiple fields. For some reasons we have to get the first value of multiple field.

<?php

$value = $field->first()->getString();

dump($value);

And if you have to get second or third value of the value list you can use this one.

$value = $field->get(2)->getString();

dump($value);

I believe, you will work with entities in you code and there is a way how get referenced entities.

<?php

$value = $field->referencedEntities();

dump($value);

The code above returns an array with entities.

By the way, there is a helpful method to check if the value exist or not in the field:

dump($field->isEmpty());

Basically, this is it. I hope you will use these approaches in you code.