loadMultipleRevisions example

    // @see https://www.drupal.org/project/drupal/issues/2554235     $step_size = Settings::get('entity_update_batch_size', 50);
    $entity_identifiers = $this->database->select($table_name, 't')
      ->condition("t.$identifier_field", $sandbox['current_id'], '>')
      ->fields('t', [$identifier_field])
      ->orderBy($identifier_field, 'ASC')
      ->range(0, $step_size)
      ->execute()
      ->fetchCol();

    /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */
    $entities = $load_revisions ? $this->storage->loadMultipleRevisions($entity_identifiers) : $this->storage->loadMultiple($entity_identifiers);

    /** @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage $temporary_storage */
    $temporary_storage = $this->entityTypeManager->createHandlerInstance($entity_type->getStorageClass()$entity_type);
    $temporary_storage->setEntityType($entity_type);
    $temporary_storage->setFieldStorageDefinitions($field_storage_definitions);
    $temporary_storage->setTableMapping($sandbox['temporary_table_mapping']);

    foreach ($entities as $identifier => $entity) {
      try {
        if (!$original->isRevisionable() && $entity_type->isRevisionable()) {
          // Set the revision ID to be same as the entity ID.
$changes_count[$entity_type_id] = $this->entityTypeManager->getDefinition($entity_type_id)->getCountLabel(count($tracked_entities));

        $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
        if ($this->entityTypeManager->hasHandler($entity_type_id, 'list_builder')) {
          $list_builder = $this->entityTypeManager->getListBuilder($entity_type_id);
        }
        else {
          $list_builder = $this->entityTypeManager->createHandlerInstance(EntityListBuilder::class$entity_type);
        }

        $revisions = $this->entityTypeManager->getStorage($entity_type_id)->loadMultipleRevisions(array_keys($tracked_entities));

        // Load all users at once.         $user_ids = [];
        foreach ($revisions as $revision) {
          if ($revision instanceof EntityOwnerInterface) {
            $user_ids[$revision->getOwnerId()] = $revision->getOwnerId();
          }
        }

        if ($user_ids = array_filter($user_ids)) {
          $revision_owners = $this->entityTypeManager->getStorage('user')->loadMultiple($user_ids);
        }

    $violations = $workspace_3->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('A workspace with this ID has been deleted but data still exists for it.', $violations[0]->getMessage());

    // Running cron should delete the remaining data as well as the workspace ID     // from the "workspace.delete" state entry.     \Drupal::service('cron')->run();

    // Check that the actual node revisions were deleted as well.     $node_storage = $this->entityTypeManager->getStorage('node');
    $this->assertEmpty($node_storage->loadMultipleRevisions(array_keys($associated_revisions)));

    // 'workspace_2 'is empty now.     $associated_revisions = $workspace_association->getAssociatedRevisions($workspace_2->id(), 'node', [$workspace_2_node_1->id()]);
    $this->assertCount(0, $associated_revisions);
    $tracked_entities = $workspace_association->getTrackedEntities($workspace_2->id());
    $this->assertCount(0, $tracked_entities);

    $workspace_deleted = \Drupal::state()->get('workspace.deleted');
    $this->assertCount(0, $workspace_deleted);

    // Check that the deleted workspace is no longer active.


    // Get a list of revision IDs for entities that have a revision set for the     // current active workspace. If an entity has multiple revisions set for a     // workspace, only the one with the highest ID is returned.     if ($tracked_entities = $this->workspaceAssociation->getTrackedEntities($this->workspaceManager->getActiveWorkspace()->id()$entity_type_id$ids)) {
      /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
      $storage = $this->entityTypeManager->getStorage($entity_type_id);

      // Swap out every entity which has a revision set for the current active       // workspace.       foreach ($storage->loadMultipleRevisions(array_keys($tracked_entities[$entity_type_id])) as $revision) {
        $entities[$revision->id()] = $revision;
      }
    }

    return $entities;
  }

  /** * Acts on an entity before it is created or updated. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity being saved. * * @see hook_entity_presave() */
