After stupidly losing time with A"I", I come to you, dear humans.
I’m trying to automatically rename the cover image for my articles to “cover-image.jpg”. To do this I tried the following hooks which both don’t work :
Hook 1, simple :
'file.create:after' => function (Kirby\Cms\File $file) {
if ($file->template() === 'cover-image') {
$parent = $file->parent();
$originalName = $file->filename(); // e.g. "image-truc.jpg"
Hook 2, more complicated :
'file.create:after' => function (Kirby\Cms\File $file) {
if ($file->template() === 'cover-image') {
$parent = $file->parent();
$originalName = $file->filename(); // e.g. "image-truc.jpg"
// check if the picture already exists
$existing = $parent->file('cover-image.jpg');
if ($existing && $existing->uuid() !== $file->uuid()) {
$existing->delete();
}
// rename
kirby()->impersonate('kirby', function () use ($file) {
$file->changeName('cover-image');
});
// remove the old .txt orphan in case that was the problem...
$orphan = $parent->root() . '/' . $originalName . '.txt';
if (file_exists($orphan)) {
unlink($orphan);
}
}
},
What happens is that the card section in the panel becomes red right after I tried to upload the picture, and the article’s folder content becomes :
I’ve read all the other posts about this topic and none solved my problem. I’d like to avoid the problem entirely but I need to rename the file to distinguish it from other pictures using something else than Kirby’s internal file references system in case I want to migrate later. (If the cover-image field saved in the content’s article.txt was the filename and not a uuid that would solve the problem but it seems that we can’t do that.)
For info here is the relevant section in my article.yml file :
I can’t re-edit the first post which has a mistake because I messed something up with the code block, but here is the first hook which didn’t work and I’d like to know why :
'file.create:after' => function (Kirby\Cms\File $file) {
if ($file->template() === 'cover-image') {
$file->changeName('cover-image');
}
},