You are here

charts.module in Charts 5.0.x

Charts - Module.

File

charts.module
View source
<?php

/**
 * @file
 * Charts - Module.
 */
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_data().
 */
function charts_views_data() {
  $data['charts_fields']['table']['group'] = t('Charts');
  $data['charts_fields']['table']['join'] = [
    // Exist in all views.
    '#global' => [],
  ];
  $data['charts_fields']['field_charts_fields_scatter'] = [
    'title' => t('Scatter Field'),
    'help' => t('Use this field for your data field in a scatter plot.'),
    'field' => [
      'id' => 'field_charts_fields_scatter',
    ],
  ];
  $data['charts_fields']['field_exposed_chart_type'] = [
    'title' => t('Exposed Chart Type'),
    'help' => t('Use this field for exposing chart type.'),
    'field' => [
      'id' => 'field_exposed_chart_type',
    ],
  ];
  return $data;
}

/**
 * Implements hook_theme().
 */
function charts_theme($existing, $type, $theme, $path) {
  return [
    'charts_chart' => [
      'render element' => 'element',
    ],
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function template_preprocess_charts_chart(&$variables) {
  $element = $variables['element'];
  $attributes = $element['#attributes'];
  $attributes['id'] = $element['#id'];
  $attributes['class'][] = 'chart';
  $variables['content'] = [
    '#type' => 'html_tag',
    '#tag' => 'div',
    '#attributes' => $attributes,
    '#value' => isset($element['#chart']) ? $element['#chart'] : '',
  ];
}

/**
 * Implements hook_views_pre_view().
 */
function charts_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $hasFields = array_key_exists('fields', $view->display_handler->options);
  if ($hasFields) {
    $fields = $view->display_handler
      ->getOption('fields');
    $hasViewsFieldsOnOffHandler = FALSE;
    foreach ($fields as $field) {
      if (array_key_exists('plugin_id', $field)) {
        if ($field['plugin_id'] == 'field_exposed_chart_type') {
          $hasViewsFieldsOnOffHandler = TRUE;
        }
      }
    }
    if ($hasViewsFieldsOnOffHandler) {

      // Grab the type that has been submitted.
      $params = \Drupal::request()->query
        ->all();

      // This is for a GET request.
      // If the view is submitted through AJAX, like in view preview, it will be
      // a POST request. Merge the parameter arrays and we will get our values.
      $postParams = \Drupal::request()->request
        ->all();
      $params = array_merge($params, $postParams);
      foreach ($params as $key => $value) {
        if (strpos($key, 'ct') === 0) {
          $view->storage
            ->set('exposed_chart_type', $value);
        }
      }
      $view->element['#cache']['contexts'][] = 'url';
    }
  }
}