You are here

class RevisionOverviewForm in Support Ticketing System 8

Provides a form for revision overview page.

Hierarchy

Expanded class hierarchy of RevisionOverviewForm

File

modules/support_ticket/src/Form/RevisionOverviewForm.php, line 27
Contains \Drupal\support_ticket\Form\RevisionOverviewForm

Namespace

Drupal\support_ticket\Form
View source
class RevisionOverviewForm extends FormBase {

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * The current user service.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The date service.
   *
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $date;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Wrapper object for writing/reading simple configuration from support_ticket.settings.yml
   */
  protected $config;

  /**
   * Constructs a RevisionOverviewForm object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entityManager
   *   The entity manager.
   * @param \Drupal\Core\Session\AccountInterface $currentUser
   *   The current user.
   * @param \Drupal\Core\Datetime\DateFormatter $date
   *   The date service.
   * @param  \Drupal\Core\Render\RendererInterface
   *   The renderer service.
   */
  public function __construct(EntityManagerInterface $entityManager, AccountInterface $currentUser, DateFormatter $date, RendererInterface $renderer) {
    $this->entityManager = $entityManager;
    $this->currentUser = $currentUser;
    $this->date = $date;
    $this->renderer = $renderer;
    $this->config = $this
      ->config('support_ticket.settings');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager'), $container
      ->get('current_user'), $container
      ->get('date.formatter'), $container
      ->get('renderer'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $support_ticket = NULL) {
    $account = $this->currentUser;
    $support_ticket_store = $this->entityManager
      ->getStorage('support_ticket');
    $type = $support_ticket
      ->getType();
    $vids = array_reverse($support_ticket_store
      ->revisionIds($support_ticket));
    $revision_count = count($vids);
    $build = array(
      '#title' => $this
        ->t('Revisions for %title', array(
        '%title' => $support_ticket
          ->label(),
      )),
      'stid' => array(
        '#type' => 'hidden',
        '#value' => $support_ticket->stid->value,
      ),
    );
    $table_header = array(
      'revision' => $this
        ->t('Revision'),
      'operations' => $this
        ->t('Operations'),
    );

    // Allow comparisons only if there are 2 or more revisions.
    if ($revision_count > 1) {
      $table_header += array(
        'select_column_one' => '',
        'select_column_two' => '',
      );
    }
    $rev_revert_perm = $account
      ->hasPermission("revert {$type} revisions") || $account
      ->hasPermission('revert all revisions') || $account
      ->hasPermission('administer support tickets');
    $rev_delete_perm = $account
      ->hasPermission("delete {$type} revisions") || $account
      ->hasPermission('delete all revisions') || $account
      ->hasPermission('administer support tickets');
    $revert_permission = $rev_revert_perm && $support_ticket
      ->access('update');
    $delete_permission = $rev_delete_perm && $support_ticket
      ->access('delete');

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

    // Add rows to the table.
    foreach ($vids as $vid) {
      if ($revision = $support_ticket_store
        ->loadRevision($vid)) {

        // Markup for revision log.
        if ($revision->revision_log->value != '') {
          $revision_log = '<p class="revision-log">' . Xss::filter($revision->revision_log->value) . '</p>';
        }
        else {
          $revision_log = '';
        }

        // Username to be rendered.
        $username = array(
          '#theme' => 'username',
          '#account' => $revision->uid->entity,
        );
        $revision_date = $this->date
          ->format($revision
          ->getRevisionCreationTime(), 'short');

        // Default revision.
        if ($revision
          ->isDefaultRevision()) {
          $date_username_markup = $this
            ->t('!date by !username', array(
            '!date' => $this
              ->l($revision_date, Url::fromRoute('entity.support_ticket.canonical', array(
              'support_ticket' => $support_ticket
                ->id(),
            ))),
            '!username' => $this->renderer
              ->render($username),
          ));
          $row = array(
            'revision' => array(
              '#markup' => $date_username_markup . $revision_log,
            ),
            'operations' => array(
              '#markup' => SafeMarkup::format('%placeholder', array(
                '%placeholder' => $this
                  ->t('current revision'),
              )),
            ),
            '#attributes' => array(
              'class' => array(
                'revision-current',
              ),
            ),
          );

          // Allow comparisons only if there are 2 or more revisions.
          if ($revision_count > 1) {
            $row += array(
              'select_column_one' => array(
                '#type' => 'radio',
                '#title_display' => 'invisible',
                '#name' => 'radios_left',
                '#return_value' => $vid,
                '#default_value' => FALSE,
              ),
              'select_column_two' => array(
                '#type' => 'radio',
                '#title_display' => 'invisible',
                '#name' => 'radios_right',
                '#default_value' => $vid,
                '#return_value' => $vid,
              ),
            );
          }
        }
        else {
          $route_params = array(
            'support_ticket' => $support_ticket
              ->id(),
            'support_ticket_revision' => $vid,
          );

          // Add links based on permissions.
          if ($revert_permission) {
            $links['revert'] = array(
              'title' => $this
                ->t('Revert'),
              'url' => Url::fromRoute('support_ticket.revision_revert_confirm', $route_params),
            );
          }
          if ($delete_permission) {
            $links['delete'] = array(
              'title' => $this
                ->t('Delete'),
              'url' => Url::fromRoute('support_ticket.revision_delete_confirm', $route_params),
            );
          }
          $date_username_markup = $this
            ->t('!date by !username', array(
            '!date' => $this
              ->l($revision_date, Url::fromRoute('entity.support_ticket.revision', $route_params)),
            '!username' => $this->renderer
              ->render($username),
          ));

          // 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 = array(
            'revision' => array(
              '#markup' => $date_username_markup . $revision_log,
            ),
            'select_column_one' => array(
              '#type' => 'radio',
              '#title_display' => 'invisible',
              '#name' => 'radios_left',
              '#return_value' => $vid,
              '#default_value' => isset($vids[1]) ? $vids[1] : FALSE,
            ),
            'select_column_two' => array(
              '#type' => 'radio',
              '#title_display' => 'invisible',
              '#name' => 'radios_right',
              '#return_value' => $vid,
              '#default_value' => FALSE,
            ),
            'operations' => array(
              '#type' => 'operations',
              '#links' => $links,
            ),
          );
        }

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

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

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

      // @todo Radio-boxes selection resets if there are errors.
      $form_state
        ->setErrorByName('support_ticket_revisions_table', $this
        ->t('Select different revisions to compare.'));
    }
  }

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

    // 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('support_ticket.revisions_diff', array(
      'support_ticket' => $stid,
      'left_vid' => $vid_left,
      'right_vid' => $vid_right,
    ));
    $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.
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 writing/reading simple configuration from support_ticket.settings.yml
RevisionOverviewForm::$currentUser protected property The current user service.
RevisionOverviewForm::$date protected property The date service.
RevisionOverviewForm::$entityManager protected property The entity manager.
RevisionOverviewForm::$renderer protected property The renderer service.
RevisionOverviewForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
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::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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.