View source
<?php
namespace Drupal\dashboards\Plugin\Dashboard;
use Drupal\Core\StringTranslation\StringTranslationTrait;
trait ChartTrait {
use StringTranslationTrait;
protected $labels = [];
protected $rows = [];
protected $type = 'pie';
protected $empty = FALSE;
public function setChartType($chart) : void {
if (!in_array($chart, array_keys($this
->getAllowedStyles()))) {
throw new \InvalidArgumentException($this
->t('Chart type @chart not allowed', [
'@chart' => $chart,
]));
}
$this->type = $chart;
}
public function addLabel($label) : void {
$this->labels[] = $label;
}
public function getAllowedStyles() : array {
return [
'line' => $this
->t('Lines'),
'pie' => $this
->t('Pies'),
'bar' => $this
->t('Bars'),
'radar' => $this
->t('Radar'),
'polarArea' => $this
->t('Polar area'),
'doughnut' => $this
->t('Doughnut'),
'bubble' => $this
->t('Bubbles'),
];
}
public function setLabels(array $labels) : void {
$this->labels = $labels;
}
public function addRow(array $row) : void {
$this->rows[] = $row;
}
public function setRows(array $rows) : void {
$this->rows = $rows;
}
public function setEmpty(bool $empty) : void {
$this->empty = $empty;
}
public function renderChart(array $conf = [], bool $plain = FALSE) : array {
if (count($this->rows) == 0) {
return [
'#markup' => $this
->t('No data found'),
];
}
$table = [
'#type' => 'table',
'#header' => $this->labels,
'#rows' => $this->rows,
'#attributes' => [
'class' => [
'dashboard-table',
'table',
],
],
'#attached' => [
'library' => [
'dashboards/chart',
],
],
];
$attributes = [
'data-app' => 'chart',
'data-chart-type' => $this->type,
];
if (isset($conf['legend']) && $conf['legend']) {
$attributes['data-chart-display-legend'] = '1';
}
$build = [
'#prefix' => '<div>',
'#suffix' => '</div>',
'chart' => [
'#type' => 'container',
'#attributes' => $attributes,
[
'#type' => 'container',
[
'#type' => 'details',
'#title' => $this
->t('Show data'),
'#open' => FALSE,
'content' => $table,
],
],
],
];
if ($plain == TRUE) {
unset($build['#attributes']);
unset($build['chart']['table']['#attached']);
}
return $build;
}
}