You are here

public function FaqFieldAccordionFormatter::viewElements in FAQ Field 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Field/FieldFormatter/FaqFieldAccordionFormatter.php \Drupal\faqfield\Plugin\Field\FieldFormatter\FaqFieldAccordionFormatter::viewElements()

This will not be themeable, because changes would break jQuery UI accordion functionality!

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/FaqFieldAccordionFormatter.php, line 147

Class

FaqFieldAccordionFormatter
Plugin implementation of the 'faqfield_accordion' formatter.

Namespace

Drupal\faqfield\Plugin\Field\FieldFormatter

Code

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

  // Generate faqfield id by fieldname and entity id.
  $faqfield_id = 'faqfield_' . $this->fieldDefinition
    ->getName() . '_' . $items
    ->getEntity()
    ->getEntityTypeId() . '_' . $items
    ->getEntity()
    ->id();

  // If active setting was blank, set FALSE so no element will be active.
  if (!is_numeric($settings['active'])) {
    $settings['active'] = FALSE;
  }
  $element_items = [];
  foreach ($items as $item) {

    // Decide whether to use the default format or the custom one.
    $format = !empty($item->answer_format) ? $item->answer_format : $default_format;
    $element_items[] = [
      'question' => $item->question,
      'answer' => $item->answer,
      'answer_format' => $format,
    ];
  }
  if ($element_items) {
    $elements[0] = [
      '#theme' => 'faqfield_jquery_accordion_formatter',
      '#items' => $element_items,
      '#id' => $faqfield_id,
      '#attached' => [
        // Add FAQ Field accordion library.
        'library' => [
          'faqfield/faqfield.accordion',
        ],
        'drupalSettings' => [
          'faqfield' => [
            '#' . $faqfield_id => $settings,
          ],
        ],
      ],
    ];
  }
  return $elements;
}