improvements-2.x-dev/src/Plugin/Field/ComputedMapFieldItemList.php

src/Plugin/Field/ComputedMapFieldItemList.php
<?php

namespace Drupal\improvements\Plugin\Field;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 * Class for computed fields for extract data from "map" fields.
 *
 * $fields['example_map_field'] = BaseFieldDefinition::create('map')->setLabel('ExampleMapField');
 *
 * $fields['example_computed_field'] = BaseFieldDefinition::create('string')
 *   ->setLabel('Example computed field')
 *   ->setComputed(TRUE)
 *   ->setClass(ComputedMapFieldItemList::class)
 *   ->setSettings([
 *     'source_field_name' => 'example_map_field',
 *     'array_path' => 'path.to.value', // Equivalent to $field_value['path']['to']['value']
 *   ]);
 *
 * $fields['second_computed_field'] = BaseFieldDefinition::create('string')
 *   ->setLabel('Second computed field')
 *   ->setComputed(TRUE)
 *   ->setClass(ComputedMapFieldItemList::class)
 *   ->setSettings([
 *     'source_field_name' => 'example_map_field',
 *     'array_path' => [
 *       0 => 'path.to.value',    // Equivalent to $field_value['path']['to']['value']
 *       1 => 'other.value.path', // Equivalent to $field_value['other']['value']['path']
 *     ]
 *     'value_template' => '@0-@1',
 *   ]);
 */
class ComputedMapFieldItemList extends FieldItemList {

  use ComputedItemListTrait;

  /**
   * {@inheritdoc}
   */
  protected function computeValue(): void {
    $field_settings = $this->getSettings();
    $entity = $this->getEntity();

    if ($source_field_values = $entity->get($field_settings['source_field_name'])->getValue()) {
      // Single array_path
      if (is_string($field_settings['array_path'])) {
        $array_path = explode('.', $field_settings['array_path']);

        foreach ($source_field_values as $delta => $source_field_value) {
          $this->list[$delta] = $this->createItem($delta, NestedArray::getValue($source_field_value, $array_path));
        }
      }
      // Multiple array_path
      elseif (is_array($field_settings['array_path']) && !empty($field_settings['value_template'])) {
        $array_paths = [];
        foreach ($field_settings['array_path'] as $array_path) {
          $array_paths[] = explode('.', $array_path);
        }

        foreach ($source_field_values as $delta => $source_field_value) {
          $field_value_args = [];
          foreach ($array_paths as $array_path_delta => $array_path) {
            $field_value_args['@' . $array_path_delta] = NestedArray::getValue($source_field_value, $array_path);
          }
          $this->list[$delta] = $this->createItem($delta, strtr($field_settings['value_template'], $field_value_args));
        }
      }
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc