- Issue created by @introfini
- 🇵🇹Portugal introfini
introfini → changed the visibility of the branch 3516325-add-support-for to hidden.
- 🇵🇹Portugal introfini
Please review the MR.
Here's an example of how it can be used to calculate the sum of a duration field:
/** * Implements hook_views_aggregation_functions_info(). */ function bloom_custom_views_aggregation_functions_info(): array { $functions = [ 'views_aggregator_group_sum_duration' => [ 'group' => t('Group Duration field Sum'), 'column' => t('Group Duration field Sum'), 'is_renderable' => TRUE, ], ]; return $functions; } /** * Aggregates a field group as the sum of duration fields. * * @param array $groups * An array of groups of rows, each group indexed by group value. * @param \Drupal\views\Plugin\views\field\FieldHandlerInterface $field_handler * The handler for the view column to sum groups in. * * @return array * An array of values, one for each group, plus the 'column' group. */ function views_aggregator_group_sum_duration(array $groups, FieldHandlerInterface $field_handler): array { $values = []; $total_seconds_all_groups = 0.0; $duration_service = \Drupal::service('duration_field.service'); foreach ($groups as $group => $rows) { $sum = 0.0; foreach ($rows as $num => $row) { $cell = views_aggregator_get_cell($field_handler, $num, FALSE); if ($cell !== FALSE) { // Convert duration string to DateInterval $date_interval = $duration_service->getDateIntervalFromDurationString($cell); // Convert to total seconds $total_seconds = $duration_service->getSecondsFromDateInterval($date_interval); // Convert to hours $sum += $total_seconds / 3600; } } // Track the total seconds for all groups combined $total_seconds_all_groups += $sum * 3600; // Convert hours back to seconds // Convert hours back to duration string for this group $total_minutes = round($sum * 60); $hours = floor($total_minutes / 60); $minutes = $total_minutes % 60; // Create duration array with h:i granularity $duration = [ 'y' => 0, 'm' => 0, 'd' => 0, 'h' => $hours, 'i' => $minutes, 's' => 0, ]; $values[$group] = $duration_service->convertDateArrayToDurationString($duration); } // Now create the column total from all groups combined $total_minutes_all = round($total_seconds_all_groups / 60); $hours_all = floor($total_minutes_all / 60); $minutes_all = $total_minutes_all % 60; $column_duration = [ 'y' => 0, 'm' => 0, 'd' => 0, 'h' => $hours_all, 'i' => $minutes_all, 's' => 0, ]; $values['column'] = $duration_service->convertDateArrayToDurationString($column_duration); return $values; }