I got a problem with checking whether a file exists or not when using the following code:
<?php
foreach( $sponsors as $img_name ) {
if( $all_sponsors->image($img_name)->exists() ) {
// do something
}
?>
To give you some background of the problem. I got sponsors which are just image files with a link as meta information. Now I created a checkbox field that pulls in every image as a checkbox item that you can select. If you hit save you get something like this:
Mainsponsor.txt
Title: Main Sponsors
----
Selected-sponsors: cewe.gif, nikon.png, something.jpg
Now if someone would delete an image (so to speak remove a sponsor by deleting e.g. nikon.png) the data in the file mainsponsor.txt would not change and thus link to a file that does not exist anymore.
Strangely my code breaks when I try to check if the file exists with the following error: Fatal error: Method Kirby\Patterns\Pattern::__toString() must not throw an exception, caught Error: Call to a member function exists() on null in C:\xampp\htdocs\ww\site\plugins\patterns\lib\helpers.php on line 0
What can I do to avoid a nullpointer exception there?
To explain the purpose of the exists() method: It’s part of the Toolkit Media class. Media objects can be created even if the file does not actually exist. In Kirby you will get null however.