class RevisionRevertForm

Same name in other branches
  1. 11.x core/lib/Drupal/Core/Entity/Form/RevisionRevertForm.php \Drupal\Core\Entity\Form\RevisionRevertForm

Provides a form for reverting an entity revision.

@internal

Hierarchy

Expanded class hierarchy of RevisionRevertForm

2 files declare their use of RevisionRevertForm
block_content.install in core/modules/block_content/block_content.install
Install, update and uninstall functions for the block_content module.
taxonomy.install in core/modules/taxonomy/taxonomy.install
Install, update and uninstall functions for the taxonomy module.

File

core/lib/Drupal/Core/Entity/Form/RevisionRevertForm.php, line 28

Namespace

Drupal\Core\Entity\Form
View source
class RevisionRevertForm extends ConfirmFormBase implements EntityFormInterface {
    
    /**
     * The entity operation.
     *
     * @var string
     */
    protected string $operation;
    
    /**
     * The entity revision.
     *
     * @var \Drupal\Core\Entity\RevisionableInterface
     */
    protected RevisionableInterface $revision;
    
    /**
     * The module handler.
     *
     * @var \Drupal\Core\Extension\ModuleHandlerInterface
     */
    protected ModuleHandlerInterface $moduleHandler;
    
    /**
     * The entity type manager.
     *
     * @var \Drupal\Core\Entity\EntityTypeManagerInterface
     */
    protected EntityTypeManagerInterface $entityTypeManager;
    
    /**
     * Creates a new RevisionRevertForm instance.
     *
     * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
     *   The date formatter.
     * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundleInformation
     *   The bundle information.
     * @param \Drupal\Core\Messenger\MessengerInterface $messenger
     *   The messenger service.
     * @param \Drupal\Component\Datetime\TimeInterface $time
     *   The time service.
     * @param \Drupal\Core\Session\AccountInterface $currentUser
     *   The current user.
     */
    public function __construct(DateFormatterInterface $dateFormatter, EntityTypeBundleInfoInterface $bundleInformation, MessengerInterface $messenger, TimeInterface $time, AccountInterface $currentUser) {
        $this->messenger = $messenger;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('date.formatter'), $container->get('entity_type.bundle.info'), $container->get('messenger'), $container->get('datetime.time'), $container->get('current_user'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function getBaseFormId() {
        return $this->revision
            ->getEntityTypeId() . '_revision_revert';
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return $this->revision
            ->getEntityTypeId() . '_revision_revert';
    }
    
    /**
     * {@inheritdoc}
     */
    public function getQuestion() {
        return $this->getEntity() instanceof RevisionLogInterface ? $this->t('Are you sure you want to revert to the revision from %revision-date?', [
            '%revision-date' => $this->dateFormatter
                ->format($this->getEntity()
                ->getRevisionCreationTime()),
        ]) : $this->t('Are you sure you want to revert the revision?');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCancelUrl() {
        return $this->getEntity()
            ->getEntityType()
            ->hasLinkTemplate('version-history') && $this->getEntity()
            ->toUrl('version-history')
            ->access($this->currentUser) ? $this->getEntity()
            ->toUrl('version-history') : $this->getEntity()
            ->toUrl();
    }
    
    /**
     * {@inheritdoc}
     */
    public function getConfirmText() {
        return $this->t('Revert');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getDescription() {
        return '';
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form = parent::buildForm($form, $form_state);
        $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.', [
                '@type' => $bundleLabel,
                '%title' => $revisionLabel,
                '%revision-date' => $date,
            ]));
        }
        else {
            $this->messenger
                ->addMessage($this->t('@type %title has been reverted.', [
                '@type' => $bundleLabel,
                '%title' => $revisionLabel,
            ]));
        }
        $this->logger($this->revision
            ->getEntityType()
            ->getProvider())
            ->info('@type: reverted %title revision %revision.', [
            '@type' => $this->revision
                ->bundle(),
            '%title' => $revisionLabel,
            '%revision' => $revisionId,
        ]);
        $versionHistoryUrl = $this->revision
            ->toUrl('version-history');
        if ($versionHistoryUrl->access($this->currentUser())) {
            $form_state->setRedirectUrl($versionHistoryUrl);
        }
        if (!$form_state->getRedirect()) {
            $canonicalUrl = $this->revision
                ->toUrl();
            if ($canonicalUrl->access($this->currentUser())) {
                $form_state->setRedirectUrl($canonicalUrl);
            }
        }
    }
    
