Hello and thanks for looking my question.

On Drupal 7 I use this hook hook_file_presave() for change file name.

function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];

But how to do it on Drupal 8.1.x? Programmatically or module ways or something else?

1 Answer 1



Description from the DocBlock:

Act on an entity before it is created or updated.
You can get the original entity object from $entity->original when it is an update of the entity.

  • Yes, thx for answer. But how to write code with this hook, like on my first post? Any example make me understand. Jun 2, 2016 at 9:40
  • 1
    Try function yourModule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {drupal_set_message('<pre>'.print_r(array_keys((array) $entity),1).'</pre>');} and let me know the result. Jun 2, 2016 at 11:53
  • this code return error on white screen Jun 14, 2016 at 6:02
  • I've done it for Drupal 9, let me know if you're interested in the answer for v 9
    – Cortex
    Feb 9, 2021 at 7:00

Your Answer

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

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