Is there a way to detect when a file, uploaded to a page, has been deleted or is missing? A practical example would be an image slider built with a structure field. When a user selects a file within the structure field and one would remove the chosen uploaded file, stuff will break without a check.
I’ve tried using empty() to check, but with no avail.
<?php if (!$imageslider->photo()->empty()): ?>
What you are testing with your if statement is whether or not the field is empty.
The field contains the name of the file and has no way of knowing when the file is deleted. It therefore won’t be empty and will keep the filename.
What you want is to check is if the file exists. See the docs here: https://getkirby.com/docs/toolkit/api/media/exists
This doesn’t work. See @lukasbestle’s solution below instead.
By the way, you can use
->isNotEmpty() instead of
empty() will only check if the field is empty. You can use the following code to check if the file exists:
$photo = $imageslider->photo()->toFile();
// Photo exists
$media->exists() only works if you already have a media object, so it won’t help here. Thanks for your post though!
Right my bad! Edited my post to avoid confusion…
Hey, that works! I was not thinking clear at the moment of writing I suppose. Gracias @lukasbestle & @Thiousi.