class EntityModerationForm

Same name in other branches
  1. 9 core/modules/content_moderation/src/Form/EntityModerationForm.php \Drupal\content_moderation\Form\EntityModerationForm
  2. 8.9.x core/modules/content_moderation/src/Form/EntityModerationForm.php \Drupal\content_moderation\Form\EntityModerationForm
  3. 11.x core/modules/content_moderation/src/Form/EntityModerationForm.php \Drupal\content_moderation\Form\EntityModerationForm

The EntityModerationForm provides a simple UI for changing moderation state.

@internal

Hierarchy

Expanded class hierarchy of EntityModerationForm

1 file declares its use of EntityModerationForm
EntityOperations.php in core/modules/content_moderation/src/EntityOperations.php

File

core/modules/content_moderation/src/Form/EntityModerationForm.php, line 20

Namespace

Drupal\content_moderation\Form
View source
class EntityModerationForm extends FormBase {
    
    /**
     * The moderation information service.
     *
     * @var \Drupal\content_moderation\ModerationInformationInterface
     */
    protected $moderationInfo;
    
    /**
     * The time service.
     *
     * @var \Drupal\Component\Datetime\TimeInterface
     */
    protected $time;
    
    /**
     * The moderation state transition validation service.
     *
     * @var \Drupal\content_moderation\StateTransitionValidationInterface
     */
    protected $validation;
    
    /**
     * EntityModerationForm 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\Component\Datetime\TimeInterface $time
     *   The time service.
     */
    public function __construct(ModerationInformationInterface $moderation_info, StateTransitionValidationInterface $validation, TimeInterface $time) {
        $this->moderationInfo = $moderation_info;
        $this->validation = $validation;
        $this->time = $time;
    }
    
    /**
     * {@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('datetime.time'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'content_moderation_entity_moderation_form';
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, ?ContentEntityInterface $entity = NULL) {
        $current_state = $entity->moderation_state->value;
        $workflow = $this->moderationInfo
            ->getWorkflowForEntity($entity);
        
        /** @var \Drupal\workflows\Transition[] $transitions */
        $transitions = $this->validation
            ->getValidTransitions($entity, $this->currentUser());
        // Exclude self-transitions.
        $transitions = array_filter($transitions, function (Transition $transition) use ($current_state) {
            return $transition->to()
                ->id() != $current_state;
        });
        $target_states = [];
        foreach ($transitions as $transition) {
            $target_states[$transition->to()
                ->id()] = $transition->to()
                ->label();
        }
        if (!count($target_states)) {
            return $form;
        }
        if ($current_state) {
            $form['current'] = [
                '#type' => 'item',
                '#title' => $this->t('Moderation state'),
                '#markup' => $workflow->getTypePlugin()
                    ->getState($current_state)
                    ->label(),
            ];
        }
        // Persist the entity so we can access it in the submit handler.
        $form_state->set('entity', $entity);
        $form['new_state'] = [
            '#type' => 'select',
            '#title' => $this->t('Change to'),
            '#options' => $target_states,
        ];
        $form['revision_log'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Log message'),
            '#size' => 30,
        ];
        $form['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Apply'),
        ];
        $form['#theme'] = [
            'entity_moderation_form',
        ];
        $form['#attached']['library'][] = 'content_moderation/content_moderation';
        // Moderating an entity is allowed in a workspace.
        $form_state->set('workspace_safe', TRUE);
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        
        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
        $entity = $form_state->get('entity');
        
        /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
        $storage = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId());
        $entity = $storage->createRevision($entity, $entity->isDefaultRevision());
        $new_state = $form_state->getValue('new_state');
        $entity->set('moderation_state', $new_state);
        if ($entity instanceof RevisionLogInterface) {
            $entity->setRevisionCreationTime($this->time
                ->getRequestTime());
            $entity->setRevisionLogMessage($form_state->getValue('revision_log'));
            $entity->setRevisionUserId($this->currentUser()
                ->id());
        }
        $entity->save();
        $this->messenger()
            ->addStatus($this->t('The moderation state has been updated.'));
        $new_state = $this->moderationInfo
            ->getWorkflowForEntity($entity)
            ->getTypePlugin()
            ->getState($new_state);
        // The page we're on likely won't be visible if we just set the entity to
        // the default state, as we hide that latest-revision tab if there is no
        // pending revision. Redirect to the canonical URL instead, since that will
        // still exist.
        if ($new_state->isDefaultRevisionState()) {
            $form_state->setRedirectUrl($entity->toUrl('canonical'));
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityModerationForm::$moderationInfo protected property The moderation information service.
EntityModerationForm::$time protected property The time service.
EntityModerationForm::$validation protected property The moderation state transition validation service.
EntityModerationForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
EntityModerationForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EntityModerationForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EntityModerationForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
EntityModerationForm::__construct public function EntityModerationForm constructor.
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::currentUser protected function Gets the current user. 2
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.
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.