if ($event->isPublishingStopped()) {
      throw new WorkspacePublishException((string) $event->getPublishingStoppedReason());
    }

    try {
      $transaction = $this->database->startTransaction();
      // @todo Handle the publishing of a workspace with a batch operation in       // https://www.drupal.org/node/2958752.       $this->workspaceManager->executeOutsideWorkspace(function D) use ($tracked_entities) {
        foreach ($tracked_entities as $entity_type_id => $revision_difference) {
          $entity_revisions = $this->entityTypeManager->getStorage($entity_type_id)
            ->loadMultipleRevisions(array_keys($revision_difference));
          $default_revisions = $this->entityTypeManager->getStorage($entity_type_id)
            ->loadMultiple(array_values($revision_difference));

          /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
          foreach ($entity_revisions as $entity) {
            // When pushing workspace-specific revisions to the default             // workspace (Live), we simply need to mark them as default             // revisions.             $entity->setSyncing(TRUE);
            $entity->isDefaultRevision(TRUE);

            
$container->get('date.formatter'),
      $container->get('redirect.destination'),
      $entity_type_manager
    );
  }

  /** * {@inheritdoc} */
  public function load() {
    $revision_ids = $this->getEntityRevisionIds();
    return $this->storage->loadMultipleRevisions($revision_ids);
  }

  /** * Loads entity revision IDs using a pager sorted by the entity revision ID. * * @return array * An array of entity revision IDs. */
  protected function getEntityRevisionIds() {
    $query = $this->entityTypeManager->getStorage('content_moderation_state')->getAggregateQuery()
      ->accessCheck(TRUE)
      
throw new \InvalidArgumentException('The contents of a workspace can only be merged into its parent workspace.');
    }

    if ($this->checkConflictsOnTarget()) {
      throw new WorkspaceConflictException();
    }

    try {
      $transaction = $this->database->startTransaction();
      foreach ($this->getDifferringRevisionIdsOnSource() as $entity_type_id => $revision_difference) {
        $revisions_on_source = $this->entityTypeManager->getStorage($entity_type_id)
          ->loadMultipleRevisions(array_keys($revision_difference));

        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
        foreach ($revisions_on_source as $revision) {
          // Track all the differing revisions from the source workspace in           // the context of the target workspace. This will automatically           // update all the descendants of the target workspace as well.           $this->workspaceAssociation->trackEntity($revision$this->targetWorkspace);
        }

        // Since we're not saving entity objects, we need to invalidate the list         // cache tags manually.
7 => 4,
      ],
    ];
    $this->assertEquals($expected$workspace_publisher->getDifferringRevisionIdsOnSource());

    $this->workspaces['stage']->publish();
    $this->assertWorkspaceStatus($test_scenarios['push_stage_to_live'], 'node');
    $this->assertWorkspaceAssociation($expected_workspace_association['push_stage_to_live'], 'node');

    // Check that all the revisions that were published to 'Live' were also     // marked as default revisions in their revision metadata field.     $published_revisions = $this->entityTypeManager->getStorage('node')->loadMultipleRevisions(array_keys($expected['node']));
    foreach ($published_revisions as $published_revision) {
      $this->assertTrue($published_revision->wasDefaultRevision());
    }

    // Check that there are no more revisions to push.     $this->assertEmpty($workspace_publisher->getDifferringRevisionIdsOnSource());
  }

  /** * Tests the workspace association data integrity for entity CRUD operations. * * @covers ::workspaces_entity_presave * @covers ::workspaces_entity_insert * @covers ::workspaces_entity_delete * @covers ::workspaces_entity_revision_delete */
