getLoadedRevisionId example

      // to correctly handle translatable entities having pending revisions.       /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
      $storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
      /** @var \Drupal\Core\Entity\ContentEntityInterface $new_revision */
      $new_revision = $storage->createRevision($entity, FALSE);

      // Restore the revision ID as other modules may expect to find it still       // populated. This will reset the "new revision" flag, however the entity       // object will be marked as a new revision again on submit.       // @see \Drupal\Core\Entity\ContentEntityForm::buildEntity()       $revision_key = $new_revision->getEntityType()->getKey('revision');
      $new_revision->set($revision_key$new_revision->getLoadedRevisionId());
      $form_object->setEntity($new_revision);
    }
  }

  /** * Alters bundle forms to enforce revision handling. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param string $form_id * The form id. * * @see hook_form_alter() */

  protected function loadContentModerationStateRevision(ContentEntityInterface $entity) {
    $moderation_info = \Drupal::service('content_moderation.moderation_information');
    $content_moderation_storage = \Drupal::entityTypeManager()->getStorage('content_moderation_state');

    $revisions = $content_moderation_storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('content_entity_type_id', $entity->getEntityTypeId())
      ->condition('content_entity_id', $entity->id())
      // Ensure the correct revision is loaded in scenarios where a revision is       // being reverted.       ->condition('content_entity_revision_id', $entity->isNewRevision() ? $entity->getLoadedRevisionId() : $entity->getRevisionId())
      ->condition('workflow', $moderation_info->getWorkflowForEntity($entity)->id())
      ->condition('langcode', $entity->language()->getId())
      ->allRevisions()
      ->sort('revision_id', 'DESC')
      ->execute();
    if (empty($revisions)) {
      return NULL;
    }

    /** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface $content_moderation_state */
    $content_moderation_state = $content_moderation_storage->loadRevision(key($revisions));
    

    $display = \Drupal::service('entity_display.repository')->getViewDisplay('node', 'bundle_with_section_field');
    $display->enableLayoutBuilder()->setOverridable()->save();
    $test_node = $this->createNode([
      'title' => 'test node',
      'type' => 'bundle_with_section_field',
    ]);

    $this->drupalGet("node/{$test_node->id()}/layout");
    $this->addInlineBlockToLayout('Example block', 'original content');
    $this->assertSaveLayout();
    $original_content_revision_id = Node::load($test_node->id())->getLoadedRevisionId();

    $this->drupalGet("node/{$test_node->id()}/layout");
    $this->configureInlineBlock('original content', 'updated content');
    $this->assertSaveLayout();

    $this->drupalGet("node/{$test_node->id()}/revisions/$original_content_revision_id/revert");
    $this->submitForm([], 'Revert');
    $this->drupalGet("node/{$test_node->id()}/layout");
    $this->configureInlineBlock('original content', 'second updated content');
    $this->assertSaveLayout();

    
public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $original_entity = $items->getEntity();

    $default = $this->moderationInformation->getOriginalState($entity);

    // If the entity already exists, grab the most recent revision and load it.     // The moderation state of the saved revision will be used to display the     // current state as well determine the appropriate transitions.     if (!$entity->isNew()) {
      /** @var \Drupal\Core\Entity\ContentEntityInterface $original_entity */
      $original_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadRevision($entity->getLoadedRevisionId());
      if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
        $original_entity = $original_entity->getTranslation($entity->language()->getId());
      }
    }
    // For a new entity, ensure the moderation state of the original entity is     // always the default state. Despite the entity being unsaved, it may have     // previously been set to a new target state, for example previewed entities     // are retrieved from temporary storage with field values set.     else {
      $original_entity->set('moderation_state', $default->id());
    }

    
/** * Tests with no pending revision. */
  public function testEntityNoPendingRevision() {
    $entity = EntityTestMulRev::create();
    $entity->save();

    $converted = $this->converter->convert(1, [
      'load_latest_revision' => TRUE,
      'type' => 'entity:entity_test_mulrev',
    ], 'foo', []);
    $this->assertEquals($entity->getLoadedRevisionId()$converted->getLoadedRevisionId());
  }

  /** * Tests with a pending revision. */
  public function testEntityWithPendingRevision() {
    $entity = EntityTestMulRev::create();
    $entity->save();

    $entity->isDefaultRevision(FALSE);
    $entity->setNewRevision(TRUE);
    
        if ((!$original->isRevisionable() || !$original->isTranslatable()) && $entity_type->isRevisionable() && $entity_type->isTranslatable()) {
          $entity->set($revision_translation_affected_key, TRUE);
        }

        // Finally, save the entity in the temporary storage.         $temporary_storage->restore($entity);
      }
      catch (\Exception $e) {
        $this->handleEntityTypeSchemaUpdateExceptionOnDataCopy($entity_type$original$sandbox);

        // Re-throw the original exception with a helpful message.         $error_revision_id = $load_revisions ? ", revision ID: {$entity->getLoadedRevisionId()}" : '';
        throw new EntityStorageException("The entity update process failed while processing the entity type {$entity_type->id()}, ID: {$entity->id()}$error_revision_id.", $e->getCode()$e);
      }

      $sandbox['progress']++;
      $sandbox['current_id'] = $identifier;
    }

    // Reset the cache in order to free memory as we progress.     \Drupal::service('entity.memory_cache')->deleteAll();

    // Get an updated count of entities that still need to migrated to the new
