View source
<?php
namespace Drupal\radioactivity\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\radioactivity\Incident;
class RadioactivityEmitter extends FormatterBase {
public static function defaultSettings() {
return [
'energy' => 10,
'display' => 'none',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
return [
'energy' => [
'#title' => $this
->t('Energy'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => $this
->t('The amount of energy to emit when this field is displayed. Examples: 0.5, 10.'),
'#pattern' => '[0-9]+(\\.[0-9]+)?',
'#default_value' => $this
->getSetting('energy'),
],
'display' => [
'#title' => $this
->t('Display'),
'#type' => 'select',
'#options' => [
'none' => $this
->t('Only emit'),
'raw' => $this
->t('Energy level + emit'),
],
'#default_value' => $this
->getSetting('display'),
],
] + parent::settingsForm($form, $form_state);
}
public function settingsSummary() {
$summary = [];
$summary[] = t('Emit: @energy', [
'@energy' => $this
->getSetting('energy'),
]);
switch ($this
->getSetting('display')) {
case 'none':
$summary[] = $this
->t('Only emit');
break;
case 'raw':
$summary[] = $this
->t('Display energy level');
break;
}
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$shouldEmit = $this
->shouldEmit($items);
foreach ($items as $delta => $item) {
if ($shouldEmit) {
$incident = Incident::createFromFieldItemsAndFormatter($items, $item, $this);
$key = 'ra_emit_' . radioactivity_unique_emit_id();
$elements[$delta] = [
'#attached' => [
'library' => [
'radioactivity/triggers',
],
'drupalSettings' => [
$key => $incident
->toJson(),
],
],
];
}
switch ($this
->getSetting('display')) {
case 'raw':
$elements[$delta]['#markup'] = $this
->viewValue($item);
break;
}
}
return $elements;
}
public function view(FieldItemListInterface $items, $langcode = NULL) {
$build = parent::view($items, $langcode);
if ($this
->getSetting('display') == 'none') {
$children = Element::children($build);
$build = array_intersect_key($build, $children);
}
return $build;
}
protected function viewValue(FieldItemInterface $item) {
return $item->energy;
}
protected function shouldEmit(FieldItemListInterface $items) {
$entity = $items
->getEntity();
if (!$entity instanceof EntityPublishedInterface) {
return TRUE;
}
return $entity
->isPublished();
}
}