You are here

class LogRescheduleActionForm in Log entity 2.x

Provides a log reschedule confirmation form.

Hierarchy

Expanded class hierarchy of LogRescheduleActionForm

1 string reference to 'LogRescheduleActionForm'
log.routing.yml in ./log.routing.yml
log.routing.yml

File

src/Form/LogRescheduleActionForm.php, line 11

Namespace

Drupal\log\Form
View source
class LogRescheduleActionForm extends LogActionFormBase {

  /**
   * The action id.
   *
   * @var string
   */
  protected $actionId = 'log_reschedule_action';

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->formatPlural(count($this->logs), 'Are you sure you want to reschedule this log?', 'Are you sure you want to reschedule these logs?');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Reschedule');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['type_of_date'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Reschedule by a relative date'),
      '#weight' => -10,
    ];
    $form['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h4',
      '#value' => $form['date']['#title'],
      '#weight' => -9,
    ];

    // Datetime fields need to be wrapped for #states to work.
    // @see https://www.drupal.org/project/drupal/issues/2419131
    $form['absolute'] = [
      '#type' => 'container',
      '#states' => [
        'visible' => [
          ':input[name="type_of_date"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['absolute']['date'] = $form['date'];
    unset($form['absolute']['date']['#title']);
    $form['absolute']['date']['#required'] = FALSE;
    unset($form['date']);
    $form['relative'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'container-inline',
        ],
      ],
      '#states' => [
        'visible' => [
          ':input[name="type_of_date"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['relative']['amount'] = [
      '#type' => 'number',
      '#size' => 4,
    ];
    $form['relative']['time'] = [
      '#type' => 'select',
      '#options' => [
        'hour' => $this
          ->t('Hours'),
        'day' => $this
          ->t('Days'),
        'week' => $this
          ->t('Weeks'),
        'month' => $this
          ->t('Months'),
        'year' => $this
          ->t('Years'),
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $type_of_date = $form_state
      ->getValue('type_of_date');
    if ($type_of_date) {
      $amount = $form_state
        ->getValue('amount');
      $time = $form_state
        ->getValue('time');
      if (empty($amount)) {
        $form_state
          ->setError($form['relative']['amount'], 'Please enter the amount of time for rescheduling.');
      }
      if (empty($time)) {
        $form_state
          ->setError($form['relative']['amount'], 'Please enter the time units for rescheduling.');
      }
    }
  }

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

    // Filter out logs the user doesn't have access to.
    $inaccessible_logs = [];
    $accessible_logs = [];
    $current_user = $this
      ->currentUser();
    foreach ($this->logs as $log) {
      if (!$log
        ->get('timestamp')
        ->access('edit', $current_user) || !$log
        ->get('status')
        ->access('edit', $current_user) || !$log
        ->access('update', $current_user)) {
        $inaccessible_logs[] = $log;
        continue;
      }
      $accessible_logs[] = $log;
    }
    if ($form_state
      ->getValue('confirm') && !empty($accessible_logs)) {
      $count = count($accessible_logs);
      $type_of_date = $form_state
        ->getValue('type_of_date');
      if ($type_of_date) {
        $amount = $form_state
          ->getValue('amount');
        $time = $form_state
          ->getValue('time');
        $sign = $amount >= 0 ? '+' : '';
        foreach ($accessible_logs as $log) {
          $new_date = new DrupalDateTime();
          $new_date
            ->setTimestamp($log
            ->get('timestamp')->value);
          $new_date
            ->modify("{$sign}{$amount} {$time}");
          if ($log
            ->get('status')
            ->first()
            ->isTransitionAllowed('to_pending')) {
            $log
              ->get('status')
              ->first()
              ->applyTransitionById('to_pending');
          }
          $log
            ->set('timestamp', $new_date
            ->getTimestamp());
          $log
            ->setNewRevision(TRUE);
          $log
            ->save();
        }
      }
      else {

        /** @var \Drupal\Core\Datetime\DrupalDateTime $new_date */
        $new_date = $form_state
          ->getValue('date');
        foreach ($accessible_logs as $log) {
          if ($log
            ->get('status')
            ->first()
            ->isTransitionAllowed('to_pending')) {
            $log
              ->get('status')
              ->first()
              ->applyTransitionById('to_pending');
          }
          $log
            ->set('timestamp', $new_date
            ->getTimestamp());
          $log
            ->setNewRevision(TRUE);
          $log
            ->save();
        }
      }
      $this
        ->messenger()
        ->addMessage($this
        ->formatPlural($count, 'Rescheduled 1 log.', 'Rescheduled @count logs.'));
    }

    // Add warning message if there were inaccessible logs.
    if (!empty($inaccessible_logs)) {
      $inaccessible_count = count($inaccessible_logs);
      $this
        ->messenger()
        ->addWarning($this
        ->formatPlural($inaccessible_count, 'Could not reschedule @count log because you do not have the necessary permissions.', 'Could not reschedule @count logs because you do not have the necessary permissions.'));
    }
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description 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 2
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::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.
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.
LogActionFormBase::$entityTypeManager protected property The entity type manager.
LogActionFormBase::$logs protected property The logs to clone.
LogActionFormBase::$tempStoreFactory protected property The tempstore factory.
LogActionFormBase::$user protected property The current user.
LogActionFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
LogActionFormBase::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
LogActionFormBase::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
LogActionFormBase::__construct public function Constructs a LogCloneActionForm form object.
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.
LogRescheduleActionForm::$actionId protected property The action id.
LogRescheduleActionForm::buildForm public function Form constructor. Overrides LogActionFormBase::buildForm
LogRescheduleActionForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides LogActionFormBase::getConfirmText
LogRescheduleActionForm::getFormId public function Returns a unique string identifying the form. Overrides LogActionFormBase::getFormId
LogRescheduleActionForm::getQuestion public function Returns the question to ask the user. Overrides LogActionFormBase::getQuestion
LogRescheduleActionForm::submitForm public function Form submission handler. Overrides LogActionFormBase::submitForm
LogRescheduleActionForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.