Receiving an undefined variable error when filter isn't used in URL

Hi there, I’m trying to follow along with Filtering via routes from the Cookbook, slightly modified to filter the contents of a Structure field using multi-word parameters.

On the page itself, I include the following PHP:

<?php
    $publications = $page->publications()->toStructure();

    if($pubtype) {
        $pubtype = urldecode($pubtype);
        $publications = $publications->filterBy('pubtype', $pubtype, ',');
    }
?>

and in config.php I have:


'routes' => [
        [
            'pattern' => 'publications/(:any)',
            'action' => function ($pubtype) {
                if ($page = page('publications/' . $pubtype)) {
                    return $page;
                } else {
                    urlencode($pubtype);
                    return page('publications')->render([
                        'pubtype' => $pubtype
                    ]);
                }
            }
        ]
    ]

When I enter a URL that includes a parameter (e.g. http://example.com/publications/Example+One), the page loads and the filter works as intended. However, without the parameter in the URL (http://example.com/publications), I land on the Kirby CMS Debugger screen with the error “Undefined variable $pubtype”

Thanks in advance for any help with this!

As the error says, in that case your variable is not defined. So instead of

    if($pubtype) {

which does not check if the variable exists but if it is not equal null or false, use

if (isset($pubtype)) {
  // do stuff
}
1 Like

Great, thanks!