eav_field-2.x-dev/src/Entity/EavValue.php

src/Entity/EavValue.php
<?php

namespace Drupal\eav_field\Entity;

use Drupal\Core\Annotation\Translation;
use Drupal\Core\Entity\Annotation\ContentEntityType;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity\BundleFieldDefinition;

/**
 * @ContentEntityType(
 *   id = "eav_value",
 *   label = @Translation("EAV value"),
 *   base_table = "eav_value",
 *   entity_keys = {
 *     "id" = "vid",
 *     "uuid" = "uuid",
 *   },
 *   translatable = FALSE,
 *   revisionable = FALSE,
 *   fieldable = FALSE,
 *   handlers = {
 *     "storage" = "\Drupal\eav_field\EavValueStorage",
 *     "form" = {
 *       "default" = "\Drupal\eav_field\Form\EavValueForm",
 *     },
 *   },
 *   links = {},
 * )
 */
class EavValue extends ContentEntityBase implements EavValueInterface {

  /**
   * {@inheritDoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type); /** @var BaseFieldDefinition[] $fields */

    $fields['vid']->setLabel(t('Value ID'));

    $fields['aid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Attribute'))
      ->setSetting('target_type', 'eav_attribute')
      ->setRequired(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'options_select',
      ]);

    $field_types = self::getFieldTypes();

    foreach ($field_types as $field_type => $field_settings) {
      // Used BundleFieldDefinition without BaseFieldDefinition to solve the following problem:
      // when value field configured as single-value it does not save values, because Drupal try
      // save data in "eav_value" table instead "eav_value__*_value" table.
      $fields[$field_type . '_value'] = BundleFieldDefinition::create($field_type)
        ->setLabel(t('Value'))
        ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);

      if ($field_settings) {
        $fields[$field_type . '_value']->setSettings($field_settings);
      }
    }

    return $fields;
  }

  /**
   * {@inheritDoc}
   */
  public static function load($id): ?EavValueInterface {
    return parent::load($id);
  }

  /**
   * {@inheritDoc}
   */
  public static function create(array $values = []): EavValueInterface {
    if (!empty($values['value']) && !empty($values['aid'])) {
      $attribute = NULL;
      if (is_numeric($values['aid'])) {
        $attribute = EavAttribute::load($values['aid']);
      }
      elseif ($values['aid'] instanceof EavAttributeInterface) {
        $attribute = $values['aid'];
      }

      if ($attribute) {
        $values[$attribute->getValueFieldName()] = $values['value'];
        unset($values['value']);
      }
    }

    return parent::create($values);
  }

  /**
   * {@inheritDoc}
   */
  public function save(): int {
    if ($attribute = $this->getAttributeEntity()) {
      $attribute->configureValueFieldDefinition();
    }
    return parent::save();
  }

  /**
   * {@inheritDoc}
   */
  public static function getFieldTypes(): array {
    $field_types = [
      'string' => ['max_length' => 1000],
      'string_long' => [],
      'integer' => [],
      'decimal' => [],
      'boolean' => [],
      'entity_reference' => [],
      'list_string' => [],
      'list_integer' => [],
    ];

    \Drupal::moduleHandler()->alter('eav_field_types', $field_types);

    return $field_types;
  }

  /**
   * {@inheritDoc}
   */
  public function getAttributeId(): ?int {
    return $this->get('aid')->target_id;
  }

  /**
   * {@inheritDoc}
   */
  public function getAttributeEntity(): ?EavAttributeInterface {
    return $this->get('aid')->entity;
  }

  /**
   * {@inheritDoc}
   */
  public function getValueFieldName(): ?string {
    if ($attribute = $this->getAttributeEntity()) {
      return $attribute->getValueFieldName();
    }
    return NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function getValueFieldItems(): ?FieldItemListInterface {
    if ($value_field_name = $this->getValueFieldName()) {
      return $this->get($value_field_name);
    }
    return NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function getValueFieldValues(): ?array {
    if ($value_field_items = $this->getValueFieldItems()) {
      return $value_field_items->getValue();
    }
    return NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function getValueFieldMainValues(): array {
    if (($value_field_items = $this->getValueFieldItems()) && !$value_field_items->isEmpty()) {
      $main_property_name = $value_field_items->first()->mainPropertyName();
      return array_map(function (FieldItemInterface $value_field_item) use ($main_property_name) {
        return $value_field_item->{$main_property_name};
      }, iterator_to_array($value_field_items));
    }
    return [];
  }

  /**
   * {@inheritDoc}
   */
  public function setValueFieldValue($value): void {
    $this->set($this->getValueFieldName(), $value);
  }

  /**
   * {@inheritDoc}
   */
  public function viewValueField() {
    $attribute = $this->getAttributeEntity();

    if ($attribute && ($formatter_type = $attribute->getValueFormatterType())) {
      $value_field_build = $this->getValueFieldItems()->view([
        'type' => $formatter_type,
        'settings' => $attribute->getValueFormatterSettings(),
        'label' => 'hidden',
      ]);
    }
    else {
      $value_field_build = $this->getValueFieldItems()->getString();
    }

    return $value_field_build;
  }

}

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

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