Commit 05bedda5 authored by Nia Kathoni's avatar Nia Kathoni Committed by Daniel Cothran
Browse files

Issue #3251123 by nikathone, andileco: Create interface for selecting colors...

Issue #3251123 by nikathone, andileco: Create interface for selecting colors when chart views are grouped or in other tricky situations, such as pie charts
parent 59c2d109
Loading
Loading
Loading
Loading
+26 −0
Original line number Diff line number Diff line
@@ -141,6 +141,13 @@ charts_views_field_data_provider:
      type: integer
      label: 'Weight'

charts_views_field_entity_grouping_selected_method_colors:
  type: mapping
  mapping:
    color:
      type: string
      label: Color

charts_config:
  type: mapping
  mapping:
@@ -165,6 +172,25 @@ charts_config:
          label: 'Data providers'
          sequence:
            type: charts_views_field_data_provider
        entity_grouping:
          type: mapping
          label: 'Entity grouping settings'
          mapping:
            color_selection_method:
              type: string
              label: 'Color selection method'
            selected_method:
              type: mapping
              label: 'Selected method'
              mapping:
                color_field_name:
                  type: string
                  label: 'Color field name'
                colors:
                  type: sequence
                  label: 'Colors'
                  sequence:
                    type: charts_views_field_entity_grouping_selected_method_colors
    display:
      type: charts_display
      label: 'Display'
+290 −6
Original line number Diff line number Diff line
@@ -5,10 +5,13 @@ namespace Drupal\charts\Element;
use Drupal\charts\Settings\ChartsDefaultSettings;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\views\Views;

/**
 * Provides a form element for setting a chart.
@@ -79,7 +82,7 @@ class BaseSettings extends FormElement {
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public static function processSettings(array &$element, FormStateInterface $form_state, array &$complete_form) {
  public static function processSettings(array &$element, FormStateInterface $form_state, array &$complete_form = []) {
    $supported_usage = ['basic_form', 'config_form', 'view_form'];
    if (empty($element['#used_in']) || !in_array($element['#used_in'], $supported_usage)) {
      throw new \InvalidArgumentException('The chart_base_settings element can only be used in basic, config and view forms.');
@@ -92,11 +95,16 @@ class BaseSettings extends FormElement {
    $wrapper_id = Html::getUniqueId($id_prefix . '-ajax-wrapper');
    $value = $element['#value'] ?? [];

    // Collect the main prefix and suffix just in case this element is wrapped
    // with one.
    $main_prefix = $element['#prefix'] ?? '';
    $main_suffix = $element['#suffix'] ?? '';

    // Enforce tree.
    $element = [
      '#tree' => TRUE,
      '#prefix' => '<div id="' . $wrapper_id . '">',
      '#suffix' => '</div>',
      '#prefix' => $main_prefix . '<div id="' . $wrapper_id . '">',
      '#suffix' => '</div>' . $main_suffix,
      // Pass the id along to other methods.
      '#wrapper_id' => $wrapper_id,
    ] + $element;
@@ -181,7 +189,7 @@ class BaseSettings extends FormElement {
    ];

    if ($used_in === 'view_form') {
      $element = self::processViewForm($element, $options, $form_state);
      $element = self::processViewForm($element, $options, $complete_form, $form_state);
    }
    elseif ($used_in === 'config_form') {
      $element = self::processConfigForm($element, $options);
@@ -812,10 +820,11 @@ class BaseSettings extends FormElement {
   * @return array
   *   The element.
   */
  private static function processViewForm(array $element, array $options, FormStateInterface $form_state) {
  private static function processViewForm(array $element, array $options, array &$complete_form, FormStateInterface $form_state) {
    if (!is_array($element['#field_options'])) {
      throw new \InvalidArgumentException('The chart_base_settings element need valid field options when used as view form.');
    }

    $element['display']['#weight'] = 2;
    $element['xaxis']['#weight'] = 2;
    $element['yaxis']['#weight'] = 2;
@@ -845,7 +854,7 @@ class BaseSettings extends FormElement {
      '#type' => 'radios',
      '#title' => new TranslatableMarkup('Label field'),
      '#options' => $field_options + ['' => new TranslatableMarkup('No label field')],
      '#default_value' => isset($options['fields']['label']) ? $options['fields']['label'] : $first_field,
      '#default_value' => $options['fields']['label'] ?? $first_field,
    ];

    // Enable stacking.
@@ -925,6 +934,102 @@ class BaseSettings extends FormElement {
      $field_option_element['#weight'] = $default_weight;
    }

    $element['fields']['entity_grouping'] = [
      '#title' => new TranslatableMarkup('Entity grouping settings'),
      '#type' => 'fieldset',
      '#collapsed' => TRUE,
      '#collapsible' => TRUE,
      '#weight' => 2,
      '#description' => new TranslatableMarkup('When grouping by an entity reference field, you can set the colors by entities or by a <a href="@href">color field</a>  attached to the entity type bundle in question.', [
        '@href' => 'https://drupal.org/projects/color_field',
      ]),
      '#description_display' => 'before',
    ];
    $module_handler = \Drupal::moduleHandler();
    if (empty($element['#view_charts_style_plugin'])) {
      return $element;
    }

    // Entity grouping settings.
    // Try to get it from $form_state.
    $style_options_values = $form_state->getValue(['style_options'], []);
    $grouping_field = $style_options_values['grouping'][0] ?? [];
    $grouping_field_name = $grouping_field['field'] ?? '';
    $grouping_field_element = $complete_form['options']['style_options']['grouping'][0]['field'] ?? [];
    $triggering_element = $form_state->getTriggeringElement();
    if (!$grouping_field_name && !$triggering_element && $grouping_field_element) {
      // Get the grouping field name from default value property.
      $grouping_field_name = $grouping_field_element['#default_value'] ?? '';
    }
    if (!$grouping_field_name) {
      return $element;
    }

    // Check which selection method the user want to go with.
    /** @var \Drupal\charts\Plugin\views\style\ChartsPluginStyleChart $style_plugin */
    $style_plugin = $element['#view_charts_style_plugin'];
    $view = $style_plugin->view;
    $selection_method_wrapper_id = $view->id() . '--' . $view->current_display . '--' . $style_plugin->getPluginId() . '--fields--entity-grouping--color-selection-method';
    $selected_method = $options['fields']['entity_grouping']['color_selection_method'] ?? 'by_entities_on_entity_reference';
    $element['fields']['entity_grouping']['color_selection_method'] = [
      '#type' => 'radios',
      '#title' => new TranslatableMarkup('Color selection method'),
      '#required' => TRUE,
      '#options' => [
        'by_entities_on_entity_reference' => new TranslatableMarkup('Set color by entities on entity reference'),
        // @todo remove if no plan to support this use case.
        //        'by_entities_on_current_entity' => new TranslatableMarkup('Set color by entities on current entity'),
      ],
      '#default_value' => $selected_method,
      '#ajax' => [
        'wrapper' => $selection_method_wrapper_id,
        'callback' => [get_called_class(), 'groupingChartSettingsSelectedMethodAjaxCallback'],
      ],
      '#limit_validation_errors' => [],
    ];
    if ($module_handler->moduleExists('color_field')) {
      $element['fields']['entity_grouping']['color_selection_method']['#options']['by_field_on_referenced_entity'] = new TranslatableMarkup('Set color based on a color field on entity reference');
      // @todo remove if no plan to support this use case.
      //      $element['fields']['entity_grouping']['color_selection_method']['#options']['by_field_on_current_entity'] = new TranslatableMarkup('Set color based on a color field on the current entity');
    }
    $element['fields']['entity_grouping']['selected_method'] = [
      '#type' => 'container',
      '#prefix' => '<div id="' . $selection_method_wrapper_id . '">',
      '#suffix' => '</div>',
      'colors' => [
        // Empty placeholder.
        '#markup' => '',
      ],
      'color_field_name' => [
        // Empty placeholder.
        '#markup' => '',
      ],
    ];

    $fields = $style_plugin->displayHandler->getOption('fields');
    $grouping_field_info = $fields[$grouping_field_name];
    // Get the entity type id of the reference field.
    if (!($entity_type_id = static::getReferenceEntityTypeId($grouping_field_info, $selected_method)) || empty($grouping_field_info['field'])) {
      return $element;
    }

    $metadata = [
      'grouping_field_name' => $grouping_field_name,
      'selected_method' => $selected_method,
      'entity_type_id' => $entity_type_id,
    ];
    $entity_type_manager = \Drupal::entityTypeManager();
    switch ($selected_method) {
      case 'by_entities_on_entity_reference':
        $metadata['colors'] = $options['fields']['entity_grouping']['selected_method']['colors'] ?? [];
        $element['fields']['entity_grouping']['selected_method']['colors'] = static::buildColorsSelectionSubFormByEntities($element, $metadata, $entity_type_manager);
        break;
      case 'by_field_on_referenced_entity':
        $metadata['color_field_name'] = $options['fields']['entity_grouping']['selected_method']['color_field_name'] ?? '';
        $element['fields']['entity_grouping']['selected_method']['color_field_name'] = static::buildColorsSelectionSubFormByFieldOnReferencedEntity($metadata, $entity_type_manager);
        break;
    }

    return $element;
  }

@@ -1090,6 +1195,23 @@ class BaseSettings extends FormElement {
    $form_state->setRebuild();
  }

  /**
   * Grouping chart settings ajax callback.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\core\form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The render array of the chart settings.
   */
  public static function groupingChartSettingsSelectedMethodAjaxCallback(array $form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    $entity_grouping_element = NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -2));
    return $entity_grouping_element['selected_method'];
  }

  /**
   * Builds the chart library configuration form into the settings.
   *
@@ -1125,4 +1247,166 @@ class BaseSettings extends FormElement {
    return $element;
  }

  /**
   * Helper method to retrieve the referenced entity type id.
   *
   * @param $field_info
   *   The field info.
   *
   * @return string
   *   The entity type id.
   */
  private static function getReferenceEntityTypeId($field_info, string $selection_method) {
    if (!$selection_method || empty($field_info['type']) || $field_info['type'] !== 'entity_reference_label' || empty($field_info['id'])) {
      return '';
    }
    $table = Views::viewsData()->get($field_info['table']);
    $field_id = $field_info['id'];
    return $table[$field_id]['relationship']['entity type'] ?? '';
  }

  private static function buildColorsSelectionSubFormByEntities(array $element, array $metadata, EntityTypeManagerInterface $entity_type_manager) {
    $empty_entity_colors = new TranslatableMarkup('No grouping by an entity reference field was detected or the selected field didn\'t have any entity or color field attached.');
    $colors = [
      '#markup' => '<p>' . $empty_entity_colors . '</p>',
    ];
    if (empty($metadata['grouping_field_name']) || empty($metadata['entity_type_id'])) {
      return $colors;
    }

    // Identifying the vocabulary this field could belong to.
    $field_config_storage = $entity_type_manager->getStorage('field_config');
    /** @var \Drupal\field\FieldConfigInterface[] $grouping_field_configs */
    $grouping_field_configs = $field_config_storage->loadByProperties(['field_name' => $metadata['grouping_field_name']]);
    $entity_type_id = $metadata['entity_type_id'];
    $bundle_ids = [];
    foreach ($grouping_field_configs as $key => $grouping_field_config) {
      $field_settings = $grouping_field_config->getSettings();
      if (empty($field_settings['target_type']) || $field_settings['target_type'] !== $entity_type_id) {
        continue;
      }
      $target_bundles = $field_settings['handler_settings']['target_bundles'] ?? [];
      foreach ($target_bundles as $bundle_id) {
        $bundle_ids[$bundle_id] = $bundle_id;
      }
    }

    // Load the entities by bundle.
    try {
      $entity_storage = $entity_type_manager->getStorage($entity_type_id);
      $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    } catch (\Exception $e) {
      return $colors;
    }

    $colors = [
      '#type' => 'table',
      '#empty'  => $empty_entity_colors,
      '#header' => [
        new TranslatableMarkup('Entity label'),
        new TranslatableMarkup('Bundle'),
        new TranslatableMarkup('Color'),
      ],
    ];
    $bundle_key = $entity_type->getKey('bundle');
    $query = $entity_storage->getQuery()
      ->condition($bundle_key, $bundle_ids, 'IN');

    if ($entity_type instanceof EntityPublishedInterface) {
      $published_key = $entity_type->getKey('published');
      $query->condition($published_key, TRUE);
    }

    // For now limiting to 150 entities.
    $entity_ids = $query->range(0, 150)
      ->execute();
    $has_uuid_key = $entity_type->hasKey('uuid');
    foreach ($entity_ids as $id) {
      $entity = $entity_storage->load($id);
      $color_id_key = $has_uuid_key ? $entity->get('uuid')->value : $entity->id();
      $field_option_element = &$colors[$color_id_key];
      $default_value = $metadata['colors'][$color_id_key]['color'] ?? '#000000';

      $label = $entity->label();
      $field_option_element['label'] = [
        '#markup' => new TranslatableMarkup('@label', [
          '@label' => $label,
        ]),
      ];
      $field_option_element['bundle'] = [
        '#markup' => new TranslatableMarkup('@bundle', [
          '@bundle' => $entity->bundle(),
        ]),
      ];
      $field_option_element['color'] = [
        '#type' => 'textfield',
        '#title' => new TranslatableMarkup('@label', ['@label' => $label]),
        '#title_display' => 'invisible',
        '#attributes' => [
          'TYPE' => 'color',
          'style' => 'min-width:50px;'
        ],
        '#size' => 10,
        '#maxlength' => 7,
        '#default_value' => $default_value,
      ];
    }

    return $colors;
  }

  private static function buildColorsSelectionSubFormByFieldOnReferencedEntity(array $metadata, EntityTypeManagerInterface $entity_type_manager) {
    // Identifying the vocabulary this field could belong to.
    $field_config_storage = $entity_type_manager->getStorage('field_config');
    /** @var \Drupal\field\FieldConfigInterface[] $grouping_field_configs */
    $grouping_field_configs = $field_config_storage->loadByProperties(['field_name' => $metadata['grouping_field_name']]);
    $entity_type_id = $metadata['entity_type_id'];
    $processed_bundle_ids = [];
    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager */
    $entity_field_manager = \Drupal::service('entity_field.manager');
    $color_field_options = [];
    foreach ($grouping_field_configs as $key => $grouping_field_config) {
      $field_settings = $grouping_field_config->getSettings();
      if (empty($field_settings['target_type']) || $field_settings['target_type'] !== $entity_type_id) {
        continue;
      }

      $target_bundles = $field_settings['handler_settings']['target_bundles'] ?? [];
      foreach ($target_bundles as $bundle_id) {
        if (in_array($bundle_id, $processed_bundle_ids)) {
          continue;
        }

        // Extract fields from bundle fields.
        foreach ($entity_field_manager->getFieldDefinitions($entity_type_id, $bundle_id) as $field_name => $field_definition) {
          if ($field_definition->getType() !== 'color_field_type' || !empty($color_field_options[$field_name])) {
            continue;
          }
          $color_field_options[$field_name] = $field_definition->getLabel();
        }
        $processed_bundle_ids[] = $bundle_id;
      }
    }

    if (!$color_field_options) {
      $empty_entity_field_name = new TranslatableMarkup('You can\'t set the color using the selected method because the referenced entity doesn\'t have any color field type configured.');
      return [
        '#theme' => 'status_messages',
        '#message_list' => ['warning' => [$empty_entity_field_name]],
        '#status_headings' => [
          'warning' => new TranslatableMarkup('Warning message'),
        ],
      ];
    }

    return [
      '#type' => 'select',
      '#title' => new TranslatableMarkup('Color field'),
      '#description' => new TranslatableMarkup('The color field on which we should get the color data from.'),
      '#options' => $color_field_options,
      '#default_value' => $metadata['color_field_name'] ?? '',
      '#required' => TRUE,
    ];
  }

}
+0 −1
Original line number Diff line number Diff line
@@ -159,7 +159,6 @@ class Chart extends RenderElement implements ContainerFactoryPluginInterface {

    // Ensure there's an x and y axis to provide defaults.
    $type_name = $element['#chart_type'];
    /** @var \Drupal\charts\TypeManager $type */
    $type = $this->chartsTypeManager->getDefinition($type_name);
    if ($type && $type['axis'] === ChartInterface::DUAL_AXIS) {
      $children_types = [];
+86 −4
Original line number Diff line number Diff line
@@ -14,7 +14,9 @@ use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\TwigEnvironment;
use Drupal\views\Plugin\views\field\EntityField;
use Drupal\views\Plugin\views\style\StylePluginBase;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
@@ -181,6 +183,7 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
      return;
    }

    $settings_wrapper = 'views-charts-plugin-style-chart-options-settings-wrapper';
    // Limit grouping options (we only support one grouping field).
    if (isset($form['grouping'][0])) {
      $form['grouping'][0]['field']['#title'] = $this->t('Grouping field');
@@ -189,6 +192,13 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
      // Grouping by rendered version has no effect in charts. Hide the options.
      $form['grouping'][0]['rendered']['#access'] = FALSE;
      $form['grouping'][0]['rendered_strip']['#access'] = FALSE;

      // Add ajax related to grouping to allow taxonomy colors selection when
      // the field is an entity reference.
      $form['grouping'][0]['field']['#ajax'] = [
        'wrapper' => $settings_wrapper,
        'callback' => [get_called_class(), 'groupingChartSettingsAjaxCallback'],
      ];
    }
    if (isset($form['grouping'][1])) {
      $form['grouping'][1]['#access'] = FALSE;
@@ -198,11 +208,14 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
    $field_options = $this->displayHandler->getFieldLabels();
    $form_state->set('default_options', $this->options);
    $form['chart_settings'] = [
      '#prefix' => '<div id="' . $settings_wrapper . '">',
      '#type' => 'charts_settings',
      '#used_in' => 'view_form',
      '#required' => TRUE,
      '#field_options' => $field_options,
      '#default_value' => $this->options['chart_settings'],
      '#suffix' => '</div>',
      '#view_charts_style_plugin' => $this,
    ];
  }

@@ -214,7 +227,7 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
    $chart_settings = $this->options['chart_settings'];
    $selected_data_fields = is_array($chart_settings['fields']['data_providers']) ? $this->getSelectedDataFields($chart_settings['fields']['data_providers']) : NULL;

    // Avoid calling validation before arriving on the view edit page.
    // Avoid calling validation before arriving at the view edit page.
    if ($this->routeMatch->getRouteName() != 'views_ui.add' && empty($selected_data_fields)) {
      $errors[] = $this->t('At least one data field must be selected in the chart configuration before this chart may be shown');
    }
@@ -481,6 +494,8 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
    $grouping_field_info = $groupings[$grouping_level];
    $grouping_field = $grouping_field_info['field'];
    $xaxis_label_field_key = $this->getLabelFieldKey();
    $chart_settings = $this->options['chart_settings'];
    $color_selection_method = $chart_settings['fields']['entity_grouping']['color_selection_method'] ?? '';

    foreach ($records as $index => $row) {
      $set = &$sets;
@@ -505,6 +520,19 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory

      // Create the group if it does not exist yet.
      if (empty($set[$grouping])) {
        $grouping_entity_field = $this->view->field[$grouping_field];
        $group_field_name = $grouping_entity_field ? ($grouping_entity_field->definition['field_name'] ?? '') : '';
        if ($color_selection_method && $group_field_name && $grouping_entity_field instanceof EntityField && $row instanceof ResultRow) {
          switch ($color_selection_method) {
            case 'by_entities_on_entity_reference':
              $set[$grouping]['color'] = $this->extractGroupedSelectedColorByEntity($grouping_entity_field, $row, $group_field_name);
              break;
            case 'by_field_on_referenced_entity':
              $set[$grouping]['color'] = $this->extractGroupedSelectedColorOnReferencedEntityField($grouping_entity_field, $row, $group_field_name);
              break;
          }
        }

        $set[$grouping]['group'] = $group_content;
        $set[$grouping]['level'] = $grouping_level;
        $set[$grouping]['rows'] = [];
@@ -549,9 +577,8 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
        unset($children_displays[$key]);
      }
    }
    $children_displays = array_values($children_displays);

    return $children_displays;
    return array_values($children_displays);
  }

  /**
@@ -643,9 +670,9 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
    }

    $series_index = 0;
    foreach ($sets as $set_label => $data_set) {
    $element_key_prefix = $this->view->current_display . '__' . $label_field_key;
    $chart_settings = $this->options['chart_settings'];
    foreach ($sets as $set_label => $data_set) {
      /** Drupal\views\ResultRow $row */
      $name = strtolower(Html::cleanCssIdentifier($set_label));
      $element_key = $element_key_prefix . '__' . $name;
