association-1.0.0-alpha2/src/Field/AssociationReferenceItemList.php

src/Field/AssociationReferenceItemList.php
<?php

namespace Drupal\association\Field;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 * Computed field for fetching back references to associations for entities.
 *
 * Allows entities to maintain a reference to any of their current association
 * entities as a computed field. This is maintained as a convenience as well as
 * possibly caching this reference for the life of the loaded entity.
 */
class AssociationReferenceItemList extends EntityReferenceFieldItemList {

  use ComputedItemListTrait;

  /**
   * Fetch association entities linked to this content entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity which this field belongs to.
   *
   * @return \Drupal\association\Entity\AssociationLink[]
   *   An array of found association links the $entity belongs to.
   *   This can be an empty array, if no associations can be found.
   */
  protected function getAssociations(EntityInterface $entity) {
    /** @var \Drupal\association\Entity\Storage\AssociationLinkStorageInterface */
    $linkStorage = \Drupal::entityTypeManager()->getStorage('association_link');
    return $linkStorage->loadByTarget($entity);
  }

  /**
   * {@inheritdoc}
   */
  public function referencedEntities() {
    $this->ensureComputedValue();
    return parent::referencedEntities();
  }

  /**
   * {@inheritdoc}
   */
  public function preSave() {
    // Prevent the parent from calling preSave on the reference items.
  }

  /**
   * {@inheritdoc}
   */
  public function postSave($update) {
    // Prevent any post save because this is a computed field.
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  protected function computeValue() {
    $entity = $this->getEntity();
    $this->list = [];

    // Entities that have yet to be saved cannot have an association.
    if ($entity->isNew()) {
      return;
    }

    foreach ($this->getAssociations($entity) as $delta => $link) {
      $this->list[] = $this->createItem($delta, [
        'target_id' => $link->id(),
        'entity' => $link,
      ]);
    }
  }

}

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

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