I have a module I'm working on that links to a sound file and plays it when something happens. I have it so that there is a button in the admin config to set the path of the file to a default path which is a file that comes with the module. Furthermore, one may upload their own file and it will switch to playing that file when the thing happens. The problem is, the module on a fresh install does nothing, when I want it to have that default sound set up to play immediately after install. I tried doing that with a settings.yml file however trying to access that data returns null until I go into the admin config and either set it to default or upload my own file.
Here is a look at the files:
MYMODULE.settings.yml
pathToSound: '/assets/sound.mp3'
MYMODULE.schema.yml
MYMODULE.settings:
type: config_object
label: 'MYMODULE Settings'
mapping:
pathToSound:
type: string
label: 'Path to Sound'
MYMODULE.module
<?php
use Drupal\Core\Form\FormStateInterface;
function MYMODULE_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'MYMODULE/MYMODULE';
$attachments['#attached']['drupalSettings']['MYMODULE'] = [
'pathToSound' => \Drupal::config('MYMODULE.settings')->get('pathToSound'),
];
}
MYMODULE.js
/**
* @file
*/
(function ($, Drupal) {
'use strict';
Drupal.behaviors.MYMODULE = {
/**
* Drupal attach behavior.
*/
attach: function (context, settings) {
// Triggers when the cache is cleared to play a sound.
$('body', context).once('MYMODULE').each(function () {
console.log(settings.MYMODULE.pathToSound);
var sound = document.createElement('audio');
sound.setAttribute('src', settings.MYMODULE.pathToSound);
sound.play();
});
},
};
})(jQuery, Drupal, drupalSettings, once);
I tried to exclude as much irrelevant code as possible. Anyway, there's also a form that edits the MYMODULE.settings "pathToSound" when the module is configured in the admin menu. Finally, there is the JS file which plays the sound. Like I said, it works after it is configured in the admin menu, but not before. I'm wondering before it is configured, the pathToSound returns null even though it is set in MYMODULE.settings. Any ideas would be greatly appreciated, thanks!
EDIT: Adjusted code according to suggestions, still not working. Also added the JS that is running the console log which is returning null.