Skip to content
This repository has been archived by the owner on Oct 6, 2022. It is now read-only.

PHP: autoid(), Field Method fromAutoID()

Bruno Meilick edited this page Mar 18, 2020 · 8 revisions

AutoID of Page/File-Object in PHP

// form field will only read value
$autoid = $page->autoid()->value();

// RECOMMENDED
// but using the page method makes sure 
// the object has been indexed
$autoid = $page->AUTOID();

Find Page/File-Object in PHP

$autoid = 'any-autoid-value';

$result = autoid($autoid); // global helper function
// or
$result = $page->myFieldWithAutoIDReference()->fromAutoID(); // fieldMethod

if(is_a($result, 'Kirby\Cms\Page')) {
    // got a Page
} elseif(is_a($result, 'Kirby\Cms\File')) {
    // got a File
} elseif(is_a($result, 'Kirby\Cms\StructureObject')) {
    // got a StructureObject
    // $result->myFieldname()
    // $result->id: $autoid
    // $result->parent: Site|Page-Object hosting the Structure
}

Create a Page/File programmatically and retrieve autoid

Right after creating a Page/File programmatically the $object->autoid()->value() will be empty since the page.create:after/file.create:after hook triggered an update-hook but the Page/File-Object returned by createChild()/createFile() can not reflect this yet. But you can use the autoid() helper to retrieve the autoid from the database based on the id of your Page/File-Object.

$page = $parent->createChild($yourProps);
// autoid()-helper will not find drafts, so make it unlisted/listed
$page = $page->changeStatus('unlisted');
// return page.create:after but not [=> autoid => $page->update(...)] 
$willBeEmpty = $page->autoid()->value(); 
// but this will work
$autoid = autoid($page)->autoid()->value();
// this as well
$autoid = $page->AUTOID();

$file = $page->createFile($yourFileProps);
$willBeEmpty = $file->autoid()->value();
// but this will work
$autoidOfFile = autoid($file)->autoid()->value();
// this as well
$autoid = $file->AUTOID();

ATTENTION: This only works in version 2 of this plugin.