ComputedFormatter.php in Computed Field 8
File
src/Plugin/Field/FieldFormatter/ComputedFormatter.php
View source
<?php
namespace Drupal\computed_field\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
class ComputedFormatter extends FormatterBase {
public static function defaultSettings() {
return array(
'sanitized' => TRUE,
) + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
return array(
'sanitized' => array(
'#type' => 'checkbox',
'#title' => t('Sanitized'),
'#default_value' => $this
->getSetting('sanitized'),
),
) + parent::settingsForm($form, $form_state);
}
public function settingsSummary() {
$summary = [];
$summary[] = $this
->getSetting('sanitized') ? t('Sanitized') : t('Unsanitized');
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#markup' => $this
->viewValue($item),
];
}
return $elements;
}
protected function viewValue(FieldItemInterface $item) {
$display_output = $item
->executeDisplayCode();
if ($this
->getSetting('sanitized')) {
return nl2br(SafeMarkup::checkPlain($display_output));
}
else {
return nl2br($display_output);
}
}
}