getRevisionId example



  /** * Tests title is from revision in context. */
  public function testRevisionTitle(): void {
    $entity = EntityTestRev::create();
    $entity
      ->setName('first revision, view revision')
      ->setNewRevision();
    $entity->save();
    $revisionId = $entity->getRevisionId();

    // A default revision is created to ensure it is not pulled from the     // non-revision entity parameter.     $entity
      ->setName('second revision, view revision')
      ->setNewRevision();
    $entity->isDefaultRevision(TRUE);
    $entity->save();

    // Reload the object.     $revision = \Drupal::entityTypeManager()->getStorage('entity_test_rev')->loadRevision($revisionId);
    
// Create a third revision.     $entity = $this->reloadEntity($entity);
    $entity->setNewRevision(TRUE);
    $entity->save();
    $revision_3 = clone $entity;

    // Delete the second revision and check that its content moderation state is     // removed as well, while the content moderation states for revisions 1 and     // 3 are kept in place.     $entity_storage = $this->entityTypeManager->getStorage($entity_type_id);
    $entity_storage->deleteRevision($revision_2->getRevisionId());

    $this->assertNotNull(ContentModerationState::loadFromModeratedEntity($revision_1));
    $this->assertNull(ContentModerationState::loadFromModeratedEntity($revision_2));
    $this->assertNotNull(ContentModerationState::loadFromModeratedEntity($revision_3));
  }

  /** * Tests removal of content moderation state pending entity revisions. * * @dataProvider basicModerationTestCases */
  
// Get current target file entities and file IDs.       $files = $this->referencedEntities();
      $ids = [];

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

      // On new revisions, all files are considered to be a new usage and no       // deletion of previous file usages are necessary.       if (!empty($entity->original) && $entity->getRevisionId() != $entity->original->getRevisionId()) {
        foreach ($files as $file) {
          \Drupal::service('file.usage')->add($file, 'file', $entity->getEntityTypeId()$entity->id());
        }
        return;
      }

      // Get the file IDs attached to the field before this update.       $field_name = $this->getFieldDefinition()->getName();
      $original_ids = [];
      $langcode = $this->getLangcode();
      $original = $entity->original;
      
// Edit the same block, creating a new revision.     $this->drupalGet("admin/content/block/" . $block->id());
    $edit = [];
    $edit['info[0][value]'] = $this->randomMachineName(8);
    $edit[$body_key] = $this->randomMachineName(16);
    $edit['revision'] = TRUE;
    $this->submitForm($edit, 'Save');

    // Ensure that the block revision has been created.     \Drupal::entityTypeManager()->getStorage('block_content')->resetCache([$block->id()]);
    $revised_block = BlockContent::load($block->id());
    $this->assertNotSame($block->getRevisionId()$revised_block->getRevisionId(), 'A new revision has been created.');

    // Test deleting the block.     $this->drupalGet("admin/content/block/" . $revised_block->id());
    $this->clickLink('Delete');
    $this->assertSession()->pageTextContains('Are you sure you want to delete the content block ' . $revised_block->label() . '?');

    // Test breadcrumb.     $trail = [
      '' => 'Home',
      'admin/content/block' => 'Content blocks',
      'admin/content/block/' . $revised_block->id() => $revised_block->label(),
    ];
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->assertSession()->checkboxChecked('edit-revision');

    // Uncheck the create new revision checkbox and save the node.     $edit = ['revision' => FALSE];
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->submitForm($edit, 'Save');

    // Load the node again and check the revision is the same as before.     $node_storage->resetCache([$node->id()]);
    $node_revision = $node_storage->load($node->id(), TRUE);
    $this->assertEquals($node->getRevisionId()$node_revision->getRevisionId(), "After an existing node is saved with 'Create new revision' unchecked, a new revision is not created.");

    // Verify the checkbox is checked on the node edit form.     $this->drupalGet('node/' . $node->id() . '/edit');
    $this->assertSession()->checkboxChecked('edit-revision');

    // Submit the form without changing the checkbox.     $edit = [];
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->submitForm($edit, 'Save');

    // Load the node again and check the revision is different from before.
    $storage->resetCache();
    $ids = array_reverse($ids);
    $entities = $storage->loadMultiple($ids);
    $this->assertEquals($idsarray_keys($entities));

    // Entity revision load.     $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);
    

  protected function getExpectedGetRelationshipDocument($relationship_field_name, EntityInterface $entity = NULL) {
    $entity = $entity ?: $this->entity;
    $entity_type_id = $entity->getEntityTypeId();
    $bundle = $entity->bundle();
    $id = $entity->uuid();
    $self_link = Url::fromUri("base:/jsonapi/$entity_type_id/$bundle/$id/relationships/$relationship_field_name")->setAbsolute();
    $related_link = Url::fromUri("base:/jsonapi/$entity_type_id/$bundle/$id/$relationship_field_name")->setAbsolute();
    if (static::$resourceTypeIsVersionable) {
      assert($entity instanceof RevisionableInterface);
      $version_query = ['resourceVersion' => 'id:' . $entity->getRevisionId()];
      $related_link->setOption('query', $version_query);
    }
    $data = $this->getExpectedGetRelationshipDocumentData($relationship_field_name$entity);
    return [
      'data' => $data,
      'jsonapi' => static::$jsonApiMember,
      'links' => [
        'self' => ['href' => $self_link->toString(TRUE)->getGeneratedUrl()],
        'related' => ['href' => $related_link->toString(TRUE)->getGeneratedUrl()],
      ],
    ];
  }
