You are here

public function EntityField::getValue in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/views/src/Plugin/views/field/EntityField.php \Drupal\views\Plugin\views\field\EntityField::getValue()

Gets the value that's supposed to be rendered.

This api exists so that other modules can easy set the values of the field without having the need to change the render method as well.

Parameters

\Drupal\views\ResultRow $values: An object containing all retrieved values.

string $field: Optional name of the field where the value is stored.

Overrides FieldPluginBase::getValue

File

core/modules/views/src/Plugin/views/field/EntityField.php, line 1080

Class

EntityField
A field that displays entity field data.

Namespace

Drupal\views\Plugin\views\field

Code

public function getValue(ResultRow $values, $field = NULL) {
  $entity = $this
    ->getEntity($values);

  // Ensure the object is not NULL before attempting to translate it.
  if ($entity === NULL) {
    return NULL;
  }

  // Retrieve the translated object.
  $translated_entity = $this
    ->getEntityFieldRenderer()
    ->getEntityTranslation($entity, $values);

  // Some bundles might not have a specific field, in which case the entity
  // (potentially a fake one) doesn't have it either.

  /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
  $field_item_list = isset($translated_entity->{$this->definition['field_name']}) ? $translated_entity->{$this->definition['field_name']} : NULL;
  if (!isset($field_item_list)) {

    // There isn't anything we can do without a valid field.
    return NULL;
  }
  $field_item_definition = $field_item_list
    ->getFieldDefinition();
  $values = [];
  foreach ($field_item_list as $field_item) {

    /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
    if ($field) {
      $values[] = $field_item->{$field};
    }
    elseif ($main_property_name = $field_item
      ->mainPropertyName()) {
      $values[] = $field_item->{$main_property_name};
    }
    else {
      $values[] = $field_item->value;
    }
  }
  if ($field_item_definition
    ->getFieldStorageDefinition()
    ->getCardinality() == 1) {
    return reset($values);
  }
  else {
    return $values;
  }
}