Sep 12, 2019 in Drupal 8, Snippets

A thing that is very nice about drupal 8 is the flexibility of views In this tutorial, a snippet about how to show a 'total' count of results of some number fields of a table. 

How do I show the total result row in drupal 8? I created this snippet to show you how to do it:

use Drupal\views\ViewExecutable;

function helper_views_pre_render(ViewExecutable $view){
  if ($view->id() == "numbers" && $view->current_display == 'page_1') {
    $total = 0;
    foreach ($view->result as $value) {
      $number = $value->_entity->get('field_number')->value;
      $total += $number;
    }
    $view->attachment_after = [
      '#markup' => '<table class="table cols-0"><tr><td>Total:</td><td>'.$total.'</td></tr></table>',
      '#allowed_tags' => ['table','tr','td']
    ];
  }
}