    /**
     * Prepares a revision to be reverted.
     *
     * @param \Drupal\Core\Entity\RevisionableInterface $revision
     *   The revision to be reverted.
     * @param \Drupal\Core\Form\FormStateInterface $formState
     *   The current state of the form.
     *
     * @return \Drupal\Core\Entity\RevisionableInterface
     *   The new revision, the same type as passed to $revision.
     */
    protected function prepareRevision(RevisionableInterface $revision, FormStateInterface $formState) : RevisionableInterface {
        $storage = $this->entityTypeManager
            ->getStorage($revision->getEntityTypeId());
        if (!$storage instanceof RevisionableStorageInterface) {
            throw new \LogicException('Revisionable entities are expected to implement RevisionableStorageInterface');
        }
        $revision = $storage->createRevision($revision);
        $time = $this->time
            ->getRequestTime();
        if ($revision instanceof EntityChangedInterface) {
            $revision->setChangedTime($time);
        }
        if ($revision instanceof RevisionLogInterface) {
            $originalRevisionTimestamp = $revision->getRevisionCreationTime();
            $date = $this->dateFormatter
                ->format($originalRevisionTimestamp);
            $revision->setRevisionLogMessage($this->t('Copy of the revision from %date.', [
                '%date' => $date,
            ]))
                ->setRevisionCreationTime($time)
                ->setRevisionUserId($this->currentUser()
                ->id());
        }
        return $revision;
    }
    
    /**
     * Returns the bundle label of an entity.
     *
     * @param \Drupal\Core\Entity\RevisionableInterface $entity
     *   The entity.
     *
     * @return string|null
     *   The bundle label.
     */
    protected function getBundleLabel(RevisionableInterface $entity) : ?string {
        $bundleInfo = $this->bundleInformation
            ->getBundleInfo($entity->getEntityTypeId());
        return isset($bundleInfo[$entity->bundle()]['label']) ? (string) $bundleInfo[$entity->bundle()]['label'] : NULL;
    }
    
    /**
     * {@inheritdoc}
     */
    public function setOperation($operation) {
        $this->operation = $operation;
        return $this;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getOperation() {
        return $this->operation;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getEntity() {
        return $this->revision;
    }
    
    /**
     * {@inheritdoc}
     */
    public function setEntity(EntityInterface $entity) {
        assert($entity instanceof RevisionableInterface);
        $this->revision = $entity;
        return $this;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getEntityFromRouteMatch(RouteMatchInterface $route_match, $entity_type_id) {
        return $route_match->getParameter($entity_type_id . '_revision');
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildEntity(array $form, FormStateInterface $form_state) {
        return $this->revision;
    }
    
    /**
     * {@inheritdoc}
     */
    public function save(array $form, FormStateInterface $form_state) {
        return $this->revision
            ->save();
    }
    
    /**
     * {@inheritdoc}
     */
    public function setModuleHandler(ModuleHandlerInterface $module_handler) {
        $this->moduleHandler = $module_handler;
        return $this;
    }
    
    /**
     * {@inheritdoc}
     */
    public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
        $this->entityTypeManager = $entity_type_manager;
        return $this;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function currentUser() {
        return $this->currentUser;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 2
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
FormBase::container private function Returns the service container.
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.
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 57
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. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
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.
RevisionRevertForm::$entityTypeManager protected property The entity type manager.
RevisionRevertForm::$moduleHandler protected property The module handler.
RevisionRevertForm::$operation protected property The entity operation.
RevisionRevertForm::$revision protected property The entity revision.
RevisionRevertForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity
RevisionRevertForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
RevisionRevertForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
RevisionRevertForm::currentUser protected function Gets the current user. Overrides FormBase::currentUser
RevisionRevertForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId
RevisionRevertForm::getBundleLabel protected function Returns the bundle label of an entity.
RevisionRevertForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
RevisionRevertForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
RevisionRevertForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
RevisionRevertForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
RevisionRevertForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch
RevisionRevertForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RevisionRevertForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
RevisionRevertForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
RevisionRevertForm::prepareRevision protected function Prepares a revision to be reverted.
RevisionRevertForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save
RevisionRevertForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
RevisionRevertForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
RevisionRevertForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
RevisionRevertForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
RevisionRevertForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
RevisionRevertForm::__construct public function Creates a new RevisionRevertForm instance.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
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.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.