deleteRevision example


  public function getDescription() {
    return '';
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $entityTypeId = $this->revision->getEntityTypeId();
    $entityStorage = $this->entityTypeManager->getStorage($entityTypeId);
    $entityStorage->deleteRevision($this->revision->getRevisionId());

    $bundleLabel = $this->getBundleLabel($this->revision);
    $messengerArgs = [
      '@type' => $bundleLabel ?? $this->revision->getEntityType()->getLabel(),
      '%title' => $this->revision->label(),
    ];
    if ($this->revision instanceof RevisionLogInterface) {
      $messengerArgs['%revision-date'] = $this->dateFormatter->format($this->revision->getRevisionCreationTime());
      $this->messenger->addStatus($this->t('Revision from %revision-date of @type %title has been deleted.', $messengerArgs));
    }
    else {
      
$vids[] = $entity->getRevisionId();
    $controller = $this->container->get('entity_type.manager')->getStorage($entity->getEntityTypeId());
    $controller->resetCache();

    // Confirm each revision loads     foreach ($vids as $vid) {
      $revision = $controller->loadRevision($vid);
      $this->assertCount($cardinality$revision->{$this->fieldTestData->field_name}, "The test entity revision $vid has $cardinality values.");
    }

    // Delete revision 1, confirm the other two still load.     $controller->deleteRevision($vids[1]);
    $controller->resetCache();
    foreach ([0, 2] as $key) {
      $vid = $vids[$key];
      $revision = $controller->loadRevision($vid);
      $this->assertCount($cardinality$revision->{$this->fieldTestData->field_name}, "The test entity revision $vid has $cardinality values.");
    }

    // Confirm the current revision still loads     $controller->resetCache();
    $current = $controller->load($entity->id());
    $this->assertCount($cardinality$current->{$this->fieldTestData->field_name}, "The test entity current revision has $cardinality values.");

    

  public function entityRevisionDelete(EntityInterface $entity) {
    if ($content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity)) {
      if ($content_moderation_state->isDefaultRevision()) {
        $content_moderation_state->delete();
      }
      else {
        $this->entityTypeManager
          ->getStorage('content_moderation_state')
          ->deleteRevision($content_moderation_state->getRevisionId());
      }
    }
  }

  /** * @param \Drupal\Core\Entity\EntityInterface $translation * The entity translation being deleted. * * @see hook_entity_translation_delete() */
  public function entityTranslationDelete(EntityInterface $translation) {
    
    foreach (range(1, 3) as $count) {
      $timestamp = rand(1e8, 2e8);
      $this->createRevision($entity$user$timestamp, 'This is my log message number: ' . $count);
      $revision_ids[] = $entity->getRevisionId();
    }
    $this->assertItemsTableCount(6, $definition);

    $this->assertCount(6, $revision_ids);

    // Delete the first 3 revisions.     foreach (range(0, 2) as $key) {
      $storage->deleteRevision($revision_ids[$key]);
    }

    // We should have only data for three revisions.     $this->assertItemsTableCount(3, $definition);
  }

  /** * Tests the behavior of the "revision_default" flag. * * @covers \Drupal\Core\Entity\ContentEntityBase::wasDefaultRevision */
  
$this->assertNull($this->entityStorage->loadRevision(1));
  }

  /** * @covers ::deleteRevision * @group legacy */
  public function testDeleteRevision() {
    $this->expectDeprecation('Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage::deleteRevision() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use \Drupal\Core\Entity\RevisionableStorageInterface::deleteRevision instead. See https://www.drupal.org/node/3294237');
    $this->setUpKeyValueEntityStorage();

    $this->assertNull($this->entityStorage->deleteRevision(1));
  }

  /** * @covers ::delete * @covers ::doDelete */
  public function testDelete() {
    $entities['foo'] = $this->getMockEntity(EntityBaseTest::class[['id' => 'foo']]);
    $entities['bar'] = $this->getMockEntity(EntityBaseTest::class[['id' => 'bar']]);
    $this->setUpKeyValueEntityStorage();

    
// 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 */
  
$this->drupalGet("node/" . $node->id() . "/revisions/" . $nodes[2]->getRevisionId() . "/revert");
    $this->submitForm([], 'Revert');
    $this->assertSession()->pageTextContains("Basic page {$nodes[2]->label()} has been reverted to the revision from {$this->container->get('date.formatter')->format($old_revision_date)}.");

    // Confirm user is redirected depending on the remaining revisions,     // when a revision is deleted.     $existing_revision_ids = $node_storage->revisionIds($node);
    // Delete all revision except last 3.     $remaining_revision_ids = array_slice($existing_revision_ids, -3, 3);
    foreach ($existing_revision_ids as $revision_id) {
      if (!in_array($revision_id$remaining_revision_ids)) {
        $node_storage->deleteRevision($revision_id);
      }
    }

    // Confirm user was redirected to revisions history page.     $this->drupalGet("node/" . $node->id() . "/revisions/" . $remaining_revision_ids[0] . "/delete");
    $this->submitForm([], 'Delete');
    $this->assertSession()->pageTextContains("Revisions for {$nodes[2]->label()}");
    $this->assertSession()->pageTextNotContains($nodes[2]->body->value);

    // Confirm user was redirected to the node page.     $this->drupalGet("node/" . $node->id() . "/revisions/" . $remaining_revision_ids[1] . "/delete");
    
/** * @covers ::deleteRevision * @group legacy */
  public function testDeleteRevision() {
    $this->expectDeprecation('Drupal\Core\Config\Entity\ConfigEntityStorage::deleteRevision() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use \Drupal\Core\Entity\RevisionableStorageInterface::deleteRevision instead. See https://www.drupal.org/node/3294237');

    $this->cacheTagsInvalidator->invalidateTags(Argument::cetera())
      ->shouldNotBeCalled();

    $this->assertNull($this->entityStorage->deleteRevision(1));
  }

  /** * @covers ::delete * @covers ::doDelete */
  public function testDelete() {
    // Dependencies are tested in     // \Drupal\Tests\config\Kernel\ConfigDependencyTest.     $this->configManager
      ->getConfigEntitiesToChangeOnDependencyRemoval('config', ['the_provider.the_config_prefix.foo'], FALSE)
      
    // default translation is deleted remove all file usages within this entity.     $count = $entity->isDefaultTranslation() ? 0 : 1;
    foreach ($this->referencedEntities() as $file) {
      \Drupal::service('file.usage')->delete($file, 'file', $entity->getEntityTypeId()$entity->id()$count);
    }
  }

  /** * {@inheritdoc} */
  public function deleteRevision() {
    parent::deleteRevision();
    $entity = $this->getEntity();

    // Decrement the file usage by 1.     foreach ($this->referencedEntities() as $file) {
      \Drupal::service('file.usage')->delete($file, 'file', $entity->getEntityTypeId()$entity->id());
    }
  }

}
$path_alias->save();
        }
      }
    }
    elseif ($this->pid && !$this->alias) {
      // Otherwise, delete the old alias if the user erased it.       $path_alias = $path_alias_storage->load($this->pid);
      if ($entity->isDefaultRevision()) {
        $path_alias_storage->delete([$path_alias]);
      }
      else {
        $path_alias_storage->deleteRevision($path_alias->getRevisionID());
      }
    }
  }

  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $values['alias'] = '/' . str_replace(' ', '-', strtolower($random->sentences(3)));
    return $values;
  }
