You are here

public function Details::viewElements in Double Field 8.3

Same name and namespace in other branches
  1. 4.x src/Plugin/Field/FieldFormatter/Details.php \Drupal\double_field\Plugin\Field\FieldFormatter\Details::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/Details.php, line 57

Class

Details
Plugin implementations for 'details' formatter.

Namespace

Drupal\double_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];
  $settings = $this
    ->getSettings();
  foreach ($items as $delta => $item) {
    $values = [];
    foreach ([
      'first',
      'second',
    ] as $subfield) {
      $values[$subfield] = $item->{$subfield};

      // Copy the property to a variable because of its magic nature.
      $value = $item->{$subfield};

      // The value can be a render array if link option is enabled.
      if (is_array($value)) {
        $values[$subfield]['#prefix'] = $settings[$subfield]['prefix'];
        $values[$subfield]['#suffix'] = $settings[$subfield]['suffix'];
      }
      else {
        $values[$subfield] = $settings[$subfield]['prefix'] . $value . $settings[$subfield]['suffix'];
      }
    }
    $element[$delta] = [
      '#title' => $values['first'],
      '#value' => $values['second'],
      '#type' => 'details',
      '#open' => $settings['open'],
      '#attributes' => [
        'class' => [
          'double-field-details',
        ],
      ],
    ];
  }
  return $element;
}