$this->assertEquals("dedicated table - {$translation->id()} - delta 1 - value 2 - ro", $translation->test_multiple_properties_multiple_values[1]->value2);
      }
    }

    if ($revisionable) {
      $revisions_result = $this->entityTypeManager
        ->getStorage($this->entityTypeId)
        ->getQuery()
        ->accessCheck(FALSE)
        ->allRevisions()
        ->execute();
      $revisions = $this->entityTypeManager->getStorage($this->entityTypeId)->loadMultipleRevisions(array_keys($revisions_result));
      $this->assertCount(6, $revisions);

      foreach ($revisions as $revision) {
        /** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
        $revision_label = $revision->isDefaultRevision() ? NULL : ' - rev2';
        $this->assertEquals("test entity - {$revision->id()} - en{$revision_label}", $revision->label());
        $this->assertEquals("bundle field - {$revision->id()} - en{$revision_label}", $revision->new_bundle_field->value);
        $this->assertEquals("shared table - {$revision->id()} - value 1 - en{$revision_label}", $revision->test_multiple_properties->value1);
        $this->assertEquals("shared table - {$revision->id()} - value 2 - en{$revision_label}", $revision->test_multiple_properties->value2);
        $this->assertEquals("dedicated table - {$revision->id()} - delta 0 - value 1 - en{$revision_label}", $revision->test_multiple_properties_multiple_values[0]->value1);
        $this->assertEquals("dedicated table - {$revision->id()} - delta 0 - value 2 - en{$revision_label}", $revision->test_multiple_properties_multiple_values[0]->value2);
        
    $storage = $this->container->get('entity_type.manager')->getStorage('entity_test_rev');

    $ids = [];
    $entity = $storage->create(['name' => 'test_rev']);
    $entity->save();
    $ids[] = $entity->getRevisionId();

    $revision = $storage->createRevision($entity, TRUE);
    $revision->save();
    $ids[] = $revision->getRevisionId();

    $entities = $storage->loadMultipleRevisions($ids);
    $this->assertEquals($idsarray_keys($entities));

    // Reverse the order and load again.     $ids = array_reverse($ids);
    $entities = $storage->loadMultipleRevisions($ids);
    $this->assertEquals($idsarray_keys($entities));

    // Reverse the order again, reset the cache and load again.     $ids = array_reverse($ids);
    $storage->resetCache();
    $entities = $storage->loadMultipleRevisions($ids);
    
$translation->set('translatable_test_field', $values['de'][$i]['translatable_test_field']);
        $translation->save();
      }

      // Check that the fields and properties contain new content.       // Verify that the revision ID changed.       $this->assertGreaterThan($legacy_revision_id$entity->revision_id->value);
      $this->assertNotEquals($legacy_name$entity->name->value, new FormattableMarkup('%entity_type: Name changed.', ['%entity_type' => $entity_type]));
      $this->assertNotEquals($legacy_text$entity->translatable_test_field->value, new FormattableMarkup('%entity_type: Text changed.', ['%entity_type' => $entity_type]));
    }

    $revisions = $storage->loadMultipleRevisions($revision_ids);
    for ($i = 0; $i < $revision_count$i++) {
      // Load specific revision.       $entity_revision = $revisions[$revision_ids[$i]];

      // Check if properties and fields contain the revision specific content.       $this->assertEquals($revision_ids[$i]$entity_revision->revision_id->value, new FormattableMarkup('%entity_type: Revision ID matches.', ['%entity_type' => $entity_type]));
      $this->assertEquals($values['en'][$i]['name']$entity_revision->name->value, new FormattableMarkup('%entity_type: Name matches.', ['%entity_type' => $entity_type]));
      $this->assertEquals($values['en'][$i]['translatable_test_field'][0]$entity_revision->translatable_test_field[0]->value, new FormattableMarkup('%entity_type: Text matches.', ['%entity_type' => $entity_type]));
      $this->assertEquals($values['en'][$i]['translatable_test_field'][1]$entity_revision->translatable_test_field[1]->value, new FormattableMarkup('%entity_type: Text matches.', ['%entity_type' => $entity_type]));

      // Check the translated values.

  protected function loadEntitiesWithAccess(EntityStorageInterface $storage, array $ids$load_latest_revisions) {
    $output = [];
    if ($load_latest_revisions) {
      assert($storage instanceof RevisionableStorageInterface);
      $entities = $storage->loadMultipleRevisions(array_keys($ids));
    }
    else {
      $entities = $storage->loadMultiple($ids);
    }
    foreach ($entities as $entity) {
      $output[$entity->id()] = $this->entityAccessChecker->getAccessCheckedResourceObject($entity);
    }
    return array_values($output);
  }

  /** * Checks if the given entity exists. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which to test existence. * * @return bool * Whether the entity already has been created. */
/** * {@inheritdoc} */
  protected function loadLinks($menu_name, MenuTreeParameters $parameters) {
    $links = parent::loadLinks($menu_name$parameters);

    // Replace the menu link plugin definitions with workspace-specific ones.     if ($active_workspace = $this->workspaceManager->getActiveWorkspace()) {
      $tracked_revisions = $this->workspaceAssociation->getTrackedEntities($active_workspace->id());
      if (isset($tracked_revisions['menu_link_content'])) {
        /** @var \Drupal\menu_link_content\MenuLinkContentInterface[] $workspace_revisions */
        $workspace_revisions = $this->entityTypeManager->getStorage('menu_link_content')->loadMultipleRevisions(array_keys($tracked_revisions['menu_link_content']));
        foreach ($workspace_revisions as $workspace_revision) {
          if (isset($links[$workspace_revision->getPluginId()])) {
            $pending_plugin_definition = $workspace_revision->getPluginDefinition();
            $links[$workspace_revision->getPluginId()] = [
              'title' => serialize($pending_plugin_definition['title']),
              'description' => serialize($pending_plugin_definition['description']),
              'enabled' => (string) $pending_plugin_definition['enabled'],
              'url' => $pending_plugin_definition['url'],
              'route_name' => $pending_plugin_definition['route_name'],
              'route_parameters' => serialize($pending_plugin_definition['route_parameters']),
              'options' => serialize($pending_plugin_definition['options']),
            ]
$ids = array_values($result);
      }
    }

    return $entities;
  }

  /** * {@inheritdoc} */
  public function loadRevision($revision_id) {
    $revisions = $this->loadMultipleRevisions([$revision_id]);

    return $revisions[$revision_id] ?? NULL;
  }

  /** * {@inheritdoc} */
  public function loadMultipleRevisions(array $revision_ids) {
    $revisions = $this->doLoadMultipleRevisionsFieldItems($revision_ids);

    // The hooks are executed with an array of entities keyed by the entity ID.
$result = $entityStorage->getQuery()
      ->accessCheck(FALSE)
      ->allRevisions()
      ->condition($entityType->getKey('id')$entity->id())
      ->sort($entityType->getKey('revision'), 'DESC')
      ->execute();

    $currentLangcode = $this->languageManager
      ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
      ->getId();
    foreach ($entityStorage->loadMultipleRevisions(array_keys($result)) as $revision) {
      // Only show revisions that are affected by the language that is being       // displayed.       if (!$translatable || ($revision->hasTranslation($currentLangcode) && $revision->getTranslation($currentLangcode)->isRevisionTranslationAffected())) {
        yield $revision;
      }
    }
  }

  /** * Generates an overview table of revisions of an entity. * * @param \Drupal\Core\Entity\RevisionableInterface $entity * A revisionable entity. * * @return array * A render array. */
Home | Imprint | This part of the site doesn't use cookies.