You are here

class ChartsApiExample in Charts 5.0.x

Same name and namespace in other branches
  1. 8.4 modules/charts_api_example/src/Controller/ChartsApiExample.php \Drupal\charts_api_example\Controller\ChartsApiExample
  2. 8.3 modules/charts_api_example/src/Controller/ChartsApiExample.php \Drupal\charts_api_example\Controller\ChartsApiExample

Charts Api Example.

Hierarchy

Expanded class hierarchy of ChartsApiExample

1 string reference to 'ChartsApiExample'
charts_api_example.services.yml in modules/charts_api_example/charts_api_example.services.yml
modules/charts_api_example/charts_api_example.services.yml
1 service uses ChartsApiExample
charts.api_example in modules/charts_api_example/charts_api_example.services.yml
Drupal\charts_api_example\Controller\ChartsApiExample

File

modules/charts_api_example/src/Controller/ChartsApiExample.php, line 14

Namespace

Drupal\charts_api_example\Controller
View source
class ChartsApiExample extends ControllerBase {

  /**
   * The charts settings.
   *
   * @var \Drupal\charts\Services\ChartsSettingsServiceInterface
   */
  protected $chartSettings;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The UUID service.
   *
   * @var \Drupal\Component\Uuid\UuidInterface
   */
  protected $uuidService;

  /**
   * Construct.
   *
   * @param \Drupal\charts\Services\ChartsSettingsServiceInterface $chartSettings
   *   The charts settings.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Component\Uuid\UuidInterface $uuidService
   *   The UUID service.
   */
  public function __construct(ChartsSettingsServiceInterface $chartSettings, MessengerInterface $messenger, UuidInterface $uuidService) {
    $this->chartSettings = $chartSettings
      ->getChartsSettings();
    $this->messenger = $messenger;
    $this->uuidService = $uuidService;
  }

