FaqFieldAnchorListFormatter.php in FAQ Field 8
File
src/Plugin/Field/FieldFormatter/FaqFieldAnchorListFormatter.php
View source
<?php
namespace Drupal\faqfield\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
class FaqFieldAnchorListFormatter extends FormatterBase {
public static function defaultSettings() {
return [
'anchor_list_type' => 'ul',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['anchor_list_type'] = [
'#type' => 'select',
'#title' => $this
->t('Anchor link list type'),
'#default_value' => $this
->getSetting('anchor_list_type'),
'#options' => [
'ul' => $this
->t('<ul> - Bullet list'),
'ol' => $this
->t('<ol> - Numeric list'),
],
'#description' => $this
->t('The type of HTML list used for the anchor link list.'),
];
return $elements;
}
public function settingsSummary() {
$summary = [];
if ($this
->getSetting('anchor_list_type') == 'ul') {
$summary[] = $this
->t('Bullet list');
}
else {
$summary[] = $this
->t('Numeric list');
}
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$default_format = $this
->getFieldSetting('default_format');
$element_items = [];
foreach ($items as $item) {
$format = !empty($item->answer_format) ? $item->answer_format : $default_format;
$element_items[] = [
'question' => $item->question,
'answer' => $item->answer,
'answer_format' => $format,
];
}
$elements = [];
if ($element_items) {
$elements[0] = [
'#theme' => 'faqfield_anchor_list_formatter',
'#items' => $element_items,
'#list_type' => $this
->getSetting('anchor_list_type'),
];
}
return $elements;
}
}