Imagine a module called Configurable Picture. You want the path to the image to be configurable through the admin UI. A path is a string, so the first thing to do is define the configuration for the path. In this case, the configuration object will be configurable_picture.settings
path_to_picture
.
configurable_picture/config/schema/configurable_picture.schema.yml:
configurable_picture.settings:
type: config_object
label: 'Configurable Picture Settings'
mapping:
path_to_picture:
type: string
label: 'Path to Picture'
The next step is to create a configuration form that allows you to edit the configuration item defined in the above schema. Here is the documentation on creating configuration forms: https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms
With the above steps, you will be able save the path to the picture on the configuration page you have created.
There are two steps required to provide that configuration setting to the JavaScript file. The first is to add a dependency to core/drupalSettings
to your JS library.
configurable_picture/configurable_picture.libraries.yml:
picture_form:
js:
path/to/file.js: {}
dependencies:
- core/drupalSettings
Then, you attach the library and the settings to the form:
$form['#attached']['library'][] = 'configurable_picture/picture_form';
// The configurableSettings key will become the namespace within the
// drupalSettings object in the JS file.
$form['#attached']['drupalSettings']['configurablePicture'] = [
// Set the path based on the value saved in configuration:
'pathToPicture' => \Drupal::config('configurable_picture')->get('path_to_picture'),
];
Then path/to/file.js can access the settings object like this:
(function ($, Drupal, drupalSettings) {
function getPathToPicture() {
return drupalSettings.configurablePicture.pathToPicture;
}
// Or, from the settings object in Drupal.behaviors:
Drupal.behaviors.configurablePicture = {
attach: function (context, settings) {
console.log(settings.configurablePicture.pathToPicture);
}
};
}(jQuery, Drupal, drupalSettings));