I created a field of type "Entity reference" and referencing an item of type Media. In other words its an image field.

I would like to execute code with an hook or an event when an image is added, changed or removed. I don't know what's the proper way to do it since the reference to the image field is not "saved" until the complete node form is submitted.

enter image description here

For example if i remove the image and then refresh the page without saving the node form the original image will still be there. So i don't want a hook/event on the "remove" button but only when the complete node form is saved and the image deletion is processed.

Does this make sens?

More context:

Each time a Media field is used (image is added, changed or removed from any Media fields) I will call a remote service (a Digital Assets Management service) to add/change/remove a reference to this image.

I'm creating a module that will be reused on various website. So i can't assume the structure or the name of the fields. A node could have various level of paragraphs containing Media fields.

What i tried:

  • Created a Widget extending Drupal\entity_browser\WidgetBase so when the image is selected (and the widget function submit() is called) I make my remote call. It works but not really suitable since if someone adds an image and then decide to refresh the page without saving the main node form, the image would not have been saved but the remote call will have been done.

  • I tried to add actions on the Media buttons ("remove", "edit" and "add"). But it's kind of hackish and definitely doesn't seem to be the way to go.

  • Remove doesn't delete the image, it just removes the reference, that's why nothing happens until you save the node. Do you want to act on the image being deleted? or when the image is removed from a node?
    – sonfd
    Dec 13, 2019 at 1:17
  • @sonfd Yes exactly. I want to act when the image is removed from the node.
    – FR6
    Dec 13, 2019 at 1:27
  • Does this answer your question? Check if a node field has changed upon save
    – sonfd
    Dec 13, 2019 at 1:34
  • It's a good idea. But is there a way to recursively loop thru all fields to find the Media fields? Since there could be paragraphs fields.
    – FR6
    Dec 13, 2019 at 2:00
  • 1
    I think your best bet is to look at the Entity Usage module and see if it provides an event you can hook on to.
    – sonfd
    Dec 13, 2019 at 3:23


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.