Come for the code, stay for the community

Automatic image file names

Automatically create image media name when attached to content.

Currently using this trick to set the image name based on alt text.

The parent content often has a location field, location and a timestamp would make a good filename.

One option is to create a custom token to use in the auto entity label UI. This could be done with ECA.

Another option is to use ECA to set the alt text/name on save.

Are there any modules that provide reverse reference tokens?

Solution

This simple ECA loads the referenced media on save of the snapshot, and sets the media location field based on the snapshot's location.

The photo has to be save after the location is set. Is this causing multiple saves?

Image
ECA set referenced media entity field

*This isn't working when trying to set multiple locations on the photo.

https://www.drupal.org/project/eca/issues/3255608

https://www.drupal.org/project/eca/issues/3309212

Digging Deeper

Let's get a better handle on what is happening.

I added this code that will post a message when an entity is saved or updated.

I used drupal_static() to count the calls to either function.

function entitysavetest_entity_insert(\Drupal\Core\Entity\EntityInterface $entity) {
  $test = &drupal_static('message_count', 1);
  \Drupal::messenger()->addStatus($test . '. Saving entity: ' . $entity->getEntityTypeId() . ' ' . $entity->label());
  $test++;
}

function entitysavetest_entity_update(\Drupal\Core\Entity\EntityInterface $entity) {
  $test = &drupal_static('message_count', 1);
  \Drupal::messenger()->addStatus($test . '. Updating entity: ' . $entity->getEntityTypeId() . ' ' . $entity->label());
  $test++;
}

When I upload an image in media library, I can see that it's saved and updated right away.

Project
Modules
Task type
Topics