I am trying to create a Drupal 8 module that implements a Curator IO widget, so I created a block plugin with its own custom configuration.
public function blockForm($form, FormStateInterface $form_state) {
$form['curator_io_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Curator IO Settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['curator_io_settings']['feed_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Enter your unique Feed Id'),
'#default_value' => $this->configuration['feed_id'],
'#maxlength' => 256,
'#size' => 64,
'#description' => t('Set your unique feed id found at curator io'),
];
return $form;
}
I attached my library from the build method and passed a variable so I can work with it in jQuery.
public function build() {
$build = [
'#theme' => 'curatorio_io',
'#attached' => [
'library' => [
'curatorio/curatorio_assets',
],
'drupalSettings' => [
'curatorio' => [
'feed_id' => $this->configuration['feed_id'],
]
]
],
];
return $build;
}
I am getting this variable value in JavaScript using the following code.
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.curatorio = {
attach: function (context, settings) {
console.log(drupalSettings.curatorio);
}
}
};
It is working fine for one instance of the block.
When I add 2 or more instances of this block, only the first block works. I can understand that no matter how many instance I create for this block, the JavaScript will always get included once, so how do I pass multiple values for feed_id to the JavaScript behavior?
<div data-feed-id="abc"></div>
and then change your javascript to fetch that data attribute?drupalSettings
. Don't reuse/overwrite yourfeed_id
variable, instead push (append) multiple unique entries (keys) info thecuratioio
array.