Hi,
I have successfully set up front end image uploading, and am updating a field in a user account with what is uploaded. This is my current code in a controller:
$portfolioImage = $this->form->data('portfolioImage');
if(!empty($portfolioImage['name'])) {
$filename = time() . '-'. $portfolioImage['name'];
$file = kirby()->user()->createFile([
'source' => $portfolioImage['tmp_name'],
'filename' => $filename,
'template' => 'image'
]);
kirby()->user()->update([
'allImages' => $filename
]);
}
Which is working great. I want to change how it works a little - instead of replacing the file in allImages
with what has just been uploaded, I want to add it to the list of files (allImages
has multiple: true
set on it). What is the best way of doing this?
Update:
It tried this - the process seems to make sense to me (create an array of the existing images, upload the file, append it to the array, write the array to the content file):
$portfolioImage = $this->form->data('portfolioImage');
$existingImages = kirby()->user()->allImages()->toFiles();
$newImageSet = [];
foreach($existingImages as $existing):
$newImageSet[] = $existing->uuid();
endforeach;
if(!empty($portfolioImage['name'])) {
$filename = time() . '-'. $portfolioImage['name'];
$newfile = kirby()->user()->createFile([
'source' => $portfolioImage['tmp_name'],
'filename' => $filename,
'template' => 'image'
]);
$newImageSet[] = $newfile->uuid();
kirby()->user()->update([
'allImages' => Data::encode($newImageSet, 'yaml')
]);
}
But this causes a major error - the file is repeatedly uploaded until the site runs out of memory! It seems to be caught in a loop, as the file name (which includes time()
) changes each upload before it crashes. If anyone has any thoughts that would be super!
OK got it - below is working for me:
$portfolioImage = $this->form->data('portfolioImage');
if(!empty($portfolioImage['name'])) {
$existingImages = kirby()->user()->allImages()->toFiles();
$newImageSet = [];
foreach($existingImages as $existing):
$newImageSet[] = 'file://' . $existing->uuid()->id();
endforeach;
$filename = time() . '-'. $portfolioImage['name'];
$newfile = kirby()->user()->createFile([
'source' => $portfolioImage['tmp_name'],
'filename' => $filename,
'template' => 'image'
]);
$newImageSet[] = 'file://' . $newfile->uuid()->id();
kirby()->user()->update([
'allImages' => Data::encode($newImageSet, 'yaml')
]);
}