0

I'm loading a variable list of blocks. In some cases these blocks are a views_block type. When I load a views_block, the viewsblockbase provides the protected View object, but does not provide a method to retrieve it.

How would I go about retrieving the full view object from a views_block?

I considered a ViewsBlock::Create() approach however this would be redundant which Im trying to avoid. Likewise, I have the view_id and display_id but would rather not Views::GetView() when the object is already sitting right there in the loaded block.

snippet

<?php

public function buildDashboard() {
  // $block_instance = new DashboardBlockManager;
  $block_instance = \Drupal::service('plugin.manager.block');
  $blocks = $this->getBlocks();
  foreach ($blocks as $region => $region_blocks) {
    foreach ($region_blocks as $index => $block_id) {

      //$block_id example views_block:dashboard_tasks_by_assignee-block_1

      $load_block = $block_instance->createInstance($block_id);

      $title = $load_block->label();
      $build_block = $load_block->build();
      $build_block['#block_title'] = $title;

      //check the plugin type
      $definition = $load_block->getPluginDefinition();

      if ($definition['id'] == 'views_block') {
        //cant do this
          $view = $load_block->view;
      }
}
0

I think there is no way to get the the view Object directly it's protected property and there is no method to get it: From ViewsBlockBase

/**
* The View executable object.
*
* @var \Drupal\views\ViewExecutable
*/
protected $view;

But there is a way first get the view id from the DerivativeId and then load the view here is a code snippet below:

  use Drupal\views\ViewExecutable;

  $blockManager = \Drupal::service('plugin.manager.block');
  $contextRepository = \Drupal::service('context.repository');
  // Get blocks definition.
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());
  $views_blocks = [];
  foreach ($definitions as $id => $definition) {
    $id_type = explode(':', $id);
    if ($id_type[0] == 'views_block') {
      /** @var \Drupal\views\Plugin\Block\ViewsBlock $viewsBlock */
      $viewsBlock = $blockManager->createInstance($id);
      $derivativeId = $viewsBlock->getDerivativeId();
      $derivativeId_exploded = explode('-', $derivativeId);
      $view_id = $derivativeId_exploded[0];
      $view = Views::getView($view_id);
      $views_blocks[] = $view;
    }
  }

I hope that helps.

1
  • Thats was what I was trying to avoid, but I suppose if that's what needs to be done so be it. thanks – Matt Campbell Apr 1 '19 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.