You are here

class DeleteUpdateForm in Scheduled Publish 8.3

Hierarchy

Expanded class hierarchy of DeleteUpdateForm

1 string reference to 'DeleteUpdateForm'
scheduled_publish.routing.yml in ./scheduled_publish.routing.yml
scheduled_publish.routing.yml

File

src/Form/DeleteUpdateForm.php, line 16
Contains \Drupal\scheduled_publish\Form\DeleteUpdateForm.

Namespace

Drupal\scheduled_publish\Form
View source
class DeleteUpdateForm extends ConfirmFormBase {

  /**
   * The entity.
   */
  protected $entity;

  /**
   * The field.
   */
  protected $field;

  /**
   * The field delta.
   */
  protected $field_delta;

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    $states = $this->entity
      ->get($this->field)
      ->getValue();
    $prev_state = $states[$this->field_delta - 1] ?? FALSE;
    if ($prev_state) {
      $orig_status = $this->entity->moderation_state->value;
      $this->entity->moderation_state->value = $prev_state['moderation_state'];
    }
    $m_options = $this
      ->getModerationOptions($this->entity);
    if ($prev_state) {
      $this->entity->moderation_state->value = $orig_status;
    }
    $state_display = $states[$this->field_delta]['moderation_state'];
    if (isset($m_options[$states[$this->field_delta]['moderation_state']])) {
      $state_display = $m_options[$states[$this->field_delta]['moderation_state']];
      $state_display .= ' (';
      $state_display .= $states[$this->field_delta]['moderation_state'];
      $state_display .= ')';
    }
    $entity_info = $this->entity
      ->label() . ' (' . $this->entity
      ->id() . ')';
    $date = new DrupalDateTime($states[$this->field_delta]['value'], date_default_timezone_get());
    $date_display = $date
      ->format('d.m.Y - H:i');
    return $this
      ->t('Are you sure you want to delete "@state on @date" status update for the "@node" node?', [
      '@node' => $entity_info,
      '@state' => $state_display,
      '@date' => $date_display,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return Url::fromRoute('view.scheduled_publish.page_1');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity = NULL, $field_delta = NULL) {
    if (!isset($entity) || !isset($field_delta)) {
      $form['message'] = [
        '#theme_wrappers' => [
          'container',
        ],
        '#markup' => $this
          ->t('A valid entity and field delta must be provided.'),
      ];
      return $form;
    }
    $fields = $this
      ->getScheduledFields($entity
      ->getEntityTypeId(), $entity
      ->bundle());
    $field = reset($fields);
    $states = $entity
      ->get($field)
      ->getValue();
    if (!isset($states[$field_delta])) {
      $form['message'] = [
        '#theme_wrappers' => [
          'container',
        ],
        '#markup' => $this
          ->t('This status update does not exist.'),
      ];
      return $form;
    }
    $form['message'] = [
      '#theme_wrappers' => [
        'container',
      ],
      '#markup' => $this
        ->t('If this state deletion invalidates any existing transitions those will be deleted as well.'),
    ];

    // Save data into form_state and class variables.
    $form_state
      ->set([
      'scheduled_publish',
      'entity',
    ], $entity);
    $form_state
      ->set([
      'scheduled_publish',
      'field',
    ], $field);
    $form_state
      ->set([
      'scheduled_publish',
      'field_delta',
    ], $field_delta);
    $this->entity = $entity;
    $this->field = $field;
    $this->field_delta = $field_delta;
    return parent::buildForm($form, $form_state);
  }

  /**
   * Returns scheduled publish fields
   *
   * @param string $entityTypeName
   * @param string $bundleName
   *
   * @return array
   */
  protected function getScheduledFields(string $entityTypeName, string $bundleName) : array {
    $scheduledFields = [];
    $fields = \Drupal::service('entity_field.manager')
      ->getFieldDefinitions($entityTypeName, $bundleName);
    foreach ($fields as $fieldName => $field) {

      /** @var FieldConfig $field */
      if (strpos($fieldName, 'field_') !== FALSE) {
        if ($field
          ->getType() === 'scheduled_publish') {
          $scheduledFields[] = $fieldName;
        }
      }
    }
    return $scheduledFields;
  }

  /**
   * Get moderation options.
   */
  protected function getModerationOptions($entity) {
    $states = [];

    /** @var \Drupal\content_moderation\ModerationInformation $moderationInformationService */
    $moderationInformationService = \Drupal::service('content_moderation.moderation_information');
    if ($moderationInformationService
      ->isModeratedEntity($entity)) {

      /** @var \Drupal\content_moderation\StateTransitionValidation $transitionValidationService */
      $transitionValidationService = \Drupal::service('content_moderation.state_transition_validation');
      $transitions = $transitionValidationService
        ->getValidTransitions($entity, \Drupal::currentUser());
      foreach ($transitions as $key => $value) {
        $states[$transitions[$key]
          ->to()
          ->id()] = $transitions[$key]
          ->label();
      }
    }
    return $states;
  }

  /**
   * Handles state values, clean-up and ordering.
   */
  public function handleStates(FormStateInterface $form_state, &$states) {
    $entity = $form_state
      ->get([
      'scheduled_publish',
      'entity',
    ]);
    $orig_status = $entity->moderation_state->value;
    $m_options = $this
      ->getModerationOptions($entity);

    // Make sure states are ordered correctly.
    $this
      ->handleStateOrdering($states);
    foreach ($states as $key => $state) {
      if (isset($m_options[$state['moderation_state']])) {
        $entity->moderation_state->value = $state['moderation_state'];
        $m_options = $this
          ->getModerationOptions($entity);
      }
      else {

        // Delete invalid state changes.
        unset($states[$key]);
      }
    }
    $entity->moderation_state->value = $orig_status;

    // Adjust ordering in case any invalid entries got removed.
    $this
      ->handleStateOrdering($states);
  }

  /**
   * Re-orders states and adds/changes their delta values based on date.
   */
  public static function handleStateOrdering(&$states) {
    usort($states, function ($a, $b) {
      $a_timestamp = strtotime($a['value']);
      $b_timestamp = strtotime($b['value']);
      if ($a_timestamp == $b_timestamp) {
        return 0;
      }
      return $a_timestamp < $b_timestamp ? -1 : 1;
    });
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $entity = $form_state
      ->get([
      'scheduled_publish',
      'entity',
    ]);
    $field = $form_state
      ->get([
      'scheduled_publish',
      'field',
    ]);
    $delta = $form_state
      ->get([
      'scheduled_publish',
      'field_delta',
    ]);
    $states = $entity
      ->get($field)
      ->getValue();
    unset($states[$delta]);
    $this
      ->handleStates($form_state, $states);

    // Reload entity to be sure it's not old.
    $entity = \Drupal::entityTypeManager()
      ->getStorage($entity
      ->getEntityTypeId())
      ->load($entity
      ->id());
    $entity
      ->set($field, $states);
    $entity
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('Status update deleted.'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 1
ConfirmFormBase::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormInterface::getConfirmText 20
ConfirmFormBase::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormInterface::getDescription 11
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
DeleteUpdateForm::$entity protected property The entity.
DeleteUpdateForm::$field protected property The field.
DeleteUpdateForm::$field_delta protected property The field delta.
DeleteUpdateForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
DeleteUpdateForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
DeleteUpdateForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DeleteUpdateForm::getModerationOptions protected function Get moderation options.
DeleteUpdateForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
DeleteUpdateForm::getScheduledFields protected function Returns scheduled publish fields
DeleteUpdateForm::handleStateOrdering public static function Re-orders states and adds/changes their delta values based on date.
DeleteUpdateForm::handleStates public function Handles state values, clean-up and ordering.
DeleteUpdateForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
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.