Skip to main content

Drupal 9: Gettings views in a custom block with DI using the Drupal Core Render Class

Drupal 9 gives you a lot of flexibility to render a custom view in different ways either directly in php or with twig and the twig_tweak module for example.

This example here shows how to render 2 custom views blocks get the result of each of them and then render the 2 of them with an extra summary block that is created from the sum of the 2 custom views blocks.

<?php

namespace Drupal\pixelthis\Plugin\Block;

use Drupal\Core\Block\BlockBase;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Render\Renderer;

/**
 * Provides a 'TotalBlock' block.
 *
 * @Block(
 *  id = "total_block",
 *  admin_label = @Translation("Total Summary block"),
 * )
 */
class TotalBlock extends BlockBase  implements ContainerFactoryPluginInterface {

  /**
   * @var Renderer
   */
  protected $renderer;

  /**
   * Constructs a new BookNavigationBlock instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Renderer $renderer) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('renderer')
    );
  }


  /**
   * {@inheritdoc}
   */
  public function build() {

    $current_uid =
      \Drupal::currentUser()->id();
    $data = [];

    $data['saldo'] = $this->getViewData($current_uid, 'saldo', 'block_2', 'node_field_data_a');
    $data['payment'] = $this->getViewData($current_uid, 'payments', 'block_1', 'node__field_amount_field_amount_value');

    $total_label = $this->t('Saldo');
    $total_amount = $data['saldo']['total'] + $data['payment']['total'];
    $data['total'] = [
      'amount' => $total_amount,
      'label' => $total_label,
      'html' => $total_label . ': ' . $total_amount,
    ];

    return [
      '#theme' => 'total_block',
      '#data' => $data,
    ];
  }

  private function getViewData(int $uid, string $view_id, string $view_display, string $total_field) {

    $data = [
      'html' => '',
      'total' => NULL
    ];
    // Get and loop through the View $view_id
    $view = \Drupal\views\Views::getView($view_id);
    $view->setDisplay($view_display);
    $view->execute();

    // Get the results of the view.
    $view_result = $view->result;

    // Check if the view is not empty and return results.
    if (!empty($view_result)) {
      $view = views_embed_view($view_id, $view_display, $uid);
      $view_html = $this->renderer->render($view);
      $data['html'] = $view_html;

      // If the view returns results...
      foreach ($view_result as $row) {

        if ($row->$total_field) {
          $data['total'] = $row->$total_field;
        }
      }
    }

    return $data;
  }
}

With the views_embed_view i can get the custom view and with the $this->renderer->render($view) i can render the markup of the view.

 

views php dependency injection