You can do this using JS. Add a click event listener on the Add item
button. When the button is clicked you set a message.
Something like this should work:
$('.add-item-class').on('click', function () {
const messages = new Drupal.Message();
messages.add('You clicked the add item button!');
});
Make sure you have Drupal
available in your JS file by adding it as a dependency in your libraries file.
js:
path/to/js-file.js: {}
dependencies:
- core/drupal
- core/jquery
Please note that the Drupal.Message()
was first introduced in Drupal 8.7
, so if you use an older version it would not work.
Another possible solution is to create a route that sets the message, using \Drupal::messenger()->addMessage('')
.
Your controller will do like this:
\Drupal::messenger()->addMessage($this->t('Your added an item!'));
$messages = ['#type' => 'status_messages'];
return new JsonResponse(['message' => Json::encode(\Drupal::service('renderer')->renderRoot($messages))]);
And your JS file like this:
$('.add-item-class').on('click', function () {
$.get('/path/to/your-route', function (response) {
$(context).find('.region-highlighted').prepend(JSON.parse(response.message));
setTimeout(function () {
$(context).find('.region-highlighted .messages').remove();
}, 5000);
});
});
This appends the message to the highlighted
region and removes it after 5 seconds. You can place it anywhere you want.