1

The documentation on Drupal.behaviours suggests that local settings can be passed to Drupal's JavaScript behaviors.

Rather than hard coding my series data into my function:

series: [{
    name: 'Jane',
    data: [1, 5, 4]
}, {
    name: 'John',
    data: [3, 1, 2]
}]

how can I pass this series data to my function as settings, directly after the context?

JS code (my_highcharts.js)

(function ($) {

Drupal.behaviors.my_highcharts = {
  attach: function (context, settings) {
    $('#drupal_behaviours').highcharts({
      chart: {
          type: 'bar'
      },
      title: {
          text: 'Drupal.behaviors'
      },
      colors: ['#50b432', '#ed561b'],
      xAxis: {
          categories: ['Apples', 'Bananas', 'Oranges']
      },
      yAxis: {
          title: {
              text: 'Fruit eaten'
          }
      },
      series: [{
          name: 'Jane',
          data: [1, 5, 4]
      }, {
          name: 'John',
          data: [3, 1, 2]
      }]
    });
  }
};

})(jQuery);

Module code

drupal_add_js(drupal_get_path('module', 'my_highcharts') . '/highcharts.js');
return array('#markup' => '<div id="drupal_behaviours" style="width:100%; height:400px;"></div>');
2

For one thing I would suggest no using #drupal_behaviours as a HTML element ID because it doesn't describe that element in any way.

It would more logically be called #chart or #highchart or something like that.

To add settings you can use drupal_add_js() (there are examples on that docs page) like this (in your custom module in PHP):

// add the series' to a javascript setting.
$series = array(
  array(
    'name' => 'Jane',
    'data' => array(1, 5, 4),
  ),
  array(
    'name' => 'John',
    'data' => array(3, 1, 2),
  ),
);
drupal_add_js(array(
  'moduleName' => array(
    'series' => $series
  )
), 'setting');

Then in the js you can access it like this:

(function ($) {

Drupal.behaviors.my_highcharts = {
  attach: function (context, settings) {
    $('#drupal_behaviours').highcharts({
      chart: {
          type: 'bar'
      },
      title: {
          text: 'Drupal.behaviors'
      },
      colors: ['#50b432', '#ed561b'],
      xAxis: {
          categories: ['Apples', 'Bananas', 'Oranges']
      },
      yAxis: {
          title: {
              text: 'Fruit eaten'
          }
      },
      series: settings.moduleName.series
    });
  }
};

})(jQuery);

Note how the settings object in the javascript mimics what you passed into drupal_add_js().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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