Hook to rename files only works with the first one

Hi, I’m trying to adapt this hook from Kirby 2 that renames files on upload.

I adapted it a bit, and it’s kind of working, the problem is that when I upload several files in a files section, only the first one is renamed.
In Kirby 2, the hook was renaming correctly every files, even if I uploaded multiple files at once.

What am I missing from what has changed with hooks in Kirby 3 ?

'hooks' => [
	'file.create:after' => function ($file) {
		$siteTitle = $this->site()->title()->slug();
		$page = $file->page();
		$title = $page->title();
		$count = 0;
		
		try {
		    $count = $page->images()->count();
		    $count = str_pad($count, 2, '0', STR_PAD_LEFT);
		    $filename = $siteTitle . "-" . $title . "-" . $count;
		    $file->rename($filename);
		} catch(Exception $e) {
		    // optional reason: echo $e->getMessage();
		}
	}
]

Thanks!

That’s a bug in Kirby 3 that has been fixed in v3.1.3, which will be out on Tuesday. You can already try the RC version.

I’m doing something very similar with the same result on Kirby v3.3.6

Here is my code :

  'file.create:after' => function ($file) {
    $page = $file->page();
    if ( $page->template() == 'article' || $page->template() == 'work' ) {
      $site_title = $file->site()->title()->slug();
      $page_title = $page->title()->slug();
      $title = $site_title . '_' . $page_title;
      $count = 0;
      try {
        $count = $page->images()->count();
        $count = str_pad($count, 2, '0', STR_PAD_LEFT);
        $filename = $title . '_' . $count;
        $file->changeName($filename);
      } catch(Exception $e) {
        // optional reason: echo $e->getMessage();
      }
    }
  },

The main difference is that I update $file->rename() to $file->changeName().

It’s all good if I upload each file one by one, and else it works only for the first one.

Any idea why ?

What filesize and how many images are we talking here?

I just tested this and several files were renamed, others were not, depending on the number of images it seems. Haven’t debugged this properly yet, but I wonder if this has to do with PHP settings.

I only tried to upload one to three images png that are under 100ko each.

The website is on localhost, I will do more tests later today.

1 Like

Similarly, I have a plugin that runs images through the TinyPNG compressor on file.create and it works fine for the first upload but if the user drops multiple images into the files section, it only works on the first one and clogs up before doing the rest.

Do you all use the latest Kirby version (3.3.6)?