Populating files/images in a model

Hey everyone,

I’m creating some virtual pages from a database inside of a controller. It’s all working pretty well. I’m manually populating the images field (which is a field that I’ve defined myself), so I can edit it in the admin panel. However, somehow Kirby still thinks that the virtual page has no images/files ($page->images() and $page->files() don’t return anything).

So I think for these virtual pages to behave like actual pages (including thumbnail images in the panel), I need to populate some field manually.

What’s the best way to do this? I have an array of Image IDs – How to create an array of file/image objects from this? Are there any factory/constructor methods I can use?

class InternalInventoryPage extends Kirby\Cms\Page
{
    public function children(): Pages
    {
        
        $items = []; 
        $dbItems = Db::select('items');

        foreach ($dbItems as $item) {
            $items[] = [
                'slug'        => $item->invnum(),
                'num'        => 0,
                'template' => 'inventory-item',
                'model'     => 'inventory-item',
                'content'   => [
                    'title'           => $item->manufacturer()." ".$item->name()." ".$item->model(),
                    'name'            => $item->name(),
                    'invnum'          => $item->invnum(),
                    'model'           => $item->model(),
                    'amount'          => $item->amount(),
                    'uuid'            => "inv" . $item->invnum(),
                    'images'          => empty($item->images()) ? null : json_decode($item->images())
                ]
            ];
        }

        return $this->children = Pages::factory($items, $this);
    }
}

Two thoughts:

  • Field names files or images will clash with the actual page methods $page->files() and $page->images(). You won’t be able to access the fields this way as the page methods will have priority. Instead, you’d need to do something like $page->content()->get('images').
  • Where do the corresponding image objects actually exist? As a field would just reference an image object by UUID/id. From your code I cannot tell if they actually exist somewhere, or are virtually created somewhere else. For virtual files see https://getkirby.com/docs/guide/virtual-content/virtual-files#option-1-the-factory-method__virtual-files-page-model