View source
<?php
namespace Drupal\radioactivity\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Render\Element;
use Drupal\radioactivity\Incident;
use Drupal\Core\Form\FormStateInterface;
class RadioactivityReferenceEmitter extends RadioactivityReferenceFormatterBase {
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 = [];
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $entity) {
$incident = Incident::createFromFieldItemsAndFormatter($items, $entity->_referringItem, $this);
$key = 'ra_emit_' . radioactivity_unique_emit_id();
$element = [
'#attached' => [
'library' => [
'radioactivity/triggers',
],
'drupalSettings' => [
$key => $incident
->toJson(),
],
],
];
if ($this
->getSetting('display') === 'raw') {
$element['#markup'] = $entity
->getEnergy();
$element['#cache']['tags'] = $entity
->getCacheTags();
}
$elements[$delta] = $element;
}
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;
}
}