You are here

public function ViewsExposedFilterBlocksBlock::build in Views exposed filter blocks 8

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/ViewsExposedFilterBlocksBlock.php, line 78

Class

ViewsExposedFilterBlocksBlock
Provides a separate views exposed filter block.

Namespace

Drupal\views_exposed_filter_blocks\Plugin\Block

Code

public function build() {
  $view_display = $this->configuration['view_display'];
  if (!empty($view_display)) {
    list($view_id, $display_id) = explode(':', $view_display);
    if (empty($view_id) || empty($display_id)) {
      return;
    }
    $view = Views::getView($view_id);
    if (!empty($view)) {
      $view
        ->setDisplay($display_id);
      $view
        ->initHandlers();
      $form_state = (new FormState())
        ->setStorage([
        'view' => $view,
        'display' => &$view->display_handler->display,
        'rerender' => TRUE,
      ])
        ->setMethod('get')
        ->setAlwaysProcess()
        ->disableRedirect();
      $form_state
        ->set('rerender', NULL);
      $form = \Drupal::formBuilder()
        ->buildForm('\\Drupal\\views\\Form\\ViewsExposedForm', $form_state);

      // Override form action URL in order to allow to place the exposed form block on a different page as the view results
      if ($view->display_handler
        ->getOption('link_display') == 'custom_url' && !empty($view->display_handler
        ->getOption('link_url'))) {
        $form['#action'] = $view->display_handler
          ->getOption('link_url');
      }
      return $form;
    }
    else {
      $error = $this
        ->t('View "%view_id" or its given display: "%display_id" doesn\'t exist. Please check the views exposed filter block configuration.', [
        '%view_id' => $view_id,
        '%display_id' => $display_id,
      ]);
      \Drupal::logger('type')
        ->error($error);
      return [
        '#type' => 'inline_template',
        '#template' => '{{ error }}',
        '#context' => [
          'error' => $error,
        ],
      ];
    }
  }
}