I am trying to display form data as a line chart. I am running Drupal 9 in Lando. I am using Charts 5.0.x w/ the Highcharts submodule. I installed the Highcharts JS library using composer. This is the relevant code.
.libraries.yml
highcharts:
js:
/libraries/highcharts/highcharts.js: { }
dependencies:
- core/jquery
.module
function stats_degrees_theme() {
return [
'mychart_template' => [
'variables' => ['chart_var' => NULL],
],
];
}
.routing.yml
stats_degrees.render_form:
path: '/statistics/stats-degrees'
defaults:
_title: 'Engineering and Physical Science Degrees Earned by Members of Underrepresented Groups'
_form: '\Drupal\stats_degrees\Form\StatsDegreesForm'
requirements:
_permission: 'access content'
.html.twig
{# stats_degrees/templates/mychart-template.html.twig #}
{{ attach_library('stats_degrees/highcharts') }}
<div id='container' style='width:100%;height:100%;'>
{{ chart_var | raw }}
</div>
Submission handler
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRebuild();
}
Form builder
if ($form_state->isRebuilding()) {
// get the form data and build the chart
// get twig template
$form['#theme'] = 'mychart_template';
$form['#attached'] = array(
'library' => array('stats_degrees/highcharts')
);
$form['#chart_var'] = $rendered_chart;
}
The template is rendered without chart. When I look at the HTML markup, I see the rendered chart code in chart_var and this is in the console.
Uncaught ReferenceError: Highcharts is not defined at js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:4396
js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:128 Uncaught TypeError: $(...).highcharts is not a function at HTMLDivElement.
[anonymous] (js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:4373
at Function.each (js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:2)
at S.fn.init.each (js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:2)
at Object.attach (js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:4370)
at js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:139
at Array.forEach ()
at Object.Drupal.attachBehaviors (js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:136)
at js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:365
at HTMLDocument.listener (js_fLkad5FjTCYgrjWIVyhfUxVUTz4-TXopB2EJOzHz820.js:353)
When I drill down into the error I see it is failing here.
(Highcharts)})(function(w){(function(b){function r(b,a){this.init(b,a)} var v=b.CenteredSeriesMixin,u=b.each,n=b.extend,q=b.merge,g=b.splat;n(r.prototype,{coll:"pane",init:function(b,a){this.chart=a;this.background=[];a.pane.push(this);this.setOptions(b)},setOptions:function(b){this.options=q(this.defaultOptions,this.chart.angular?{background:{}}:void 0,b)},render:function(){var b=this.options,a=this.options.background,c=this.chart.renderer;
Am I loading the Highcharts library correctly?