Skip to content
Snippets Groups Projects

Issue #3176391 by cburschka, rahulrasgon: Image links with multiple query...

Merged nicxvan requested to merge issue/rest_views-3180274:3180274-add-a-field into 3.0.x
<?php
namespace Drupal\rest_views\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\Annotation\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\OptGroup;
use Drupal\rest_views\SerializedData;
/**
* Export a list.
*
* @FieldFormatter(
* id = "list_export",
* label = @Translation("Export list"),
* field_types = {
* "list_integer",
* "list_float",
* "list_string",
* }
* )
*/
class ListExportFormatter extends FormatterBase {
const VALUE_LABEL = 'value_label';
const KEY_VALUE = 'key_value';
const EXPORT_OPTIONS = [
self::VALUE_LABEL => 'Export label and value separately',
self::KEY_VALUE => 'Export as key/value',
];
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode): array {
$elements = [];
$export_format = $this->getSetting('export_format');
// Only collect allowed options if there are actually items to display.
if ($items->count()) {
$provider = $items->getFieldDefinition()
->getFieldStorageDefinition()
->getOptionsProvider('value', $items->getEntity());
// Flatten the possible options, to support opt groups.
$options = OptGroup::flattenOptions($provider->getPossibleOptions());
foreach ($items as $delta => $item) {
$value = $item->value;
$label = isset($options[$value]) ? $options[$value]: "";
if ($export_format == self::VALUE_LABEL) {
$data = [
"value" => $value,
"label" => $label,
];
} else {
$data = [$value => $label];
}
$elements[$delta] = [
'#type' => 'data',
'#data' => SerializedData::create($data),
];
}
}
return $elements;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings(): array {
return ['export_format' => self::VALUE_LABEL] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['export_format'] = [
'#type' => 'radios',
'#title' => $this->t('Export format'),
'#default_value' => $this->getSetting('export_format'),
'#options' => array_map([$this, 't'], self::EXPORT_OPTIONS),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary(): array {
$summary = parent::settingsSummary();
$export_format = $this->getSetting('export_format');
$summary[] = $this->t(self::EXPORT_OPTIONS[$export_format]);
return $summary;
}
}
Loading