// Test hook_entity_update(): increment, by modifying the last revision:     // read the data- attributes to the body field.     foreach ($original_values as $key => $original_value) {
      $node->body[$key]->value = $original_value;
    }
    $node->save();
    foreach ($image_entities as $key => $image_entity) {
      $this->assertSame(['editor' => ['node' => [1 => '3']]]$file_usage->listUsage($image_entity), 'The image ' . $image_paths[$key] . ' has 3 usages.');
    }

    // Test editor_entity_revision_delete(): decrement, by deleting a revision.     $this->container->get('entity_type.manager')->getStorage('node')->deleteRevision($second_revision_id);
    foreach ($image_entities as $key => $image_entity) {
      $this->assertSame(['editor' => ['node' => [1 => '2']]]$file_usage->listUsage($image_entity), 'The image ' . $image_paths[$key] . ' has 2 usages.');
    }

    // Populate both the body and summary. Because this will be the same     // revision of the same node, it will record only one usage.     foreach ($original_values as $key => $original_value) {
      $node->body[$key]->value = $original_value;
      $node->body[$key]->summary = $original_value;
    }
    $node->save();
    
continue 2;
        }

        // If the workspace is tracking the entity's default revision (i.e. the         // entity was created inside that workspace), we need to delete the         // whole entity after all of its pending revisions are gone.         if (isset($initial_revision_ids[$revision_id])) {
          $associated_entity_storage->delete([$associated_entity_storage->load($initial_revision_ids[$revision_id])]);
        }
        else {
          // Delete the associated entity revision.           $associated_entity_storage->deleteRevision($revision_id);
        }
        $count++;
      }
    }

    // The purging operation above might have taken a long time, so we need to     // request a fresh list of tracked entities. If it is empty, we can go ahead     // and remove the deleted workspace ID entry from state.     $has_associated_revisions = FALSE;
    foreach (array_keys($this->getSupportedEntityTypes()) as $entity_type_id) {
      if (!empty($this->workspaceAssociation->getAssociatedRevisions($workspace_id$entity_type_id))) {
        
// Add a new published node in 'stage' and check that new workspace-specific     // revision is tracked in the workspace association data. Note that revision     // '5' has been created as an unpublished default revision in Live, so it is     // not tracked.     $this->createNode(['title' => 'stage - 4 - r6 - published', 'created' => $this->createdTimestamp++, 'status' => TRUE]);
    $expected_workspace_association = ['stage' => [6]];
    $this->assertWorkspaceAssociation($expected_workspace_association, 'node');

    // Delete revision '6' and check that the workspace association does not     // track it anymore.     $this->entityTypeManager->getStorage('node')->deleteRevision(6);
    $expected_workspace_association = ['stage' => []];
    $this->assertWorkspaceAssociation($expected_workspace_association, 'node');
  }

  /** * Tests entity tracking in workspace descendants. */
  public function testWorkspaceHierarchy() {
    $this->initializeWorkspacesModule();
    $this->createWorkspaceHierarchy();

    
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node_revision = NULL) {
    $this->revision = $node_revision;
    $form = parent::buildForm($form$form_state);

    return $form;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->nodeStorage->deleteRevision($this->revision->getRevisionId());

    $this->logger('content')->info('@type: deleted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
    $node_type = $this->nodeTypeStorage->load($this->revision->bundle())->label();
    $this->messenger()
      ->addStatus($this->t('Revision from %revision-date of @type %title has been deleted.', [
        '%revision-date' => $this->dateFormatter->format($this->revision->getRevisionCreationTime()),
        '@type' => $node_type,
        '%title' => $this->revision->label(),
      ]));
    // Set redirect to the revisions history page.     $route_name = 'entity.node.version_history';
    
Home | Imprint | This part of the site doesn't use cookies.