referencedEntities example

$comment_storage->delete($comments);

    foreach ($entities as $entity) {
      \Drupal::service('comment.statistics')->update($entity);
    }
  }

  /** * {@inheritdoc} */
  public function referencedEntities() {
    $referenced_entities = parent::referencedEntities();
    if ($this->getCommentedEntityId()) {
      $referenced_entities[] = $this->getCommentedEntity();
    }
    return $referenced_entities;
  }

  /** * {@inheritdoc} */
  public function permalink() {
    $uri = $this->toUrl();
    
/** * {@inheritdoc} */
  public function uriRelationships() {
    return $this->storage->uriRelationships();
  }

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

  /** * {@inheritdoc} */
  public function hasLinkTemplate($key) {
    return $this->storage->hasLinkTemplate($key);
  }

  /** * {@inheritdoc} */
// This method is internal, so check for errors on calling it only.     $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
    $entities = [$this->entity];
    // Our mocked entity->postLoad() returns NULL, so assert that.     $this->assertNull($this->entity->postLoad($storage$entities));
  }

  /** * @covers ::referencedEntities */
  public function testReferencedEntities() {
    $this->assertSame([]$this->entity->referencedEntities());
  }

  /** * @covers ::getCacheTags * @covers ::getCacheTagsToInvalidate * @covers ::addCacheTags */
  public function testCacheTags() {
    // Ensure that both methods return the same by default.     $this->assertEqualsCanonicalizing([$this->entityTypeId . ':' . 1]$this->entity->getCacheTags());
    $this->assertEqualsCanonicalizing([$this->entityTypeId . ':' . 1]$this->entity->getCacheTagsToInvalidate());

    
$summary[] = $this->t('No placeholder');
    }

    return $summary;
  }

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $entity = $items->getEntity();
    $referenced_entities = $items->referencedEntities();

    // Append the match operation to the selection settings.     $selection_settings = $this->getFieldSetting('handler_settings') + [
      'match_operator' => $this->getSetting('match_operator'),
      'match_limit' => $this->getSetting('match_limit'),
    ];

    // Append the entity if it is already created.     if (!$entity->isNew()) {
      $selection_settings['entity'] = $entity;
    }

    
