You are here

public function FieldLimiter::viewElements in Field Limiter 8

File

src/Plugin/Field/FieldFormatter/FieldLimiter.php, line 101

Class

FieldLimiter
Plugin implementation of the 'field_limiter' formatter.

Namespace

Drupal\field_limiter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $field_values = $items
    ->getValue();
  $offset = $this
    ->getSetting('offset');

  // To show all elements, expressed by the setting '0', array_slice needs
  // NULL as 3rd argument.
  $limit = $this
    ->getSetting('limit') == 0 ? NULL : $this
    ->getSetting('limit');

  // Let array_slice limit the field values to the ones we want to keep.
  $limited_values = array_slice($field_values, $offset, $limit);
  $items
    ->setValue($limited_values);

  // Generate the output of the field.
  $field_output = $this
    ->getFieldOutput($items, $langcode);

  // Take the element children from the field output and return them.
  $children = Element::children($field_output);
  return array_intersect_key($field_output, array_flip($children));
}