improvements-2.x-dev/src/Plugin/Field/FieldFormatter/EntityHtmlAttributeFormatter.php
src/Plugin/Field/FieldFormatter/EntityHtmlAttributeFormatter.php
<?php
namespace Drupal\improvements\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\druhels\EntityHelper;
/**
* @TODO Add tests
*/
#[FieldFormatter(
id: 'entity_html_attribute_formatter',
label: new TranslatableMarkup('Entity html attribute'),
field_types: [
'string',
'integer',
'list_string',
],
)]
class EntityHtmlAttributeFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings(): array {
$options = parent::defaultSettings();
$options['attribute_name'] = 'class';
$options['attribute_value_pattern'] = '';
return $options;
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state): array {
$form = parent::settingsForm($form, $form_state);
$form['attribute_name'] = [
'#type' => 'textfield',
'#title' => $this->t('Attribute name'),
'#default_value' => $this->getSetting('attribute_name'),
];
$form['attribute_value_pattern'] = [
'#type' => 'textfield',
'#title' => $this->t('Attribute value pattern'),
'#description' => $this->t('Example: @example', ['@example' => Markup::create('<code>grid-columns-@value</code>')]),
'#default_value' => $this->getSetting('attribute_value_pattern'),
];
return $form;
}
/**
* {@inheritDoc}
*/
public function settingsSummary(): array {
$summary = [];
if ($attribute_name = $this->getSetting('attribute_name')) {
$summary[] = $this->t('Attribute name') . ': ' . $attribute_name;
}
if ($attribute_value_pattern = $this->getSetting('attribute_value_pattern')) {
$summary[] = $this->t('Attribute value pattern') . ': ' . $attribute_value_pattern;
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode): array {
$build = [];
$formatter_settings = $this->getSettings();
$attribute_name = $formatter_settings['attribute_name'];
$items_values = EntityHelper::getFieldValues($items);
foreach ($items_values as $item_value) {
$attribute_value = str_replace('@value', $item_value, $formatter_settings['attribute_value_pattern']);
if ($attribute_name == 'class') {
$build['#entity_attributes'][$attribute_name][] = $attribute_value;
}
else {
$build['#entity_attributes'][$attribute_name] = $attribute_value;
}
}
return $build;
}
}
