I have an entry type that includes an Assets field. When this entry is created/saved via the CP or a front-end form, I want to rename the Asset file as follows:
- Entry's author id. E.g: 148
- 01, 02, 03 based on how many entries the author has already submitted.
So files would look like: 148-01.jpg 148-02.jpg, 148-03.jpg.
At some point, I would also like to add the value of a custom field.
Also, I would like to limit this to entry for a certain type in a certain section: Section name: "Competitions", Entry type: "Submission".
Screenshot: https://cl.ly/a526f40c6d58
So far In my Craft 3 Module I have this. I can get the Asset id, but I can't get the Entry's Author Id:
Event::on(
Elements::class,
Elements::EVENT_AFTER_SAVE_ELEMENT,
function (ElementEvent $event) {
$asset = $event->element;
$id = $event->element->getId();
if ($event->isNew && $asset instanceof craft\elements\Asset) {
$newFileName = "new-file-name-" . $id . ".jpg";
Craft::$app->assets->moveAsset($asset, $asset->getFolder(), $newFileName);
}
}
);
I found this answer https://craftcms.stackexchange.com/a/13199/298, but it's for Craft 2:
craft()->on('entries.beforeSaveEntry', function(Event $event)
{
$entry = $event->params['entry'];
if (($entry->section['handle'] == 'friends') && ($entry->type['handle'] == 'friends'))
{
$title = $entry->slug;
$assets = $entry->imgdir;
if (count($assets) != 1)
{
$event->params['entry']->addError('imgdir', Craft::t('Exactly 1 asset has to be selected.'));
$event->performAction = false;
}
else
{
$filename = $title.'.'.$assets[0]->getExtension();
craft()->assets->renameFile($assets[0], $filename);
craft()->assets->storeFile($assets[0]);
}
}
});
How can I do this in Craft 3?