You are here

class EntityQueueUIController in Entityqueue 8

Returns responses for Entityqueue UI routes.

Hierarchy

Expanded class hierarchy of EntityQueueUIController

File

src/Controller/EntityQueueUIController.php, line 23

Namespace

Drupal\entityqueue\Controller
View source
class EntityQueueUIController extends ControllerBase {
  use AjaxHelperTrait;

  /**
   * The Entityqueue repository service.
   *
   * @var EntityQueueRepositoryInterface
   */
  protected $entityQueueRepository;

  /**
   * Constructs a EntityQueueUIController object
   *
   * @param EntityQueueRepositoryInterface $entityqueue_respository
   *   The Entityqueue repository service.
   */
  public function __construct(EntityQueueRepositoryInterface $entityqueue_respository) {
    $this->entityQueueRepository = $entityqueue_respository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entityqueue.repository'));
  }

  /**
   * Provides a list of all the subqueues of an entity queue.
   *
   * @param \Drupal\entityqueue\EntityQueueInterface $entity_queue
   *   The entity queue.
   *
   * @return array
   *   A render array.
   */
  public function subqueueList(EntityQueueInterface $entity_queue) {
    $list_builder = $this
      ->entityTypeManager()
      ->getListBuilder('entity_subqueue');
    $list_builder
      ->setQueueId($entity_queue
      ->id());
    return $list_builder
      ->render();
  }

  /**
   * Provides a list of subqueues where an entity can be added.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   * @param string $entity_type_id
   *   (optional) The entity type ID.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   (optional) An entity object.
   *
   * @return array
   *   Array of page elements to render.
   */
  public function subqueueListForEntity(RouteMatchInterface $route_match, $entity_type_id = NULL, EntityInterface $entity = NULL) {
    if (!$entity) {
      $entity = $route_match
        ->getParameter($entity_type_id);
    }
    $queues = $this->entityQueueRepository
      ->getAvailableQueuesForEntity($entity);
    $subqueues = $this
      ->entityTypeManager()
      ->getStorage('entity_subqueue')
      ->loadByProperties([
      'queue' => array_keys($queues),
    ]);
    $list_builder = $this
      ->entityTypeManager()
      ->getListBuilder('entity_subqueue');
    $build['#title'] = $this
      ->t('Entityqueues for %title', [
      '%title' => $entity
        ->label(),
    ]);
    $build['#type'] = 'container';
    $build['#attributes']['id'] = 'entity-subqueue-list';
    $build['#attached']['library'][] = 'core/drupal.ajax';
    $build['table'] = [
      '#type' => 'table',
      '#header' => $list_builder
        ->buildHeader(),
      '#rows' => [],
      '#cache' => [],
      '#empty' => $this
        ->t('There are no queues available.'),
    ];

    /** @var \Drupal\entityqueue\EntitySubqueueInterface $subqueue */
    foreach ($subqueues as $subqueue_id => $subqueue) {
      $row = $list_builder
        ->buildRow($subqueue);

      // Check if entity is in queue.
      $subqueue_items = $subqueue
        ->get('items')
        ->getValue();
      if (in_array($entity
        ->id(), array_column($subqueue_items, 'target_id'), TRUE)) {
        $row['operations']['data']['#links'] = [
          'remove-item' => [
            'title' => $this
              ->t('Remove from queue'),
            'url' => Url::fromRoute('entity.entity_subqueue.remove_item', [
              'entity_queue' => $queues[$subqueue
                ->bundle()]
                ->id(),
              'entity_subqueue' => $subqueue_id,
              'entity' => $entity
                ->id(),
            ]),
            'attributes' => [
              'class' => [
                'use-ajax',
              ],
            ],
          ],
        ];
      }
      else {
        $row['operations']['data']['#links'] = [
          'add-item' => [
            'title' => $this
              ->t('Add to queue'),
            'url' => Url::fromRoute('entity.entity_subqueue.add_item', [
              'entity_queue' => $queues[$subqueue
                ->bundle()]
                ->id(),
              'entity_subqueue' => $subqueue_id,
              'entity' => $entity
                ->id(),
            ]),
            'attributes' => [
              'class' => [
                'use-ajax',
              ],
            ],
          ],
        ];
      }

      // Add an operation for editing the subqueue items.
      // First, compute the destination to send the user back to the
      // entityqueue tab they're currently on. We can't rely on <current>
      // since if any of the AJAX links are used and the page is rebuilt,
      // <current> will point to the most recent AJAX callback, not the
      // original entityqueue tab.
      $destination = Url::fromRoute("entity.{$entity_type_id}.entityqueue", [
        $entity_type_id => $entity
          ->id(),
      ])
        ->toString();
      $row['operations']['data']['#links']['edit-subqueue-items'] = [
        'title' => $this
          ->t('Edit subqueue items'),
        'url' => $subqueue
          ->toUrl('edit-form', [
          'query' => [
            'destination' => $destination,
          ],
        ]),
      ];
      $build['table']['#rows'][$subqueue
        ->id()] = $row;
    }
    return $build;
  }

  /**
   * Returns a form to add a new subqeue.
   *
   * @param \Drupal\entityqueue\EntityQueueInterface $entity_queue
   *   The queue this subqueue will be added to.
   *
   * @return array
   *   The entity subqueue add form.
   */
  public function addForm(EntityQueueInterface $entity_queue) {
    $subqueue = $this
      ->entityTypeManager()
      ->getStorage('entity_subqueue')
      ->create([
      'queue' => $entity_queue
        ->id(),
    ]);
    return $this
      ->entityFormBuilder()
      ->getForm($subqueue);
  }

  /**
   * Calls a method on an entity queue and reloads the listing page.
   *
   * @param \Drupal\entityqueue\EntityQueueInterface $entity_queue
   *   The view being acted upon.
   * @param string $op
   *   The operation to perform, e.g., 'enable' or 'disable'.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Either returns a rebuilt listing page as an AJAX response, or redirects
   *   back to the listing page.
   */
  public function ajaxOperation(EntityQueueInterface $entity_queue, $op, Request $request) {

    // Perform the operation.
    $entity_queue
      ->{$op}()
      ->save();

    // If the request is via AJAX, return the rendered list as JSON.
    if ($request->request
      ->get('js')) {
      $list = $this
        ->entityTypeManager()
        ->getListBuilder('entity_queue')
        ->render();
      $response = new AjaxResponse();
      $response
        ->addCommand(new ReplaceCommand('#entity-queue-list', $list));
      return $response;
    }

    // Otherwise, redirect back to the page.
    return $this
      ->redirect('entity.entity_queue.collection');
  }

  /**
   * Calls a method on an entity subqueue page and reloads the page.
   *
   * @param \Drupal\entityqueue\EntitySubqueueInterface $entity_subqueue
   *   The subqueue being acted upon.
   * @param string $op
   *   The operation to perform, e.g., 'addItem' or 'removeItem'.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Either returns a rebuilt listing page as an AJAX response, or redirects
   *   back to the current page.
   */
  public function subqueueAjaxOperation(EntitySubqueueInterface $entity_subqueue, $op, Request $request) {
    $entity_id = $request
      ->get('entity');
    $entity = $this
      ->entityTypeManager()
      ->getStorage($entity_subqueue
      ->getQueue()
      ->getTargetEntityTypeId())
      ->load($entity_id);

    // Perform the operation.
    $entity_subqueue
      ->{$op}($entity);

    // Run validation.
    $violations = $entity_subqueue
      ->validate();

    // Save subqueue.
    if (count($violations) === 0) {
      $entity_subqueue
        ->save();
    }

    // If the request is via AJAX, return the rendered list as JSON.
    if ($this
      ->isAjax()) {
      $route_match = RouteMatch::createFromRequest($request);
      $content = $this
        ->subqueueListForEntity($route_match, $entity
        ->getEntityTypeId(), $entity);

      // Also display the validation errors if there are any.
      if (count($violations)) {
        $content['errors'] = [
          '#theme' => 'status_messages',
          '#message_list' => [
            'error' => [
              $this
                ->t('The operation could not be performed for the following reasons:'),
            ],
          ],
          '#status_headings' => [
            'error' => $this
              ->t('Error message'),
          ],
          '#weight' => -10,
        ];
        foreach ($violations as $violation) {
          $content['errors']['#message_list']['error'][] = $violation
            ->getMessage();
        }
      }
      $response = new AjaxResponse();
      $response
        ->addCommand(new ReplaceCommand('#entity-subqueue-list', $content));
      return $response;
    }

    // Otherwise, redirect back to the page.
    return $this
      ->redirect('<current>');
  }

  /**
   * Checks access for a specific request.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   * @param string $entity_type_id
   *   (optional) The entity type ID.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(RouteMatchInterface $route_match, $entity_type_id = NULL) {

    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $route_match
      ->getParameter($entity_type_id);
    if ($entity && $this->entityQueueRepository
      ->getAvailableQueuesForEntity($entity)) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxHelperTrait::getRequestWrapperFormat protected function Gets the wrapper format of the current request.
AjaxHelperTrait::isAjax protected function Determines if the current request is via AJAX.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
EntityQueueUIController::$entityQueueRepository protected property The Entityqueue repository service.
EntityQueueUIController::access public function Checks access for a specific request.
EntityQueueUIController::addForm public function Returns a form to add a new subqeue.
EntityQueueUIController::ajaxOperation public function Calls a method on an entity queue and reloads the listing page.
EntityQueueUIController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
EntityQueueUIController::subqueueAjaxOperation public function Calls a method on an entity subqueue page and reloads the page.
EntityQueueUIController::subqueueList public function Provides a list of all the subqueues of an entity queue.
EntityQueueUIController::subqueueListForEntity public function Provides a list of subqueues where an entity can be added.
EntityQueueUIController::__construct public function Constructs a EntityQueueUIController object
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.