I'm trying to find an event that I can subscribe to for the method addMessage.
I need to trigger some code everytime a status message is added. On reacting to this event, I need to send a variable from php to JS. I could not find an event to subscribe to so instead I used a preprocess, below.
<?php
function mymodule_preprocess_status_messages(&$variables) {
$variables['#attached']['drupalSettings']['send_me_to_js']['_variable'] = 'Going to js...';
}
This preprocess runs everytime addMessage is used and a status message is displayed, but, the variable that i need sent to JS, is not always sent.
For example, this works for messages created from core, and I get the variable in JS. But when Drupal Commerce uses addMessage (eg. when adding a product to cart in ajax setup), the preprocess runs, the status message displays, but the variable is not available in JS.
Here's the javascript:
(function ($, Drupal, drupalSettings) {
Drupal.behaviors.alwave_alerts = {
attach: function (context, settings) {
$('.my-class', context).once('unique-string').each(function () {
// Run after each ajax call
$(document).ajaxComplete(function () {
// This is sometimes undefined even though the preprocess above runs
// and there is a status message on screen
// (eg. when commerce creates a status message)
console.log(settings.send_me_to_js);
});
});
}
};
}(jQuery, Drupal, drupalSettings));
There must be an easy way?
Update:
I discovered that the preprocess does not send the variable to javascript only on ajax requests. On first page load it is sent, but subsequent ajax requests do not send this variable to JS. Seems to be the order sequence in which things are executed during ajax requests.
So the question is, How do I send a variable to JS from this preprocess on ajax calls?