problem making a grand total on a page and its attachments

Created on 27 February 2020, about 5 years ago
Updated 19 October 2024, 6 months ago

I have a views that has a page and multiple attachments. each of these view use Table with aggregation options and everything is fine in the display.

but I what to do a grand total of these views/attachment. so I added a myModule_preprocess_views_view__<viewName> in my myModule.theme

I get the views from the variables, and I iterate on all the result of all the view/attachment and make a grand total.

This is where it gets funky, my grand total is not the correct one. the reason being the value of the first element of the view (the page one which all attachments are link) is incorrect in code. it give the value of the sum instead of its value.

to recreate the problem

  • use a content type with a number field
  • create some content (at least 2 elements)
  • create a view (page) for the content type with Table with aggregation options
  • add the number field to the list of field
  • in the setting of the Table with aggregation options for the number field set Apply group function to group and compress and Apply column function to sum
  • create a theme function for the view myTheme_preprocess_views_view__myViewID
  • add the code below and watch the view display in Kint for the value of each row and see that the first element is the sum off all the elements of the view

example
you have 3 content with value

  • 1
  • 2
  • 3

the sum is 6
so in code the list of value will be

  • 6
  • 2
  • 3

    $viewID = "MyView";
    $displayName = "page_1";
    $fieldNum = "field_num";

    $view = \Drupal\views\Views::getView($viewID);
    $view->setOffset(0);
    $view->setDisplay($displayName);  // page_1 usually
    $view->execute();
    $result = $view->result;

    foreach ($result as $key => $value) {

        $entity = $value->_entity;
        $custom_field = $entity->get($fieldNum)->getValue() != NULL ? $entity->get($fieldNum)->getValue()[0]['value'] : 0;
        ksm($custom_field);
    }

even worst when i load the node in code i still get the wrong value
you can add this code at the end of the foreach loop and see it going all wrong again. but always only for the first value.

$node = \Drupal::entityTypeManager()->getStorage('node')->load($entity->id());
ksm($node->get($fieldNum)->getValue()[0]['value']);
πŸ› Bug report
Status

Postponed: needs info

Version

1.0

Component

Code

Created by

πŸ‡¨πŸ‡¦Canada ouelmart

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024