Skip to content
Snippets Groups Projects
Commit 368769c5 authored by Joe 🤘 Shindelar's avatar Joe 🤘 Shindelar Committed by Qiangjun Ran
Browse files

Issue #3282251 by jungle: Update field_example to demonstrate configurable field formatter plugins

parent be3ef014
No related branches found
No related tags found
1 merge request!11Issue #3282251: Update field_example to demonstrate configurable field formatter plugins
......@@ -10,3 +10,13 @@ field.field_example_rgb.value:
value:
type: string
label: 'Value'
# Relates to the field_example_color_background formatter plugin.
# \Drupal\field_example\Plugin\Field\FieldFormatter\ColorBackgroudFormatter.
field.formatter.settings.field_example_color_background:
type: mapping
label: Background color formatter settings
mapping:
adjust_text_color:
type: boolean
label: Automatically adjust foreground text color based on background color lightness.
......@@ -4,10 +4,17 @@
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'field_example_color_background' formatter.
*
* This example demonstrates how a field formatter plugin can provide
* configuration options to the user and then alter the output based on their
* choices. We'll add a toggle, that defaults to on, for a feature that
* attempts to automatically adjust the foreground color of the text to either
* black or white depending on the lightness of the background color.
*
* @FieldFormatter(
* id = "field_example_color_background",
* label = @Translation("Change the background of the output text"),
......@@ -25,16 +32,109 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
// Set the value of the CSS color property depending on user provided
// configuration. Individual configuration items can be accessed with
// $this->getSetting('key') where 'key' is the same as the key in the
// form array from settingsForm() and what's defined in the configuration
// schema.
$text_color = 'inherit';
if ($this->getSetting('adjust_text_color')) {
$text_color = $this->lightness($item->value) < 50 ? 'white' : 'black';
}
$elements[$delta] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $this->t('The content area color has been changed to @code', ['@code' => $item->value]),
'#attributes' => [
'style' => 'background-color: ' . $item->value,
'style' => 'background-color: ' . $item->value . '; color: ' . $text_color,
],
];
}
return $elements;
}
/**
* {@inheritdoc}
*
* Set the default values for the formatter's configuration.
*/
public static function defaultSettings() {
// The keys of this array should match the form element names in
// settingsForm(), and the schema defined in
// config/schema/field_example.schema.yml.
return [
'adjust_text_color' => TRUE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*
* Define the Form API widgets a user should see when configuring the
* formatter. These are displayed when a user clicks the gear icon in the row
* for a formatter on the manage display page.
*
* The field_ui module takes care of handling submitted form values.
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
// Create a new array with one or more form elements. $form is available for
// context but you should not add your elements to it directly.
$elements = [];
// The keys of the array, 'adjust_text_color' in this case, should match
// what is defined in ::defaultSettings(), and the field_example.schema.yml
// schema. The values collected by the form will be automatically stored
// as part of the field instance configuration so you do not need to
// implement form submission processing.
$elements['adjust_text_color'] = [
'#type' => 'checkbox',
// The current configuration for this setting for the field instance can
// be accessed via $this->getSetting().
'#default_value' => $this->getSetting('adjust_text_color'),
'#title' => $this->t('Adjust foreground text color'),
'#description' => $this->t('Switch the foreground color between black and white depending on lightness of the background color.'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
// This optional summary text is displayed on the manage displayed in place
// of the formatter configuration form when the form is closed. You'll
// usually see it in the list of fields on the manage display page where
// this formatter is used.
$state = $this->getSetting('adjust_text_color') ? $this->t('yes') : $this->t('no');
$summary[] = $this->t('Adjust text color: @state', ['@state' => $state]);
return $summary;
}
/**
* Determine lightness of a color.
*
* This might not be the best way to determine if the contrast between the
* foreground and background colors is legible. But it'll work well enough for
* this demonstration.
*
* Logic from https://stackoverflow.com/a/12228730/8616016.
*
* @param string $color
* A color in hex format, leading '#' is optional.
*
* @return float
* Percentage of lightness of the provided color.
*/
protected function lightness(string $color) {
$hex = ltrim($color, '#');
// Convert the hex string to RGB.
$r = hexdec($hex[0].$hex[1]);
$g = hexdec($hex[2].$hex[3]);
$b = hexdec($hex[4].$hex[5]);
// Calculate the HSL lightness value and return that as a percent.
return ((max($r, $g, $b) + min($r, $g, $b)) / 510.0) * 100;
}
}
......@@ -39,9 +39,10 @@ public function testSingleValueField() {
// Details to be submitted for content creation.
$title = $this->randomMachineName(20);
$color = '#00ff00';
$edit = [
'title[0][value]' => $title,
'field_' . $this->fieldName . '[0][value]' => '#00ff00',
'field_' . $this->fieldName . '[0][value]' => $color,
];
// Submit the content creation form.
......@@ -49,7 +50,33 @@ public function testSingleValueField() {
$assert->pageTextContains((string) new FormattableMarkup('@type @title has been created', ['@type' => $this->contentTypeName, '@title' => $title]));
// Verify color.
$assert->pageTextContains('The content area color has been changed to #00ff00');
$assert->pageTextContains('The content area color has been changed to ' . $color);
// Test the formatter's configuration options. First verify the foreground
// color calculation logic is enabled by default and working.
$assert->elementAttributeNotContains('css', 'p[style*="background-color: '. $color . '"]', 'style', 'color: inherit');
$assert->elementAttributeContains('css', 'p[style*="background-color: '. $color . '"]', 'style', 'color: black');
// Then toggle the setting off.
\Drupal::service('entity_display.repository')
->getViewDisplay('node', $this->contentTypeName)
->setComponent('field_' . $this->fieldName, [
'label' => 'inline',
'weight' => 20,
'type' => 'field_example_color_background',
'settings' => [
'adjust_text_color' => 0,
],
])
->save();
// Clear the cache to ensure we get updated field output.
//drupal_flush_all_caches();
$this->getSession()->reload();
$assert = $this->assertSession();
$assert->elementAttributeContains('css', 'p[style*="background-color: '. $color . '"]', 'style', 'color: inherit');
$assert->elementAttributeNotContains('css', 'p[style*="background-color: '. $color . '"]', 'style', 'color: black');
}
/**
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment