0

In Drupal 8 inline entity form is there a "form_alter" or "submit handler" or some type of ajax callback for when a user clicks "add another item"?

What I would like to do is display a message to the user when they click "add another item" on a Inline Entity Form Multiple field.

Struggling to find the right path.

This question has an open bounty worth +50 reputation from SoundCheese ending in 3 days.

This question has not received enough attention.

0

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:

$.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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.