$ref1->save();
    $ref2 = EntityTest::create(['name' => 'baz', 'type' => 'bar']);
    $ref2->save();
    \Drupal::state()->set('entity_test_reference_computed_target_ids', [$ref1->id()$ref2->id()]);

    $entity = EntityTestComputedField::create([]);
    $entity->save();

    /** @var \Drupal\entity_test\Plugin\Field\ComputedReferenceTestFieldItemList $field */
    $field = $entity->get('computed_reference_field');
    /** @var \Drupal\Core\Entity\EntityInterface[] $referenced_entities */
    $referenced_entities = $field->referencedEntities();

    // Check that ::referencedEntities() is working with computed fields.     $this->assertEquals($ref1->id()$referenced_entities[0]->id());
    $this->assertEquals($ref2->id()$referenced_entities[1]->id());
  }

  /** * Executes the computed properties tests for the given entity type. * * @param string $entity_type * The entity type to run the tests with. */
    $field_name = $this->fieldDefinition->getName();
    $field_state = static::getWidgetState($form['#parents']$field_name$form_state);
    $field_state['items'] = $items->getValue();
    static::setWidgetState($form['#parents']$field_name$form_state$field_state);
  }

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items */
    $referenced_entities = $items->referencedEntities();
    $view_builder = $this->entityTypeManager->getViewBuilder('media');
    $field_name = $this->fieldDefinition->getName();
    $parents = $form['#parents'];
    // Create an ID suffix from the parents to make sure each widget is unique.     $id_suffix = $parents ? '-' . implode('-', $parents) : '';
    $field_widget_id = implode(':', array_filter([$field_name$id_suffix]));
    $wrapper_id = $field_name . '-media-library-wrapper' . $id_suffix;
    $limit_validation_errors = [array_merge($parents[$field_name])];

    $settings = $this->getFieldSetting('handler_settings');
    $element += [
      

class EntityReferenceAutocompleteTagsWidget extends EntityReferenceAutocompleteWidget {

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items$delta$element$form$form_state);

    $element['target_id']['#tags'] = TRUE;
    $element['target_id']['#default_value'] = $items->referencedEntities();

    return $element;
  }

  /** * {@inheritdoc} */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    return $values['target_id'];
  }

}
// '0' or NULL are considered valid empty references.     if (empty($id)) {
      return;
    }
    /** @var \Drupal\Core\Entity\FieldableEntityInterface $referenced_entity */
    $referenced_entity = $value->entity;
    if ($referenced_entity) {
      $entity = $value->getEntity();
      $check_permission = TRUE;
      if (!$entity->isNew()) {
        $existing_entity = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
        $referenced_entities = $existing_entity->{$value->getFieldDefinition()->getName()}->referencedEntities();
        // Check permission if we are not already referencing the entity.         foreach ($referenced_entities as $ref) {
          if (isset($referenced_entities[$ref->id()])) {
            $check_permission = FALSE;
            break;
          }
        }
      }
      // We check that the current user had access to view any newly added       // referenced entity.       if ($check_permission && !$referenced_entity->access('view')) {
        
    // "autocreate" feature.     $target_entity_unsaved = $this->container->get('entity_type.manager')
      ->getStorage($this->referencedEntityType)
      ->create(['type' => $this->bundle, 'name' => $this->randomString()]);
    $reference_field[6]['entity'] = $target_entity_unsaved;
    $target_entities[6] = $target_entity_unsaved;

    // Set the field value.     $entity->{$this->fieldName}->setValue($reference_field);

    // Load the target entities using EntityReferenceField::referencedEntities().     $entities = $entity->{$this->fieldName}->referencedEntities();

    // Test returned entities:     // - Deltas must be preserved.     // - Non-existent entities must not be retrieved in target entities result.     foreach ($target_entities as $delta => $target_entity) {
      if (!empty($target_entity)) {
        if (!$target_entity->isNew()) {
          // There must be an entity in the loaded set having the same id for           // the same delta.           $this->assertEquals($entities[$delta]->id()$target_entity->id());
        }
        
if (($taxonomy_term = $this->routeMatch->getParameter('taxonomy_term')) && $taxonomy_term instanceof TermInterface) {
        return $taxonomy_term->id();
      }
    }
    // Load default argument from node.     if (!empty($this->options['node'])) {
      // Just check, if a node could be detected.       if (($node = $this->routeMatch->getParameter('node')) && $node instanceof NodeInterface) {
        $taxonomy = [];
        foreach ($node->getFieldDefinitions() as $field) {
          if ($field->getType() == 'entity_reference' && $field->getSetting('target_type') == 'taxonomy_term') {
            $taxonomy_terms = $node->{$field->getName()}->referencedEntities();
            /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
            foreach ($taxonomy_terms as $taxonomy_term) {
              $taxonomy[$taxonomy_term->id()] = $taxonomy_term->bundle();
            }
          }
        }
        if (!empty($this->options['limit'])) {
          $tids = [];
          // filter by vocabulary           foreach ($taxonomy as $tid => $vocab) {
            if (!empty($this->options['vids'][$vocab])) {
              

  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {}

  /** * {@inheritdoc} */
  public function postSave($update) {
    $entity = $this->getEntity();

    if (!$update) {
      // Add a new usage for newly uploaded files.       foreach ($this->referencedEntities() as $file) {
        \Drupal::service('file.usage')->add($file, 'file', $entity->getEntityTypeId()$entity->id());
      }
    }
    else {
      // Get current target file entities and file IDs.       $files = $this->referencedEntities();
      $ids = [];

      /** @var \Drupal\file\FileInterface $file */
      foreach ($files as $file) {
        $ids[] = $file->id();
      }

  public function getRelated(ResourceType $resource_type, FieldableEntityInterface $entity$related, Request $request) {
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
    $resource_relationship = $resource_type->getFieldByPublicName($related);
    $field_list = $entity->get($resource_relationship->getInternalName());

    // Remove the entities pointing to a resource that may be disabled. Even     // though the normalizer skips disabled references, we can avoid unnecessary     // work by checking here too.     /** @var \Drupal\Core\Entity\EntityInterface[] $referenced_entities */
    $referenced_entities = array_filter(
      $field_list->referencedEntities(),
      function DEntityInterface $entity) {
        return (bool) $this->resourceTypeRepository->get(
          $entity->getEntityTypeId(),
          $entity->bundle()
        );
      }
    );
    $collection_data = [];
    foreach ($referenced_entities as $referenced_entity) {
      $collection_data[] = $this->entityAccessChecker->getAccessCheckedResourceObject($referenced_entity);
    }
    
Home | Imprint | This part of the site doesn't use cookies.