You are here

public function QuickTransitionForm::discardDraft in Moderation Sidebar 8

Form submission handler to discard the current draft.

Technically, there is no way to delete Drafts, but as a Draft is really just the current, non-live revision, we can simply re-save the default revision to get the same end-result.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

File

src/Form/QuickTransitionForm.php, line 175

Class

QuickTransitionForm
The QuickTransitionForm provides quick buttons for changing transitions.

Namespace

Drupal\moderation_sidebar\Form

Code

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

  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $entity = $form_state
    ->get('entity');
  $storage = $this->entityTypeManager
    ->getStorage($entity
    ->getEntityTypeId());
  $default_revision_id = $this->moderationInformation
    ->getDefaultRevisionId($entity
    ->getEntityTypeId(), $entity
    ->id());
  $default_revision = $storage
    ->loadRevision($default_revision_id);
  if ($form_state
    ->getValue('revision_log_toggle')) {
    $revision_log = $form_state
      ->getValue('revision_log');
  }
  else {
    $revision_log = $this
      ->t('Used the Moderation Sidebar to discard the current draft');
  }
  $revision = $this
    ->prepareNewRevision($default_revision, $revision_log);
  $revision
    ->save();
  $this
    ->messenger()
    ->addMessage($this
    ->t('The draft has been discarded successfully.'));

  // There is no generic entity route to view a single revision, but we know
  // that the node module support this.
  if ($entity
    ->getEntityTypeId() == 'node') {
    $url = Url::fromRoute('entity.node.revision', [
      'node' => $entity
        ->id(),
      'node_revision' => $entity
        ->getRevisionId(),
    ])
      ->toString();
    $this
      ->messenger()
      ->addMessage($this
      ->t('<a href="@url">You can view an archive of the draft by clicking here.</a>', [
      '@url' => $url,
    ]));
  }
  $form_state
    ->setRedirectUrl($entity
    ->toLink()
    ->getUrl());
}