// Place a block to determine which revision is provided as context     // to blocks.     $this->drupalPlaceBlock('node_block_test_context', [
      'context_mapping' => ['node' => '@node.node_route_context:node'],
    ]);

    $this->drupalLogin($this->adminUser);

    $this->drupalGet('node/' . $node1->id());
    $this->assertSession()->pageTextContains($label);
    $this->assertSession()->pageTextContains('Displaying node #' . $node1->id() . ', revision #' . $node1->getRevisionId() . ': Node revision 2 title');

    // Assert that the preview page displays the block as well.     $this->drupalGet('node/' . $node1->id() . '/edit');
    $this->submitForm([], 'Preview');
    $this->assertSession()->pageTextContains($label);
    // The previewed node object has no revision ID.     $this->assertSession()->pageTextContains('Displaying node #' . $node1->id() . ', revision #: Node revision 2 title');

    // Assert that the revision page for both revisions displays the block.     $this->drupalGet(Url::fromRoute('entity.node.revision', ['node' => $node1->id(), 'node_revision' => $node1_revision_1->getRevisionId()]));
    $this->assertSession()->pageTextContains($label);
    
/** \Symfony\Component\Validator\ConstraintViolationInterface */
      $messages[] = $violation->getMessage();
    }
    $this->assertEquals($valid, !$violations->count()$this->formatMessage('Validation does not match the expected result: %s', implode(', ', $messages)));

    if ($valid) {
      $entity->save();

      // Reload the current revision translation and the default revision to       // make sure data was stored correctly.       /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
      $entity = $this->storage->loadRevision($entity->getRevisionId());
      $entity = $entity->getTranslation($active_langcode);
      /** @var \Drupal\Core\Entity\ContentEntityInterface $default_entity */
      $default_entity = $this->storage->loadUnchanged($entity->id());

      // Verify that the values for the current revision translation match the       // expected ones, while for the other translations they match the default       // revision. We also need to verify that only the current revision       // translation was marked as affected.       foreach ($entity->getTranslationLanguages() as $langcode => $language) {
        $translation = $entity->getTranslation($langcode);
        $rta_expected = $langcode == $active_langcode || ($untranslatable_update && $all_translations_affected);
        
    // allowed.     $pending_child1_title = $this->randomMachineName(8);
    $child1_pending_revision = $storage->createRevision($child1, FALSE);
    $child1_pending_revision->set('title', $pending_child1_title);
    $child1_pending_revision->set('link', [['uri' => 'internal:/#test']]);

    $violations = $child1_pending_revision->validate();
    $this->assertEmpty($violations);
    $child1_pending_revision->save();

    $storage->resetCache();
    $child1_pending_revision = $storage->loadRevision($child1_pending_revision->getRevisionId());
    $this->assertFalse($child1_pending_revision->isDefaultRevision());
    $this->assertEquals($pending_child1_title$child1_pending_revision->getTitle());
    $this->assertEquals('/#test', $child1_pending_revision->getUrlObject()->toString());

    // Check that saving a pending revision does not affect the menu tree.     $menu_tree = \Drupal::menuTree()->load('menu_test', new MenuTreeParameters());
    $parent_link = reset($menu_tree);
    $this->assertEquals($default_root_1_title$parent_link->link->getTitle());
    $this->assertEquals('/#root_1', $parent_link->link->getUrlObject()->toString());

    $child1_link = reset($parent_link->subtree);
    

  protected function getExpectedNormalizedEntity() {
    return array_merge(parent::getExpectedNormalizedEntity()[
      'moderation_state' => [
        [
          'value' => 'published',
        ],
      ],
      'vid' => [
        [
          'value' => (int) $this->entity->getRevisionId(),
        ],
      ],
    ]);
  }

}
public function getOriginalTermId(NodeInterface $node) {
    return $this->database->queryRange("SELECT [f].[tid] FROM {forum} [f] INNER JOIN {node} [n] ON [f].[vid] = [n].[vid] WHERE [n].[nid] = :nid ORDER BY [f].[vid] DESC", 0, 1, [':nid' => $node->id()])->fetchField();
  }

  /** * {@inheritdoc} */
  public function create(NodeInterface $node) {
    $this->database->insert('forum')
      ->fields([
        'tid' => $node->forum_tid,
        'vid' => $node->getRevisionId(),
        'nid' => $node->id(),
      ])
      ->execute();
  }

  /** * {@inheritdoc} */
  public function read(array $vids) {
    return $this->database->select('forum', 'f')
      ->fields('f', ['nid', 'tid'])
      
$form['actions']['submit']['#submit'] = [
      '::submitForm',
      '::save',
    ];
    return $form;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $revisionId = $this->revision->getRevisionId();
    $revisionLabel = $this->revision->label();
    $bundleLabel = $this->getBundleLabel($this->revision);
    if ($this->revision instanceof RevisionLogInterface) {
      $originalRevisionTimestamp = $this->revision->getRevisionCreationTime();
    }

    $this->revision = $this->prepareRevision($this->revision, $form_state);

    if (isset($originalRevisionTimestamp)) {
      $date = $this->dateFormatter->format($originalRevisionTimestamp);
      $this->messenger->addMessage($this->t('@type %title has been reverted to the revision from %revision-date.', [
        

  public function testNewRevisionAfterTranslation() {
    $user = $this->createUser();

    // Create a test entity.     $entity = EntityTestMulRev::create([
      'name' => $this->randomString(),
      'user_id' => $user->id(),
      'language' => 'en',
    ]);
    $entity->save();
    $old_rev_id = $entity->getRevisionId();

    $translation = $entity->addTranslation('de');
    $translation->setNewRevision();
    $translation->save();

    // Verify that the saved translation for the new translation has a newer     // revision ID.     $this->assertGreaterThan($old_rev_id$translation->getRevisionId());
    // Verify that the entity from the storage has a newer revision ID.     $this->assertGreaterThan($old_rev_id$this->reloadEntity($entity)->getRevisionId());
  }

  
$this->submitForm($edit, 'Save');

    // Check that the new revision has the expected values.     $storage->resetCache([$id]);
    $entity = $storage->load($id);
    $this->assertEquals(99, $entity->{$field_name_no_access}->value, 'New revision has the expected value for the field with no edit access.');
    $this->assertEquals(2, $entity->{$field_name}->value, 'New revision has the expected value for the field with edit access.');

    // Check that the revision is also saved in the revisions table.     $entity = $this->container->get('entity_type.manager')
      ->getStorage($entity_type)
      ->loadRevision($entity->getRevisionId());
    $this->assertEquals(99, $entity->{$field_name_no_access}->value, 'New revision has the expected value for the field with no edit access.');
    $this->assertEquals(2, $entity->{$field_name}->value, 'New revision has the expected value for the field with edit access.');
  }

  /** * Tests hiding a field in a form. */
  public function testHiddenField() {
    $entity_type = 'entity_test_rev';
    $field_storage = $this->fieldStorageSingle;
    $field_storage['entity_type'] = $entity_type;
    
Home | Imprint | This part of the site doesn't use cookies.