You are here

public function Loader::loadField in Bamboo Twig 8.5

Same name and namespace in other branches
  1. 8.2 bamboo_twig_loader/src/TwigExtension/Loader.php \Drupal\bamboo_twig_loader\TwigExtension\Loader::loadField()
  2. 8.3 bamboo_twig_loader/src/TwigExtension/Loader.php \Drupal\bamboo_twig_loader\TwigExtension\Loader::loadField()
  3. 8.4 bamboo_twig_loader/src/TwigExtension/Loader.php \Drupal\bamboo_twig_loader\TwigExtension\Loader::loadField()

Returns the field object for a single entity field.

Parameters

string $field_name: The field name.

string $entity_type: The entity type.

mixed $id: (optional) The ID of the entity to render.

string $langcode: (optional) Language code to load translation.

Return value

null|Drupal\Core\Field\FieldItemListInterface A field object for the entity or NULL if the value does not exist.

File

bamboo_twig_loader/src/TwigExtension/Loader.php, line 81

Class

Loader
Provides some loaders as Twig Extensions.

Namespace

Drupal\bamboo_twig_loader\TwigExtension

Code

public function loadField($field_name, $entity_type, $id = NULL, $langcode = NULL) {

  // Load the entity view using the current content language.
  if (!$langcode) {
    $langcode = $this
      ->getLanguageManager()
      ->getCurrentLanguage()
      ->getId();
  }
  $entity = $this
    ->loadEntity($entity_type, $id, $langcode);
  if (!$entity) {
    return NULL;
  }

  // Ensure the entity has the requested field.
  if (!$entity
    ->hasField($field_name)) {
    return NULL;
  }

  // Do not continue if the field is empty.
  if ($entity
    ->get($field_name)
    ->isEmpty()) {
    return NULL;
  }
  if (isset($entity->{$field_name})) {
    return $entity->{$field_name};
  }
  return NULL;
}