Skip to content

Instantly share code, notes, and snippets.

@reinis-kinkeris
Created April 27, 2017 13:15
Show Gist options
  • Save reinis-kinkeris/fa7f98960e7e681d465f2bea259e53f0 to your computer and use it in GitHub Desktop.
Save reinis-kinkeris/fa7f98960e7e681d465f2bea259e53f0 to your computer and use it in GitHub Desktop.
Drupal 8 - Adding custom Views query plugin which implements new aggregation method (SUM DISTINCT)
<?php
/**
* @file
* Contains \Drupal\my_module\Plugin\views\query\CustomSql.
*/
namespace Drupal\my_module\Plugin\views\query;
use Drupal\views\Plugin\views\query\Sql;
/**
* Views query plugin for an custom SQL query.
*
* @ingroup views_query_plugins
*
* @ViewsQuery(
* id = "views_custom_query",
* title = @Translation("SQL Custom Query"),
* help = @Translation("Query will be generated and run using the Drupal database API.")
* )
*/
class CustomSql extends Sql {
/**
* {@inheritdoc}
*/
public function getAggregationInfo() {
$aggregation_info = parent::getAggregationInfo();
$aggregation_info += [
'sum_distinct' => [
'title' => $this->t('Sum DISTINCT'),
'method' => 'aggregationMethodDistinct',
'handler' => [
'argument' => 'groupby_numeric',
'field' => 'numeric',
'filter' => 'groupby_numeric',
'sort' => 'groupby_numeric',
],
],
];
return $aggregation_info;
}
}
/**
* @implements hook_views_data_alter().
*
* @param array $data
*/
function my_module_views_data_alter(array &$data) {
if (isset($data['my_table'])) {
$data['my_table']['table']['base']['query_id'] = 'views_custom_query';
}
}
@reinis-kinkeris
Copy link
Author

Easiest way to implement new Views aggregation method. Valid until https://www.drupal.org/node/2662548 is implemented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment