You are here

class ChartsApiExample in Charts 8.4

Same name and namespace in other branches
  1. 8.3 modules/charts_api_example/src/Controller/ChartsApiExample.php \Drupal\charts_api_example\Controller\ChartsApiExample
  2. 5.0.x 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.
   *
   * @return array
   *   Array to render.
   */
  public function display() {
    $library = $this->chartSettings['library'];
    if (empty($library)) {
      $this->messenger
        ->addError($this
        ->t('You need to first configure Charts default settings'));
      return [];
    }

    // If you want to include raw options, you can do so like this.
    // $options = [
    // 'chart' => [
    // 'backgroundColor' => '#000000'
    // ]
    // ];.
    $build = [
      '#type' => 'chart',
      '#chart_type' => $this->chartSettings['type'],
      '#title' => $this
        ->t('Chart title'),
      '#title_position' => 'out',
      '#tooltips' => $this->chartSettings['display']['tooltips'],
      '#data_labels' => $this->chartSettings['data_labels'] ?? '',
      '#colors' => $this->chartSettings['display']['colors'],
      '#background' => $this->chartSettings['display']['background'] ? $this->chartSettings['display']['background'] : 'transparent',
      '#legend' => !empty($this->chartSettings['display']['legend_position']),
      '#legend_position' => $this->chartSettings['display']['legend_position'] ? $this->chartSettings['display']['legend_position'] : '',
      '#width' => $this->chartSettings['display']['dimensions']['width'],
      '#height' => $this->chartSettings['display']['dimensions']['height'],
      '#width_units' => $this->chartSettings['display']['dimensions']['width_units'],
      '#height_units' => $this->chartSettings['display']['dimensions']['height_units'],
      // '#raw_options' => $options,
      '#chart_id' => 'foobar',
    ];
    $categories = [
      'Category 1',
      'Category 2',
      'Category 3',
      'Category 4',
    ];
    $build['xaxis'] = [
      '#type' => 'chart_xaxis',
      '#labels' => $categories,
      '#title' => $this->chartSettings['xaxis']['title'] ? $this->chartSettings['xaxis']['title'] : FALSE,
      '#labels_rotation' => $this->chartSettings['xaxis']['labels_rotation'],
      '#axis_type' => $this->chartSettings['type'],
    ];
    $build['yaxis'] = [
      '#type' => 'chart_yaxis',
      '#title' => $this->chartSettings['yaxis']['title'] ? $this->chartSettings['yaxis']['title'] : '',
      '#labels_rotation' => $this->chartSettings['yaxis']['labels_rotation'],
      '#max' => $this->chartSettings['yaxis']['max'],
      '#min' => $this->chartSettings['yaxis']['min'],
    ];
    $i = 0;
    $build[$i] = [
      '#type' => 'chart_data',
      '#data' => [
        250,
        350,
        400,
        200,
      ],
      '#title' => 'Series 1',
    ];

    // Sample data format.
    $seriesData[] = [
      'name' => 'Series 1',
      'color' => '#0d233a',
      'type' => $this->chartSettings['type'],
      'data' => [
        250,
        350,
        400,
        200,
      ],
    ];
    switch ($this->chartSettings['type']) {
      default:
        $seriesData[] = [
          'name' => 'Series 2',
          'color' => '#8bbc21',
          'type' => 'line',
          'data' => [
            150,
            450,
            500,
            300,
          ],
        ];
        $seriesData[] = [
          'name' => 'Series 3',
          'color' => '#910000',
          'type' => 'area',
          'data' => [
            0,
            0,
            60,
            90,
          ],
        ];
      case 'pie':
      case 'donut':
    }
    foreach ($seriesData as $index => $data) {
      $build[$index] = [
        '#type' => 'chart_data',
        '#data' => $data['data'],
        '#title' => $data['name'],
        '#color' => $data['color'],
        '#chart_type' => $data['type'],
      ];
    }

    // Creates a UUID for the chart ID.
    $chartId = 'chart-' . $this->uuidService
      ->generate();
    $build['#id'] = $chartId;
    return $build;
  }

  /**
   * Display Two.
   *
   * @return array
   *   Array to render.
   */
  public function displayTwo() {
    $chart = [];
    $chart['example_one'] = [
      '#type' => 'chart',
      '#chart_type' => 'column',
    ];
    $chart['example_one']['male'] = [
      '#type' => 'chart_data',
      '#title' => $this
        ->t('Male'),
      '#data' => [
        10,
        20,
        30,
      ],
    ];
    $chart['example_one']['xaxis'] = [
      '#type' => 'chart_xaxis',
      '#title' => $this
        ->t('Month'),
      '#labels' => [
        $this
          ->t('Jan'),
        $this
          ->t('Feb'),
        $this
          ->t('Mar'),
      ],
    ];
    return $chart;
  }

  /**
   * {@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.
ChartsApiExample::displayTwo public function Display Two.
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::$entityManager protected property The entity manager.
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::entityManager Deprecated protected function Retrieves the entity manager service.
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. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator 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. 29
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.