ListFormatter.php in Facebook Instant Articles 8.2
File
src/Plugin/Field/FieldFormatter/ListFormatter.php
View source
<?php
namespace Drupal\fb_instant_articles\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Facebook\InstantArticles\Elements\InstantArticle;
use Facebook\InstantArticles\Elements\ListElement;
use Facebook\InstantArticles\Elements\ListItem;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class ListFormatter extends FormatterBase {
public static function defaultSettings() {
return [
'is_ordered' => FALSE,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['is_ordered'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Ordered list'),
'#description' => $this
->t('Should this list be ordered or not?'),
'#default_value' => $this
->getSetting('is_ordered'),
];
return $element;
}
public function settingsSummary() {
return [
$this
->getSetting('is_ordered') ? $this
->t('Ordered') : $this
->t('Unordered'),
];
}
public function viewInstantArticle(FieldItemListInterface $items, InstantArticle $article, $region, NormalizerInterface $normalizer, $langcode = NULL) {
if (!$items
->isEmpty()) {
if ($this
->getSetting('is_ordered')) {
$list = ListElement::createOrdered();
}
else {
$list = ListElement::createUnordered();
}
foreach ($items as $delta => $item) {
$list
->addItem(ListItem::create()
->appendText($item->value));
}
$article
->addChild($list);
}
}
}