Skip to content

Instantly share code, notes, and snippets.

@tastensolo
Created July 4, 2018 12:34
Show Gist options
  • Save tastensolo/5d4718fe1e341a6f642e4244cd997526 to your computer and use it in GitHub Desktop.
Save tastensolo/5d4718fe1e341a6f642e4244cd997526 to your computer and use it in GitHub Desktop.
Create beautiful JavaScript charts with one line of FluidTYPO3
<?php
namespace TYPO3Fluid\Fluid\ViewHelpers;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
/**
* Create beautiful JavaScript charts
*
* = Examples =
*
* <f:format.raw>
* <w:chartkick chartType="ColumnChart" dataSource="{
* 'dataLabel1': 1,
* 'dataLabel2': 2,
* 'dataLabel3': 3,
* 'dataLabel4': 4
* }"/>
* </f:format.raw>
*
* @license The GNU General Public License
* @link http://www.gnu.org/copyleft/gpl.html
*/
class ChartkickViewHelper extends AbstractViewHelper
{
use CompileWithRenderStatic;
protected $options = [];
protected static $chartId = 0;
const DIV = "<div id=\"%s\" style=\"height: %s; text-align: center; color: #999; line-height: %s; font-size: 14px;
font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;\">Loading...</div>";
const SCRIPT = "<script type='application/javascript'>new Chartkick.%s('%s', %s);</script>";
/**
* Initialize arguments.
*
* @return void
* @api
*/
public function initializeArguments()
{
$this->registerArgument(
'chartType',
'string',
'Choose the type of layout for chart-rendering',
true,
'LineChart'
);
$this->registerArgument(
'dataSource',
'mixed',
'Array or string list of items to show in chartType.',
true,
''
);
$this->registerArgument(
'options',
'array',
'Rendering options for chartType',
false,
''
);
}
/**
* Manipulate headerData to load script library's for getting chartkick.js
* Renders a beautiful JavaScript chart for given dataSource
*
* @return string The rendered markup-string
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
{
$GLOBALS['TSFE']->additionalHeaderData['chartkick'] =
' <script src="https://cdnjs.cloudflare.com/ajax/libs/chartkick/2.2.1/chartkick.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>';
// $options = chartkick_deep_merge(Chartkick.options, options);
$elementId = $arguments['options']['id'] ?? 'chart-'.(++self::$chartId);
$height = $arguments['options']['height'] ?? '300px';
if (gettype($arguments['dataSource']) === 'string') {
$encodedData = '"' . $arguments['dataSource'] . '"';
} else {
$encodedData = json_encode($arguments['dataSource']);
}
$str = sprintf(self::DIV, $elementId, $height, $height);
$str .= sprintf(self::SCRIPT, $arguments['chartType'], $elementId, $encodedData);
return $str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment