You are here

class QuickTransitionForm in Moderation Sidebar 8

The QuickTransitionForm provides quick buttons for changing transitions.

Hierarchy

Expanded class hierarchy of QuickTransitionForm

1 file declares its use of QuickTransitionForm
ModerationSidebarController.php in src/Controller/ModerationSidebarController.php

File

src/Form/QuickTransitionForm.php, line 20

Namespace

Drupal\moderation_sidebar\Form
View source
class QuickTransitionForm extends FormBase {

  /**
   * The moderation information service.
   *
   * @var \Drupal\content_moderation\ModerationInformationInterface
   */
  protected $moderationInformation;

  /**
   * The moderation state transition validation service.
   *
   * @var \Drupal\content_moderation\StateTransitionValidation
   */
  protected $validation;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * QuickDraftForm constructor.
   *
   * @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
   *   The moderation information service.
   * @param \Drupal\content_moderation\StateTransitionValidationInterface $validation
   *   The moderation state transition validation service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(ModerationInformationInterface $moderation_info, StateTransitionValidationInterface $validation, EntityTypeManagerInterface $entity_type_manager) {
    $this->moderationInformation = $moderation_info;
    $this->validation = $validation;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('content_moderation.moderation_information'), $container
      ->get('content_moderation.state_transition_validation'), $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'moderation_sidebar_quick_transition_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ContentEntityInterface $entity = NULL) {

    // Return an empty form if the user does not have appropriate permissions.
    if (!$entity
      ->access('update')) {
      return [];
    }

    // If this is not the default revision and is the latest translation
    // affected revision, then show a discard draft button.
    if (!$entity
      ->isDefaultRevision() && $entity
      ->isLatestTranslationAffectedRevision()) {
      $form['discard_draft'] = [
        '#type' => 'submit',
        '#id' => 'moderation-sidebar-discard-draft',
        '#value' => $this
          ->t('Discard draft'),
        '#attributes' => [
          'class' => [
            'moderation-sidebar-link',
            'button',
            'button--danger',
          ],
        ],
        '#submit' => [
          '::discardDraft',
        ],
      ];
    }

    // Persist the entity so we can access it in the submit handler.
    $form_state
      ->set('entity', $entity);
    $transitions = $this->validation
      ->getValidTransitions($entity, $this
      ->currentUser());
    $workflow = $this->moderationInformation
      ->getWorkFlowForEntity($entity);
    $disabled_transitions = $this
      ->configFactory()
      ->getEditable('moderation_sidebar.settings')
      ->get('workflows.' . $workflow
      ->id() . '_workflow.disabled_transitions');

    // Exclude self-transitions.

    /** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface $current_state */
    $current_state = $this
      ->getModerationState($entity);

    /** @var \Drupal\workflows\TransitionInterface[] $transitions */
    $transitions = array_filter($transitions, function ($transition) use ($current_state) {
      return $transition
        ->to()
        ->id() != $current_state
        ->id();
    });
    $is_transition_enabled = FALSE;
    foreach ($transitions as $transition) {

      // Exclude disabled transitions.
      if (empty($disabled_transitions[$transition
        ->id()])) {
        $form[$transition
          ->id()] = [
          '#type' => 'submit',
          '#id' => $transition
            ->id(),
          '#value' => $transition
            ->label(),
          '#attributes' => [
            'class' => [
              'moderation-sidebar-link',
              'button--primary',
            ],
          ],
        ];
        $is_transition_enabled = TRUE;
      }
    }

    // Show only, if at least one transition is enabled.
    if ($is_transition_enabled) {
      $form['revision_log_toggle'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Use custom log message'),
        '#default_value' => FALSE,
        '#attributes' => [
          'class' => [
            'moderation-sidebar-revision-log-toggle',
          ],
        ],
      ];
      $form['revision_log'] = [
        '#type' => 'textarea',
        '#placeholder' => $this
          ->t('Briefly describe this state change.'),
        '#attributes' => [
          'class' => [
            'moderation-sidebar-revision-log',
          ],
        ],
        '#states' => [
          'visible' => [
            ':input[name="revision_log_toggle"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
    return $form;
  }

  /**
   * 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.
   *
   * @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.
   */
  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());
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_state
      ->get('entity');

    /** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface[] $transitions */
    $transitions = $this->validation
      ->getValidTransitions($entity, $this
      ->currentUser());

    // Add custom discard draft transition handled by ::discardDraft.
    $transitions['moderation-sidebar-discard-draft'] = '';
    $element = $form_state
      ->getTriggeringElement();
    if (!isset($transitions[$element['#id']])) {
      $form_state
        ->setError($element, $this
        ->t('Invalid transition selected.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_state
      ->get('entity');

    /** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface[] $transitions */
    $transitions = $this->validation
      ->getValidTransitions($entity, $this
      ->currentUser());
    $element = $form_state
      ->getTriggeringElement();

    /** @var \Drupal\content_moderation\ContentModerationState $state */
    $state = $transitions[$element['#id']]
      ->to();
    $state_id = $state
      ->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 change the state to "@state".', [
        '@state' => $state
          ->label(),
      ]);
    }
    $revision = $this
      ->prepareNewRevision($entity, $revision_log);
    $revision
      ->set('moderation_state', $state_id);
    $revision
      ->save();
    $this
      ->messenger()
      ->addMessage($this
      ->t('The moderation state has been updated.'));
    if (!$this->moderationInformation
      ->hasPendingRevision($entity)) {
      $form_state
        ->setRedirectUrl($entity
        ->toUrl());
    }
    else {
      $form_state
        ->setRedirectUrl($entity
        ->toUrl('latest-version'));
    }
  }

  /**
   * Gets the Moderation State of a given Entity.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   An entity.
   *
   * @return \Drupal\workflows\StateInterface
   *   The moderation state for the given entity.
   */
  protected function getModerationState(ContentEntityInterface $entity) {
    $state_id = $entity->moderation_state
      ->get(0)
      ->getValue()['value'];
    $workflow = $this->moderationInformation
      ->getWorkFlowForEntity($entity);
    return $workflow
      ->getTypePlugin()
      ->getState($state_id);
  }

  /**
   * Prepares a new revision of a given entity, if applicable.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   An entity.
   * @param string|\Drupal\Core\StringTranslation\TranslatableMarkup $message
   *   A revision log message to set.
   *
   * @return \Drupal\Core\Entity\EntityInterface
   *   The moderation state for the given entity.
   */
  protected function prepareNewRevision(EntityInterface $entity, $message) {
    $storage = $this->entityTypeManager
      ->getStorage($entity
      ->getEntityTypeId());
    if ($storage instanceof ContentEntityStorageInterface) {
      $revision = $storage
        ->createRevision($entity);
      if ($revision instanceof RevisionLogInterface) {
        $revision
          ->setRevisionLogMessage($message);
        $revision
          ->setRevisionCreationTime(\Drupal::time()
          ->getRequestTime());
        $revision
          ->setRevisionUserId($this
          ->currentUser()
          ->id());
      }
      return $revision;
    }
    return $entity;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
QuickTransitionForm::$entityTypeManager protected property The entity type manager.
QuickTransitionForm::$moderationInformation protected property The moderation information service.
QuickTransitionForm::$validation protected property The moderation state transition validation service.
QuickTransitionForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
QuickTransitionForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
QuickTransitionForm::discardDraft public function Form submission handler to discard the current draft.
QuickTransitionForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
QuickTransitionForm::getModerationState protected function Gets the Moderation State of a given Entity.
QuickTransitionForm::prepareNewRevision protected function Prepares a new revision of a given entity, if applicable.
QuickTransitionForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
QuickTransitionForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
QuickTransitionForm::__construct public function QuickDraftForm constructor.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.