Nov 13, 2019 in Drupal 8, Snippets

Regular text fields

In drupal 8, when the field can have multiple values:

$values = $entity->field_myfield->getValue(); // or
$values = $entity->get('field_myfield')->getValue();
// Both will return an array go further with to get value per item
$first_item = $values[0]['value'];

When you know the field will just return one value, use the following:

$value = $entity->field_myfield->getString(); // or
$value = $entity->get('field_myfield')->getString();
// where $value is your direct result

Link fields

Link field provide some other functionality:

$link = $entity->field_myfield->getUrl()->toString(); // the url
$title = $entity->field_myfield->get('title')->getValue(); // the title
// this is when field_myfield has only 1 value

 Entity references

Another common used field type are entity references. 

$entities = $entity->field_items->referencedEntities(); // Returns an array of entity objects referenced in the field