Rename files on upload to panel

Hello!

I’m trying to find a way to automatically rename files on upload to the panel to :
(Site name + Section name + Page name + Number).

I found these 2 topics that both already ask this question :

I have tried both solutions, but neither of them is functioning for me… :confused:

I tried creating a .php file at : site/config/config.php and copying the code for each of the above solutions into that file, but neither of them worked… any ideas ?

The Kirby 2 code won’t work anymore.

Could you please post what you have so that we can take it from there? A file.create:after hook is definitely the way to go.

This is the content of the config.php file :

<?php

return [
  'hooks' => [
'file.create:after' => function ($file) {
		      $page = $file->page();
		      $title = $page->title();
          $count = $page->files()->count() + 1;
          $filename = "Something-" . $title . "-" . $count;
		      try {
		          $file->changeName($filename);
		          } catch(Exception $e) {
		    }
	}
  ]
];

Hm, just tested in a Starterkit and it works as expected.

oh yes, good idea! :slight_smile:

ok so I just tested it out on the Starter Kit too :
– When I upload a single image it seems to work every time
– When I upload multiple images (2 or more) it seem to work randomly…

I have attached a screenshot, these are 2 attempts at uploading the same 7 images.

As you can see by the names highlighted in red; some are renamed, some aren’t.
And it isn’t even the same images each time… :confused:

Uploading to my site still doesn’t work at all… but I figure we should probably try to at least get it working properly in a clean starter kit before I try to make it work on my site :slight_smile:

Same problem as here: Hook to rename files only works with the first one

You could check if it makes a difference if you change your PHP settings, otherwise maybe create an issue on GitHub.

Is it possible to fine tune the hook so it only rename images and not pdf or other type of files ?

Thank you !!

Yes, while the hook will be called on every file upload, inside the hook you can of course use any conditions you like.

Thank you very much !