I'm hoping someone can shed some light on this for me. I've been building my first Drupal 8 custom block via a custom module. It was all going well until I've tried to pass some values into javascript. I'm working on some morris.js graphs, and want to display data from a database.

I've tried numerous variations, but can never get the variable to work. BTW, I'm not great at Javascript, so that might be where the flaw lies.

Here is the library definition:

      /libraries/morris/morris.css: {}
    /libraries/morris/morris.min.js: {}
    /libraries/raphael-master/raphael.min.js: {}
    js/custom.js: {}
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Here is the relevant part of the block file:

 $build['#attached']['library'][] = 'module_machine_name/morris';
$build['#attached']['drupalSettings']['module_machine_name']['morris']['memGraph'] = $graph_total;

And here is the js file:

     var infoo;

    (function ($, Drupal, drupalSettings) {
      Drupal.behaviors.module_machine_name = {
        attach: function (context, settings) {

            infoo = drupalSettings.module_machine_name.morris.memGraph;

      element: 'graph',
      data: [
        {x: '2011 Q1', y: infoo, z: 2, a: 6},
        {x: '2011 Q2', y: 2, z: null, a: 1},
        {x: '2011 Q3', y: 0, z: 2, a: 4},
        {x: '2011 Q4', y: 2, z: 4, a: 3}
      xkey: 'x',
      ykeys: ['y', 'z', 'a'],
      labels: ['Y', 'Z', 'A']
    }).on('click', function(i, row){
      console.log(i, row);


})(jQuery, Drupal, drupalSettings);

Can anybody help? Thanks


1 Answer 1


Have you try changing the order?

First load the drupalSettings attachment and after the library?

$build['#attached']['drupalSettings']['module_machine_name']['morris']['memGraph'] = $graph_total;
$build['#attached']['library'][] = 'module_machine_name/morris';
  • This was my first thought as well. Second to that, console.log drupalSettings to see if it is in the structure.
    – Kevin
    Jul 5, 2016 at 13:08
  • Thanks. It wasn't this, but it's now solved. It turns out a small html error - an unclosed strong tag - was stopping it from working for some reason. Thanks for your help.
    – infoo
    Jul 6, 2016 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.