You are here

class PetDiffRevisionOverviewForm in Previewable email templates 8.3

Provides a form for Pet revision overview page.

Hierarchy

Expanded class hierarchy of PetDiffRevisionOverviewForm

File

src/Form/PetDiffRevisionOverviewForm.php, line 14

Namespace

Drupal\pet\Form
View source
class PetDiffRevisionOverviewForm extends RevisionOverviewForm {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $node = NULL, PetInterface $pet = NULL) {
    $account = $this->currentUser;
    $langcode = $pet
      ->language()
      ->getId();
    $langname = $pet
      ->language()
      ->getName();
    $languages = $pet
      ->getTranslationLanguages();
    $has_translations = count($languages) > 1;

    /** @var \Drupal\pet\PetStorageInterface $pet_storage */
    $pet_storage = $this->entityTypeManager
      ->getStorage('pet');
    $pagerLimit = $this->config
      ->get('general_settings.revision_pager_limit');
    $query = $this->entityQuery
      ->get('pet')
      ->condition($pet
      ->getEntityType()
      ->getKey('id'), $pet
      ->id())
      ->pager($pagerLimit)
      ->allRevisions()
      ->sort($pet
      ->getEntityType()
      ->getKey('revision'), 'DESC')
      ->execute();
    $vids = array_keys($query);
    $revision_count = count($vids);
    $build['#title'] = $has_translations ? $this
      ->t('@langname revisions for %title', [
      '@langname' => $langname,
      '%title' => $pet
        ->label(),
    ]) : $this
      ->t('Revisions for %title', [
      '%title' => $pet
        ->label(),
    ]);
    $build['pid'] = array(
      '#type' => 'hidden',
      '#value' => $pet
        ->id(),
    );
    $table_header = [];
    $table_header['revision'] = $this
      ->t('Revision');

    // Allow comparisons only if there are 2 or more revisions.
    if ($revision_count > 1) {
      $table_header += array(
        'select_column_one' => '',
        'select_column_two' => '',
      );
    }
    $table_header['operations'] = $this
      ->t('Operations');
    $rev_revert_perm = $account
      ->hasPermission('revert pet revisions') || $account
      ->hasPermission('administer pet entities');
    $rev_delete_perm = $account
      ->hasPermission('delete pet revisions') || $account
      ->hasPermission('administer pet entities');
    $revert_permission = $rev_revert_perm && $pet
      ->access('update');
    $delete_permission = $rev_delete_perm && $pet
      ->access('delete');

    // Contains the table listing the revisions.
    $build['node_revisions_table'] = array(
      '#type' => 'table',
      '#header' => $table_header,
      '#attributes' => array(
        'class' => array(
          'diff-revisions',
        ),
      ),
    );
    $build['node_revisions_table']['#attached']['library'][] = 'diff/diff.general';
    $build['node_revisions_table']['#attached']['drupalSettings']['diffRevisionRadios'] = $this->config
      ->get('general_settings.radio_behavior');
    $default_revision = $pet
      ->getRevisionId();

