TextHeaderFormatter.php in Header formatter 8
File
src/Plugin/Field/FieldFormatter/TextHeaderFormatter.php
View source
<?php
namespace Drupal\header_formatter\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
class TextHeaderFormatter extends FormatterBase {
public static function defaultSettings() {
return parent::defaultSettings() + [
'level' => 2,
];
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
if (!parent::isApplicable($field_definition)) {
return FALSE;
}
$cardinality = $field_definition
->getFieldStorageDefinition()
->getCardinality();
return $cardinality === 1;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#type' => 'html_tag',
'#tag' => "h{$this->getSetting('level')}",
'#value' => $item->value,
];
}
return $elements;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$settingsForm = parent::settingsForm($form, $form_state);
$settingsForm['level'] = [
'#type' => 'select',
'#options' => [
1 => 'H1',
2 => 'H2',
3 => 'H3',
4 => 'H4',
5 => 'H5',
6 => 'H6',
],
];
return $settingsForm;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
$summary[] = "Header level: H{$this->getSetting('level')}";
return $summary;
}
}