Discover how to access field values from entity or node objects in Drupal 8 and 9, covering regular text, link, entity reference, image, date, boolean, and list fields.
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
Image fields
Image fields are also a commonly used field type in Drupal. To access the image field data, follow the examples below:
$image_uri = $entity->field_myimage->entity->getFileUri(); // Get the image URI
$image_url = file_create_url($image_uri); // Get the image URL
$alt_text = $entity->field_myimage->alt; // Get the alt text
$title_text = $entity->field_myimage->title; // Get the title text
Date fields
Date fields are often used to store date and time information. Here's how to retrieve date field values:
$date_storage_format = $entity->field_mydate->value; // Get the date in the storage format (e.g., "2023-04-14T15:30:00")
$date_timestamp = $entity->field_mydate->date->getTimestamp(); // Get the date as a Unix timestamp
$formatted_date = $entity->field_mydate->date->format('F j, Y'); // Get the date in a custom format
Boolean fields
Boolean fields are useful for storing true/false values. To access the value of a boolean field, use the following code:
$boolean_value = $entity->field_myboolean->value; // Get the boolean value (1 or 0)
$is_true = (bool) $boolean_value; // Convert the value to a boolean (true or false)
List (text) fields
List fields store a set of predefined options. To access the value and label of a list (text) field, use the following:
$selected_key = $entity->field_mylist->value; // Get the selected option's key
$selected_label = $entity->field_mylist->getSetting('allowed_values')[$selected_key]; // Get the selected option's label
Remember that these examples assume the fields contain only one value. If the fields are configured to store multiple values, you may need to iterate over the results or access specific array indexes as appropriate.