Basic conditional PHP question

Hi, I’m almost positive this is something easy to do, but my knowledge of PHP is somewhat limited so help would be appreciated. I have some code that looks like this:

    $manualfilename = $page->pageid().'.pdf' ;
    $manual = $pages->find('manuals')->documents()->$manualfilename ;
<a href="<?php echo $manual->url() ?>">Manual</a>

I’m basically automatically pulling, from a separate directory, a manual PDF whose filename matches the pageid of the current page. It works so far, but only if the corresponding PDF is present. If it’s not, or misspelled, nearly the entire page fails to load. Can someone help me make this display a broken link or something more useful than simply breaking the page? Also if I’m just doing this in a weird way that would be good to know :smiley:

Try this:

    $manualfilename = $page->slug().'.pdf' ;
    $manual = $pages->find('portfolio')->documents()->find($manualfilename);
<a href="<?php e(file_exists($manual), $manual->url(), '#fileNotFound'); ?>">Manual</a>

There were a couple things I changed.

The $manualfilename variable is now using $page->slug() instead of $page->pageid() and I used a Kirby helper e() to run an if/else statement that echo’s the results. You may also wish to wrap the whole url in the e() helper (and remove the false string) instead, so the link will only show up if the file exists.

<?php e(file_exists($manual), '<a href="' . $manual->url() . '">Manual</a>'); ?>

This doesn’t fix the problem, unfortunately. Exact same result as before (breaks the page if the file name doesn’t match). :confused:

My code up to this point looks like this:

    $manualfilename = $page->title().'.pdf' ;
    $manualpath = $pages->find('manuals')->documents()->find($manualfilename) ;
<a href="<?php e(file_exists($manualpath), $manualpath->url(), '#fileNotFound'); ?>">Manual</a>

Going with title() so I can have spaces in the PDF file name.

Is there a more kirby-specific version of file_exists()?

You don’t need file_exist, just check if you retrieve something from ->find():

<?php if ($file = page('portfolio')->documents()->find($page->slug().'.pdf')) : ?>
    <a href="<?php echo $file->url() ?>">Manual</a>
<?php endif; ?>
1 Like

This works perfectly! Thanks so much.