@@ -659,6 +686,9 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
        '#suffix' => $chart_settings['yaxis']['suffix'] ?? NULL,
        '#decimal_count' => $chart_settings['yaxis']['decimal_count'] ?? '',
      ];
      if (!empty($data_set['color'])) {
        $chart[$element_key]['#color'] = $data_set['color'];
      }

      foreach ($data_set['rows'] as $result_number => $row) {
        $set_id = $row->xaxis_label_index ?? $series_index;
@@ -677,4 +707,56 @@ class ChartsPluginStyleChart extends StylePluginBase implements ContainerFactory
    }
  }

  /**
   * Grouping chart settings ajax callback.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\core\form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The render array of the chart settings.
   */
  public static function groupingChartSettingsAjaxCallback(array $form, FormStateInterface $form_state) {
    return $form['options']['style_options']['chart_settings'];
  }

  private function extractGroupedSelectedColorByEntity(EntityField $view_entity_field, ResultRow $row, string $group_field_name) {
    $chart_settings = $this->options['chart_settings'];
    $colors_settings = $chart_settings['fields']['entity_grouping']['selected_method']['colors'] ?? [];
    /** @var \Drupal\Core\Entity\ContentEntityInterface $host_entity */
    $host_entity = $view_entity_field->getEntity($row);
    /** @var \Drupal\Core\Entity\ContentEntityInterface $referenced_entity */
    $referenced_entity = $host_entity->get($group_field_name)->entity;
    if (!$referenced_entity || !$colors_settings) {
      return '';
    }

    $entity_type = $referenced_entity->getEntityType();
    $has_uuid_key = $entity_type->hasKey('uuid');
    $color_id_key = $has_uuid_key ? $referenced_entity->get('uuid')->value : $referenced_entity->id();
    return $colors_settings[$color_id_key]['color'] ?? '';
  }

  private function extractGroupedSelectedColorOnReferencedEntityField(EntityField $view_entity_field, ResultRow $row, string $group_field_name) {
    $chart_settings = $this->options['chart_settings'];
    $color_field_name = $chart_settings['fields']['entity_grouping']['selected_method']['color_field_name'] ?? '';
    if (!$color_field_name) {
      return '';
    }
    /** @var \Drupal\Core\Entity\ContentEntityInterface $host_entity */
    $host_entity = $view_entity_field->getEntity($row);
    /** @var \Drupal\Core\Entity\ContentEntityInterface $referenced_entity */
    $referenced_entity = $host_entity->get($group_field_name)->entity;
    $field_item_list = $referenced_entity ? $referenced_entity->get($color_field_name) : NULL;
    if (!$field_item_list || $field_item_list->isEmpty()) {
      return '';
    }

    /** @var \Drupal\color_field\Plugin\Field\FieldType\ColorFieldType $color_field */
    $color_field = $field_item_list->first();
    return $color_field->getFieldDefinition()->getType() === 'color_field_type' ? $color_field->color : '';
  }

}
+1 −1
Original line number Diff line number Diff line
@@ -12,7 +12,7 @@ class Util {
  /**
   * Views Data.
   *
   * @param \Drupal\views\ViewExecutable $view
   * @param \Drupal\views\ViewExecutable|null $view
   *   View.
   * @param array $labelValues
   *   Label Values.