You are here

public function AddtocalView::viewElements in Add to Cal 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/AddtocalView.php \Drupal\addtocal\Plugin\Field\FieldFormatter\AddtocalView::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 DateTimeCustomFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/AddtocalView.php, line 150

Class

AddtocalView
Plugin annotation @FieldFormatter( id = "addtocal_view", label = @Translation("Add to Cal"), field_types = { "date", "datestamp", "datetime", "daterange", } )

Namespace

Drupal\addtocal\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $entity = $items
    ->getEntity();
  $settings = $this
    ->getSettings();

  // Appends the field name into the settings for form use
  $field = $this->fieldDefinition;
  $field_name = $field
    ->get('field_name');
  $settings['field_name'] = $field_name;
  foreach ($items as $delta => $item) {

    /** @var \Drupal\Core\Datetime\DrupalDateTime $start_date */
    $start_date = NULL;

    /** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
    $end_date = NULL;
    if ($field
      ->getType() == 'daterange') {
      if (!empty($item->start_date)) {
        $start_date = $item->start_date;
      }
      if (!empty($item->end_date)) {
        $end_date = $item->end_date;
      }
    }
    else {
      if ($field
        ->getType() == 'date_recur') {
        if (!empty($item->value)) {
          $start_date = new DrupalDateTime($item->value, 'UTC');
        }
        if (!empty($item->end_value)) {
          $end_date = new DrupalDateTime($item->end_value, 'UTC');
        }
      }
      else {
        if (!empty($item->date)) {
          $start_date = $item->date;
        }
      }
    }
    if ($start_date && $end_date && $start_date
      ->format('U') !== $end_date
      ->format('U')) {
      $elements[$delta] = [
        'start_date' => $this
          ->buildDate($start_date),
        'separator' => [
          '#plain_text' => ' ' . $settings['separator'] . ' ',
        ],
        'end_date' => $this
          ->buildDate($end_date),
      ];
    }
    elseif ($start_date) {
      $elements[$delta] = $this
        ->buildDate($start_date);
    }
    else {
      $elements[$delta] = [];
    }

    // Attaches the calendar form to each element
    $form = new AddToCalForm($entity, $settings, $delta);
    $form = \Drupal::formBuilder()
      ->getForm($form);
    $elements[$delta] += $form;
  }
  return $elements;
}