Score:0

What is the correct way to load a JavaScript library?

ae flag

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?

Jaypan avatar
de flag
Have you cleared the registry? Does `highcharts.js` show up in the HTML source? Is the path to the `highcharts.js` correct in the HTML source?
cn flag
Yes definitely check the path, the JS files are in a /code folder by default so the path might be wrong. You don't need to register the library yourself BTW, the submodule does that (see charts_highcharts.libraries.yml). Assuming the path to the JS is right and being loaded, I think the next question would be what does `$rendered_chart` contain?
Dorian Winterfeld avatar
ae flag
I have cleared the registry. highcharts.js is under /libraries/highcharts/. That's where composer installed it. When I view source the only reference to highcharts that I see it near the bottom under <script type="application/json" ... charts_highcharts\/highcharts
Dorian Winterfeld avatar
ae flag
$render_chart is too long for this comment but it starts with <div class="charts-highchart chart" data-chart="{&quot;title&quot;:{&quot;useHTML&quot;:true,&quot;text&quot;:&quot;Number of Bachelor\u0027s
Score:0
rs flag

It looks like what's happening is you need to add 'charts_highcharts/highcharts' as a dependency, like so:

highcharts:
  js:
    /libraries/highcharts/highcharts.js: {  }
  dependencies:
    - core/jquery
    - charts_highcharts/highcharts

(If this doesn't work, try 'charts_highcharts/charts_highcharts' instead of 'charts_highcharts/highcharts')

Dorian Winterfeld avatar
ae flag
Unfortunately I am getting the same behavior with the same error message "Uncaught Reference Error: Highcharts is not defined".
Dorian Winterfeld avatar
ae flag
Follow-up; the JS errors were only occurring when logged-in i.e. the chart only displayed when logged out. When I switched the theme from Bartik to Claro that issue was resolved as well. The chart now displays when logged in or not.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.