You are here

class DraggableDashboardController in Draggable dashboard 8

Same name and namespace in other branches
  1. 8.2 src/Controller/DraggableDashboardController.php \Drupal\draggable_dashboard\Controller\DraggableDashboardController

Controller routines for draggable dashboards.

Hierarchy

Expanded class hierarchy of DraggableDashboardController

File

src/Controller/DraggableDashboardController.php, line 22

Namespace

Drupal\draggable_dashboard\Controller
View source
class DraggableDashboardController extends ControllerBase {

  /**
   * DraggableDashboardController constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity Type Manager service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

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

  /**
   * Displays the draggable dashboard administration overview page.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return array
   *   A render array as expected by drupal_render().
   */
  public function adminOverview(Request $request) {
    $rows = [];
    $storage = $this->entityTypeManager
      ->getStorage('dashboard_entity');
    $header = [
      $this
        ->t('Title'),
      $this
        ->t('Description'),
      $this
        ->t('Operations'),
    ];
    $dashboards = $storage
      ->getQuery()
      ->execute();
    foreach ($dashboards as $dashboardID) {
      $dashboard = $storage
        ->load($dashboardID);
      $row = [];
      $row[] = $dashboard
        ->get('title');
      $row[] = $dashboard
        ->get('description');
      $links = [
        'manage' => [
          'title' => $this
            ->t('Manage Blocks'),
          'url' => Url::fromRoute('draggable_dashboard.manage_dashboard', [
            'did' => $dashboard
              ->id(),
          ]),
        ],
        'edit' => [
          'title' => $this
            ->t('Edit'),
          'url' => Url::fromRoute('draggable_dashboard.edit_dashboard', [
            'did' => $dashboard
              ->id(),
          ]),
        ],
        'delete' => [
          'title' => $this
            ->t('Delete'),
          'url' => Url::fromRoute('draggable_dashboard.delete_dashboard', [
            'did' => $dashboard
              ->id(),
          ]),
        ],
      ];
      $row[] = [
        'data' => [
          '#type' => 'operations',
          '#links' => $links,
        ],
      ];
      $rows[] = $row;
    }
    $form['dashboard_table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this
        ->t('No draggable dashboards available.'),
      '#weight' => 120,
    ];
    return $form;
  }

  /**
   * Assign block to a region.
   *
   * @param array $form
   *   Form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   */
  public static function assignBlock(array &$form, FormStateInterface $form_state) {

    // Save block entity.
    $settings = $form_state
      ->getValue('settings');
    $region = $form_state
      ->getValue('region');
    $dashboard_id = $form_state
      ->getValue('dashboard_id');
    $block_id = $form_state
      ->getValue('id');
    $obj = $form_state
      ->getBuildInfo()['callback_object'];

    /** @var \Drupal\block\Entity\Block $block */
    $block = $obj
      ->getEntity();
    $block
      ->set('id', $block_id);
    $block
      ->set('region', DashboardEntityInterface::BASE_REGION_NAME);
    $block
      ->set('settings', $settings);
    $block
      ->enable();
    $block
      ->save();

    /** @var \Drupal\draggable_dashboard\Entity\DashboardEntity $dashboard */
    $dashboard = DashboardEntity::load($dashboard_id);
    $blocks = json_decode($dashboard
      ->get('blocks'), TRUE);
    $relationFounded = FALSE;
    if (!empty($blocks)) {
      foreach ($blocks as $key => $relation) {
        if ($relation['bid'] == $block_id) {
          $blocks[$key]['cln'] = (int) $region;
          $relationFounded = TRUE;
          break;
        }
      }
    }
    if (!$relationFounded) {
      $blocks[] = [
        'bid' => $block_id,
        'cln' => (int) $region,
        'position' => 0,
      ];
    }

    // Save relation.
    $dashboard
      ->set('blocks', json_encode($blocks))
      ->save();

    // Redirect to manage blocks screen.
    $form_state
      ->setRedirect('draggable_dashboard.manage_dashboard', [
      'did' => $dashboard_id,
    ]);
  }

  /**
   * Delete block.
   *
   * @param string $did
   *   Dashboard Id.
   * @param string $bid
   *   Block Id.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect response back to dashboard.
   */
  public function deleteBlock($did, $bid) {

    /** @var \Drupal\draggable_dashboard\Entity\DashboardEntity $dashboard */
    $dashboard = $this->entityTypeManager
      ->getStorage('dashboard_entity')
      ->load($did);
    $blocks = json_decode($dashboard
      ->get('blocks'), TRUE);
    if (!empty($blocks)) {
      foreach ($blocks as $key => $relation) {
        if ($relation['bid'] == $bid) {
          $block = Block::load($relation['bid']);
          $block
            ->delete();
          unset($blocks[$key]);
        }
      }
    }

    // Delete block relation.
    $dashboard
      ->set('blocks', json_encode($blocks))
      ->save();
    $manageURL = Url::fromRoute('draggable_dashboard.manage_dashboard', [
      'did' => $did,
    ]);
    $response = new RedirectResponse($manageURL
      ->toString());
    return $response
      ->send();
  }

  /**
   * Returns a set of nodes' last read timestamps.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The JSON response.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   */
  public function updateBlockPositions(Request $request) {
    if ($this
      ->currentUser()
      ->isAnonymous()) {
      throw new AccessDeniedHttpException();
    }
    $did = $request->request
      ->get('did');
    $blocks = $request->request
      ->get('blocks');

    /** @var \Drupal\draggable_dashboard\Entity\DashboardEntity $dashboard */
    $dashboard = $this->entityTypeManager
      ->getStorage('dashboard_entity')
      ->load($did);
    $dBlocks = json_decode($dashboard
      ->get('blocks'), TRUE);
    if (!isset($blocks) && empty($dashboard)) {
      throw new NotFoundHttpException();
    }

    // Update dashboard blocks positions.
    foreach ($dBlocks as $key => $dBlock) {
      foreach ($blocks as $bid => $relation) {
        if ($dBlock['bid'] == $bid) {
          $dBlocks[$key]['cln'] = $relation['region'];
          $dBlocks[$key]['position'] = $relation['order'];
        }
      }
    }
    $dashboard
      ->set('blocks', json_encode($dBlocks))
      ->save();
    return new JsonResponse([
      'success' => TRUE,
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
DraggableDashboardController::adminOverview public function Displays the draggable dashboard administration overview page.
DraggableDashboardController::assignBlock public static function Assign block to a region.
DraggableDashboardController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
DraggableDashboardController::deleteBlock public function Delete block.
DraggableDashboardController::updateBlockPositions public function Returns a set of nodes' last read timestamps.
DraggableDashboardController::__construct public function DraggableDashboardController constructor.
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.