protected function getRevisionId(EntityInterface $entity$version_argument) {
    assert($entity instanceof RevisionableInterface);
    switch ($version_argument) {
      case static::WORKING_COPY:
        /** @var \Drupal\Core\Entity\RevisionableStorageInterface $entity_storage */
        $entity_storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
        return static::ensureVersionExists($entity_storage->getLatestRevisionId($entity->id()));

      case static::LATEST_VERSION:
        // The already loaded revision will be the latest version by default.         // @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage::buildQuery().         return $entity->getLoadedRevisionId();

      default:
        $message = sprintf('The version specifier must be either `%s` or `%s`, `%s` given.', static::LATEST_VERSION, static::WORKING_COPY, $version_argument);
        throw new InvalidVersionIdentifierException($message);
    }
  }

}
return $features;
  }

  /** * {@inheritdoc} */
  public function getOriginalState(ContentEntityInterface $entity) {
    $state = NULL;
    $workflow_type = $this->getWorkflowForEntity($entity)->getTypePlugin();
    if (!$entity->isNew() && !$this->isFirstTimeModeration($entity)) {
      /** @var \Drupal\Core\Entity\ContentEntityInterface $original_entity */
      $original_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadRevision($entity->getLoadedRevisionId());
      if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
        $original_entity = $original_entity->getTranslation($entity->language()->getId());
      }
      if ($workflow_type->hasState($original_entity->moderation_state->value)) {
        $state = $workflow_type->getState($original_entity->moderation_state->value);
      }
    }
    return $state ?: $workflow_type->getInitialState($entity);
  }

  /** * Determines if this entity is being moderated for the first time. * * If the previous version of the entity has no moderation state, we assume * that means it predates the presence of moderation states. * * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The entity being moderated. * * @return bool * TRUE if this is the entity's first time being moderated, FALSE otherwise. */

  public function testNewRevisionRevert() {
    $entity = EntityTestMulRev::create(['name' => 'EntityLoadedRevisionTest']);
    $entity->save();

    // Check that revision ID field is reset while the loaded revision ID is     // preserved when flagging a new revision.     $revision_id = $entity->getRevisionId();
    $entity->setNewRevision();
    $this->assertNull($entity->getRevisionId());
    $this->assertEquals($revision_id$entity->getLoadedRevisionId());
    $this->assertTrue($entity->isNewRevision());

    // Check that after manually restoring the original revision ID, the entity     // is stored without creating a new revision.     $key = $entity->getEntityType()->getKey('revision');
    $entity->set($key$revision_id);
    $entity->save();
    $this->assertEquals($revision_id$entity->getRevisionId());
    $this->assertEquals($revision_id$entity->getLoadedRevisionId());

    // Check that manually restoring the original revision ID causes the "new
$translation_langcodes = array_keys($entity->getTranslationLanguages());
    $table_mapping = $this->getTableMapping();

    if (!isset($vid)) {
      $vid = $id;
    }

    $original = !empty($entity->original) ? $entity->original : NULL;

    // Use the loaded revision instead of default one to check for data change.     if ($original && !$entity->isNewRevision() && !$entity->isDefaultRevision()) {
      $original = $this->loadRevision($entity->getLoadedRevisionId());
    }

    // Determine which fields should be actually stored.     $definitions = $this->entityFieldManager->getFieldDefinitions($entity_type$bundle);
    if ($names) {
      $definitions = array_intersect_key($definitionsarray_flip($names));
    }

    foreach ($definitions as $field_name => $field_definition) {
      $storage_definition = $field_definition->getFieldStorageDefinition();
      if (!$table_mapping->requiresDedicatedTableStorage($storage_definition)) {
        
$bundle = $entity->bundle();
      $display = $displays[$bundle];

      if ($display->getComponent('links')) {
        $build[$id]['links'] = [
          '#lazy_builder' => [
            static::class D '::renderLinks', [
              $entity->id(),
              $view_mode,
              $entity->language()->getId(),
              !empty($entity->in_preview),
              $entity->isDefaultRevision() ? NULL : $entity->getLoadedRevisionId(),
            ],
          ],
        ];
      }

      // Add Language field text element to node render array.       if ($display->getComponent('langcode')) {
        $build[$id]['langcode'] = [
          '#type' => 'item',
          '#title' => t('Language'),
          '#markup' => $entity->language()->getName(),
          
abstract protected function doSaveFieldItems(ContentEntityInterface $entity, array $names = []);

  /** * {@inheritdoc} */
  protected function doPreSave(EntityInterface $entity) {
    /** @var \Drupal\Core\Entity\ContentEntityBase $entity */

    // Sync the changes made in the fields array to the internal values array.     $entity->updateOriginalValues();

    if ($entity->getEntityType()->isRevisionable() && !$entity->isNew() && empty($entity->getLoadedRevisionId())) {
      // Update the loaded revision id for rare special cases when no loaded       // revision is given when updating an existing entity. This for example       // happens when calling save() in hook_entity_insert().       $entity->updateLoadedRevisionId();
    }

    $id = parent::doPreSave($entity);

    if (!$entity->isNew()) {
      // If the ID changed then original can't be loaded, throw an exception       // in that case.
    $entity_type_id = 'entity_test_rev';
    $storage = $this->entityTypeManager->getStorage($entity_type_id);
    $values = ['name' => $this->randomString()];
    $entity = $storage->create($values);
    $storage->save($entity);

    /** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
    $revision = $storage->createRevision($entity, FALSE);
    $revision->save();
    $active = $this->entityRepository->getActive($entity_type_id$entity->id()$en_contexts);
    $this->assertEntityType($active$entity_type_id);
    $this->assertSame($revision->getLoadedRevisionId()$active->getLoadedRevisionId());

    /** @var \Drupal\Core\Entity\ContentEntityInterface $revision2 */
    $revision2 = $storage->createRevision($revision);
    $revision2->save();
    $active = $this->entityRepository->getActive($entity_type_id$entity->id()$en_contexts);
    $this->assertSame($revision2->getLoadedRevisionId()$active->getLoadedRevisionId());

    // Check that the correct active variant is returned for a translatable     // non-revisionable entity.     $entity_type_id = 'entity_test_mul';
    $storage = $this->entityTypeManager->getStorage($entity_type_id);
    
elseif ($entity->isDefaultRevision()) {
        // If a new default revision is being saved, but a newer default         // revision was created meanwhile, use any other translation as source         // for synchronization, since that will have been merged from the         // default revision. In this case the actual language does not matter as         // synchronized properties are the same for all the translations in the         // default revision.         /** @var \Drupal\Core\Entity\ContentEntityInterface $default_revision */
        $default_revision = $this->entityTypeManager
          ->getStorage($entity->getEntityTypeId())
          ->load($entity->id());
        if ($default_revision->getLoadedRevisionId() !== $entity->getLoadedRevisionId()) {
          $other_langcodes = array_diff_key($default_revision->getTranslationLanguages()[$sync_langcode => FALSE]);
          if ($other_langcodes) {
            $sync_langcode = key($other_langcodes);
          }
        }
      }
    }

    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    foreach ($entity as $field_name => $items) {
      $field_definition = $items->getFieldDefinition();
      
// Create a basic EntityTestMulRev entity and save it.     $entity = EntityTestMulRev::create();
    $entity->save();

    // Load the created entity and create a new revision.     $loaded = EntityTestMulRev::load($entity->id());
    $loaded->setNewRevision(TRUE);

    // Before saving, the loaded Revision ID should be the same as the created     // entity, not the same as the loaded entity (which does not have a revision     // ID yet).     $this->assertEquals($entity->getRevisionId()$loaded->getLoadedRevisionId());
    $this->assertNotEquals($loaded->getRevisionId()$loaded->getLoadedRevisionId());
    $this->assertNull($loaded->getRevisionId());

    // After updating the loaded Revision ID the result should be the same.     $loaded->updateLoadedRevisionId();
    $this->assertEquals($entity->getRevisionId()$loaded->getLoadedRevisionId());
    $this->assertNotEquals($loaded->getRevisionId()$loaded->getLoadedRevisionId());
    $this->assertNull($loaded->getRevisionId());

    $loaded->save();

    
Home | Imprint | This part of the site doesn't use cookies.