When I upload a file to a files section, I would like to auto-assign a template to it, based on file type, maybe fill other fields too. I guess the file.create:after
hook is the way to go, but I can’t get to work… It works whithin the file.update:after
hook, but not after creating. Am I doing something wrong?
// general
'hooks' => [
'file.create:after' => function ($file) {
$file->update([
'fieldName' => 'content'
]);
}
]
// or in my specific case
'hooks' => [
'file.create:after' => function ($file) {
$file->update([
'template' => $file->type(),
'randomInt' => rand(1,10)
]);
}
]
Thank you in advance.
Hm, that should actually work. Is it a multi-lang installation or single language?
Ah, then you probably have to pass the language code in your update function as second argument: https://getkirby.com/docs/reference/objects/file/update
Best to loop through all languages in this case and update the file for each language
foreach (kirby()->languages() as $lang) {
$file->update([
'template' => $file->type(),
'randomInt' => rand(1,10)
], $lang->code());
}
If all language versions should have the same random int, then you would have to define the integer outside of the loop.
Oh, thank you, I wasn’t thinking about that, because both fields shall no be translatable.
For some reason, it is still not working with the file.create:after
hook, but weirdly does work on file.update:after
, with the exact same behavior I would actually expect from create
.
'hooks' => [
'file.update:after' => function ( $file ) {
$update = [
'template' => $file->type(),
'randomInt' => rand( 1, 10 )
];
foreach( kirby()->languages() as $lang ){
$file->update( $update, $lang->code() );
}
}
]
Well, but works, so I leave it for now. Thank you for your help!
Hm, ok, I only tested the code in a single-language Starterkit and there it worked. Maybe I have some more time later to look into a multi-lang installation.
Sorry for the late reply. In the mean time I experimented and researched my problem a lot, set up a excel sheets to mark under which circumstances something unexpected happened, filed a GitHub issue and closed it again after I found out, that the update
within my hook conflicted with another update
in another hook of the same kind
Looks like all updates
performed sequentially have to handle languages the same. E.g. no lang-param, fixed-lang-param or loop through all languages. Otherwise they override each other. Makes sense…