Passing Configurable Variable to JavaScript in Drupal
I needed to make a variable configurable in a JavaScript file attached to a block. Here is how I added a field in the module’s settings form and passed the value to the JS file.
This is what I had in the module’s settings (my_module.settings.yml
):
max_num: 50
The above value would be set when the module is enabled.
Here is the field in the settings form (my_module/src/Form/SettingsForm.php
):
class SettingsForm extends ConfigFormBase {
...
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('my_module.settings');
$form['max_num'] = [
'#type' => 'textfield',
'#title' => 'Maximum number of items',
'#description' => 'This is max number of items to send in our request.',
'#default_value' => $config->get('max_num'),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('my_module.settings');
$config_keys = [
'max_num'
];
foreach ($config_keys as $config_key) {
$config->set($config_key, $form_state->getValue($config_key));
}
$config->save();
parent::submitForm($form, $form_state);
}
}
Here is how I passed the var to the JS (in my_module/src/Plugin/Block/MyModuleVizBlock.php
):
class MyModuleVizBlock extends BlockBase {
public function build() {
$max_records = \Drupal::config('my_module.settings')->get('max_num');
return [
'#markup' => '',
'#attached' => [
'drupalSettings' => [
'max_records' => $max_records,
],
],
];
}
}
Finally, here is the variable in the JS (my_module/js/my_module.js
):
(function ($) {
let max_records = null;
Drupal.behaviors.myModule = {
attach: function(context, settings) {
max_records = settings.max_records;
}
}
})(jQuery);