    // Add rows to the table.
    foreach ($vids as $key => $vid) {
      $previous_revision = NULL;
      if (isset($vids[$key + 1])) {
        $previous_revision = $pet_storage
          ->loadRevision($vids[$key + 1]);
      }

      /** @var \Drupal\pet\Entity\PetInterface $revision */
      if ($revision = $pet_storage
        ->loadRevision($vid)) {
        if ($revision
          ->hasTranslation($langcode) && $revision
          ->getTranslation($langcode)
          ->isRevisionTranslationAffected()) {
          $username = array(
            '#theme' => 'username',
            '#account' => $revision
              ->getRevisionUser(),
          );
          $revision_date = $this->date
            ->format($revision
            ->getRevisionCreationTime(), 'short');

          // Use revision link to link to revisions that are not active.
          if ($vid != $pet
            ->getRevisionId()) {
            $link = Link::fromTextAndUrl($revision_date, new Url('entity.pet.revision', [
              'pet' => $pet
                ->id(),
              'pet_revision' => $vid,
            ]));
          }
          else {
            $link = $pet
              ->toLink($revision_date);
          }
          if ($vid == $default_revision) {
            $row = [
              'revision' => $this
                ->buildRevision($link, $username, $revision, $previous_revision),
            ];

            // Allow comparisons only if there are 2 or more revisions.
            if ($revision_count > 1) {
              $row += [
                'select_column_one' => $this
                  ->buildSelectColumn('radios_left', $vid, FALSE),
                'select_column_two' => $this
                  ->buildSelectColumn('radios_right', $vid, $vid),
              ];
            }
            $row['operations'] = array(
              '#prefix' => '<em>',
              '#markup' => $this
                ->t('Current revision'),
              '#suffix' => '</em>',
              '#attributes' => array(
                'class' => array(
                  'revision-current',
                ),
              ),
            );
            $row['#attributes'] = [
              'class' => [
                'revision-current',
              ],
            ];
          }
          else {
            $route_params = array(
              'pet' => $pet
                ->id(),
              'pet_revision' => $vid,
              'langcode' => $langcode,
            );
            $links = array();
            if ($revert_permission) {
              $links['revert'] = [
                'title' => $vid < $pet
                  ->getRevisionId() ? $this
                  ->t('Revert') : $this
                  ->t('Set as current revision'),
                'url' => $has_translations ? Url::fromRoute('entity.pet.revision_revert_translation_confirm', [
                  'pet' => $pet
                    ->id(),
                  'pet_revision' => $vid,
                  'langcode' => $langcode,
                ]) : Url::fromRoute('entity.pet.revision_revert_confirm', [
                  'pet' => $pet
                    ->id(),
                  'pet_revision' => $vid,
                ]),
              ];
            }
            if ($delete_permission) {
              $links['delete'] = array(
                'title' => $this
                  ->t('Delete'),
                'url' => Url::fromRoute('entity.pet.revision_delete_confirm', $route_params),
              );
            }

            // Here we don't have to deal with 'only one revision' case because
            // if there's only one revision it will also be the default one,
            // entering on the first branch of this if else statement.
            $row = [
              'revision' => $this
                ->buildRevision($link, $username, $revision, $previous_revision),
              'select_column_one' => $this
                ->buildSelectColumn('radios_left', $vid, isset($vids[1]) ? $vids[1] : FALSE),
              'select_column_two' => $this
                ->buildSelectColumn('radios_right', $vid, FALSE),
              'operations' => [
                '#type' => 'operations',
                '#links' => $links,
              ],
            ];
          }

          // Add the row to the table.
          $build['node_revisions_table'][] = $row;
        }
      }
    }

    // Allow comparisons only if there are 2 or more revisions.
    if ($revision_count > 1) {
      $build['submit'] = array(
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => t('Compare selected revisions'),
        '#attributes' => array(
          'class' => array(
            'diff-button',
          ),
        ),
      );
    }
    $build['pager'] = array(
      '#type' => 'pager',
    );
    $build['#attached']['library'][] = 'node/drupal.node.admin';
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $input = $form_state
      ->getUserInput();
    $vid_left = $input['radios_left'];
    $vid_right = $input['radios_right'];
    $pid = $input['pid'];

    // Always place the older revision on the left side of the comparison
    // and the newer revision on the right side (however revisions can be
    // compared both ways if we manually change the order of the parameters).
    if ($vid_left > $vid_right) {
      $aux = $vid_left;
      $vid_left = $vid_right;
      $vid_right = $aux;
    }

    // Builds the redirect Url.
    $redirect_url = Url::fromRoute('entity.pet.revisions_diff', array(
      'pet' => $pid,
      'left_revision' => $vid_left,
      'right_revision' => $vid_right,
      'filter' => $this->diffLayoutManager
        ->getDefaultLayout(),
    ));
    $form_state
      ->setRedirectUrl($redirect_url);
  }

}

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.
PetDiffRevisionOverviewForm::buildForm public function Form constructor. Overrides RevisionOverviewForm::buildForm
PetDiffRevisionOverviewForm::submitForm public function Form submission handler. Overrides RevisionOverviewForm::submitForm
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.
RevisionOverviewForm::$config protected property Wrapper object for simple configuration from diff.settings.yml.
RevisionOverviewForm::$currentUser protected property The current user service.
RevisionOverviewForm::$date protected property The date service.
RevisionOverviewForm::$diffLayoutManager protected property The field diff layout plugin manager service.
RevisionOverviewForm::$entityComparison protected property The diff entity comparison service.
RevisionOverviewForm::$entityTypeManager protected property The entity type manager.
RevisionOverviewForm::$languageManager protected property The language manager.
RevisionOverviewForm::$renderer protected property The renderer service.
RevisionOverviewForm::buildRevision protected function Set and return configuration for revision.
RevisionOverviewForm::buildSelectColumn protected function Set column attributes and return config array.
RevisionOverviewForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
RevisionOverviewForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RevisionOverviewForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
RevisionOverviewForm::__construct public function Constructs a RevisionOverviewForm object.
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.