  /**
   * Display the dashboard of charts.
   *
   * @return array
   *   Array to render.
   */
  public function display() {

    /*
     * If you do not set a library specifically in your render array, Charts
     * will use your default. But you do need to set your default library.
     */
    $library = $this->chartSettings['library'];
    if (empty($library)) {
      $this->messenger
        ->addError($this
        ->t('You need to first configure Charts default settings'));
      return [];
    }

    // This is a container for all the charts below.
    $charts_container = [
      '#type' => 'container',
      'content' => [],
    ];

    /* Listing all the default chart types except 'gauge' and 'scatter'
     * (they come later).
     */
    $chart_types = [
      'area',
      'bar',
      'column',
      'line',
      'spline',
      'pie',
      'donut',
    ];

    // Define a series to be used in multiple examples.
    $series = [
      '#type' => 'chart_data',
      '#title' => $this
        ->t('5.0.x'),
      '#data' => [
        257,
        235,
        325,
        340,
      ],
      '#color' => '#1d84c3',
    ];

    // Define an x-axis to be used in multiple examples.
    $xaxis = [
      '#type' => 'chart_xaxis',
      '#title' => $this
        ->t('Months'),
      '#labels' => [
        $this
          ->t('January 2021'),
        $this
          ->t('February 2021'),
        $this
          ->t('March 2021'),
        $this
          ->t('April 2021'),
      ],
    ];

    // Define a y-axis to be used in multiple examples.
    $yaxis = [
      '#type' => 'chart_yaxis',
      '#title' => $this
        ->t('Number of Installs'),
    ];

    // Iterate through the chart types and build a chart for each.
    foreach ($chart_types as $type) {
      $charts_container['content'][$type] = [
        '#type' => 'chart',
        '#tooltips' => $this->chartSettings['display']['tooltips'],
        '#title' => $this
          ->t('@library @type Chart', [
          '@library' => ucfirst($library),
          '@type' => ucfirst($type),
        ]),
        '#chart_type' => $type,
        'series' => $series,
        'x_axis' => $xaxis,
        'y_axis' => $yaxis,
        '#raw_options' => [],
      ];
    }

    // Column chart with two series.
    $charts_container['content']['two_series_column'] = [
      '#type' => 'chart',
      '#tooltips' => $this->chartSettings['display']['tooltips'],
      '#title' => $this
        ->t('@library Column Chart (Two Series)', [
        '@library' => ucfirst($library),
      ]),
      '#chart_type' => 'column',
      'series_one' => $series,
      'series_two' => [
        '#type' => 'chart_data',
        '#title' => $this
          ->t('8.x-3.x'),
        '#data' => [
          4330,
          4413,
          4212,
          4431,
        ],
        '#color' => '#77b259',
      ],
      'x_axis' => $xaxis,
      'y_axis' => $yaxis,
      '#raw_options' => [],
    ];

    // Stacked Area Chart from a local CSV file.
    $file_contents = $this
      ->getCsvContents();
    $charts_container['content']['from_csv_file'] = [
      '#type' => 'chart',
      '#tooltips' => $this->chartSettings['display']['tooltips'],
      '#title' => $this
        ->t('@library Stacked Area Chart from CSV File', [
        '@library' => ucfirst($library),
      ]),
      '#chart_type' => 'area',
      'series_seven_2' => [
        '#type' => 'chart_data',
        '#title' => $this
          ->t('7.x-2.x'),
        // Using array_reverse because my file is desc rather than asc.
        '#data' => array_reverse($file_contents['7.x-2.x']),
        '#color' => '#76b7b2',
      ],
      'series_eight_three' => [
        '#type' => 'chart_data',
        '#title' => $this
          ->t('8.x-3.x'),
        '#data' => array_reverse($file_contents['8.x-3.x']),
        '#color' => '#edc949',
      ],
      'series_five_zero' => [
        '#type' => 'chart_data',
        '#title' => $this
          ->t('5.0.x'),
        '#data' => array_reverse($file_contents['5.0.x']),
        '#color' => '#ff9da7',
      ],
      'x_axis' => [
        '#type' => 'chart_xaxis',
        '#title' => $this
          ->t('Week'),
        '#labels' => array_reverse($file_contents['Week']),
      ],
      'y_axis' => [
        '#type' => 'chart_yaxis',
        '#title' => $this
          ->t('Number of Installs'),
      ],
      '#stacking' => TRUE,
    ];
    if ($library === 'chartjs') {

      // A real-life #raw_options use-case.
      $charts_container['content']['from_csv_file']['#raw_options'] = [
        'options' => [
          'scales' => [
            'x' => [
              'ticks' => [
                'autoSkip' => TRUE,
              ],
            ],
          ],
        ],
      ];
    }
    elseif ($library === 'billboard' || $library === 'c3') {
      $charts_container['content']['from_csv_file']['#raw_options'] = [
        'axis' => [
          'x' => [
            'tick' => [
              'culling' => TRUE,
            ],
          ],
        ],
      ];
    }

    // Stacked column chart with two series.
    $charts_container['content']['stacked_two_series_column'] = [
      '#type' => 'chart',
      '#tooltips' => $this->chartSettings['display']['tooltips'],
      '#title' => $this
        ->t('@library Stacked Column Chart (Two Series)', [
        '@library' => ucfirst($library),
      ]),
      '#chart_type' => 'column',
      'series_one' => $series,
      'series_two' => [
        '#type' => 'chart_data',
        '#title' => $this
          ->t('8.x-3.x'),
        '#data' => [
          4330,
          4413,
          4212,
          4431,
        ],
        '#color' => '#77b259',
      ],
      'x_axis' => $xaxis,
      'y_axis' => $yaxis,
      '#stacking' => TRUE,
      '#raw_options' => [],
    ];

    // Combination chart (column and line).
    $charts_container['content']['combo'] = [
      '#type' => 'chart',
      '#tooltips' => $this->chartSettings['display']['tooltips'],
      '#title' => $this
        ->t('@library Combination Chart', [
        '@library' => ucfirst($library),
      ]),
      '#chart_type' => 'column',
      'series_one' => $series,
      'series_two' => [
        '#type' => 'chart_data',
        '#chart_type' => 'line',
        '#title' => $this
          ->t('8.x-3.x'),
        '#data' => [
          4330,
          4413,
          4212,
          4431,
        ],
        '#color' => '#77b259',
      ],
      'x_axis' => $xaxis,
      'y_axis' => $yaxis,
      '#raw_options' => [],
    ];

    // Radar chart. Not supported by C3.js or Google Charts (natively).
    if (!in_array($library, [
      'c3',
      'google',
    ])) {
      $charts_container['content']['radar'] = [
        '#type' => 'chart',
        '#tooltips' => $this->chartSettings['display']['tooltips'],
        '#title' => $this
          ->t('@library Radar Chart', [
          '@library' => ucfirst($library),
        ]),
        '#chart_type' => 'line',
        'series' => $series,
        'x_axis' => $xaxis,
        'y_axis' => $yaxis,
        '#polar' => TRUE,
        '#raw_options' => [],
      ];
    }

    // Gauge chart. Not yet supported by Chart.js (as of 3.5.1).
    if ($library !== 'chartjs') {
      $charts_container['content']['gauge'] = [
        '#type' => 'chart',
        '#title' => $this
          ->t('@library Gauge Chart', [
          '@library' => ucfirst($library),
        ]),
        '#chart_type' => 'gauge',
        '#gauge' => [
          'green_to' => 100,
          'green_from' => 75,
          'yellow_to' => 74,
          'yellow_from' => 50,
          'red_to' => 49,
          'red_from' => 0,
          'max' => 100,
          'min' => 0,
        ],
        'series' => [
          '#type' => 'chart_data',
          '#title' => $this
            ->t('Speed'),
          '#data' => [
            65,
          ],
        ],
        '#raw_options' => [],
      ];
    }

    // Scatter chart.
    $charts_container['content']['scatter'] = [
      '#type' => 'chart',
      '#tooltips' => $this->chartSettings['display']['tooltips'],
      '#title' => $this
        ->t('@library Scatter Chart', [
        '@library' => ucfirst($library),
      ]),
      '#chart_type' => 'scatter',
      'series' => [
        '#type' => 'chart_data',
        '#title' => $this
          ->t('Group 1'),
        '#data' => [
          [
            162.2,
            51.8,
          ],
          [
            164.5,
            58.0,
          ],
          [
            160.5,
            49.6,
          ],
          [
            154.0,
            65.0,
          ],
        ],
      ],
      'x_axis' => [
        '#type' => 'chart_xaxis',
        '#title' => $this
          ->t('Height'),
      ],
      'y_axis' => [
        '#type' => 'chart_yaxis',
        '#title' => $this
          ->t('Weight'),
      ],
      '#stacking' => TRUE,
      '#raw_options' => [],
    ];
    return $charts_container;
  }

  /**
   * @return array $all_rows
   */
  private function getCsvContents() {
    $file_path = drupal_get_path('module', 'charts_api_example');
    $file_name = $file_path . '/fixtures/charts_api_example_file.csv';
    $handle = fopen($file_name, 'r');
    $all_rows = [];
    while ($row = fgetcsv($handle)) {
      $all_rows['Week'][] = $row[0];
      $all_rows['7.x-2.x'][] = (int) $row[4];
      $all_rows['8.x-3.x'][] = (int) $row[6];
      $all_rows['5.0.x'][] = (int) $row[8];
    }
    fclose($handle);
    return $all_rows;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('charts.settings'), $container
      ->get('messenger'), $container
      ->get('uuid'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ChartsApiExample::$chartSettings protected property The charts settings.
ChartsApiExample::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
ChartsApiExample::$uuidService protected property The UUID service.
ChartsApiExample::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
ChartsApiExample::display public function Display the dashboard of charts.
ChartsApiExample::getCsvContents private function
ChartsApiExample::__construct public function Construct.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.