Page.update:after hook is called when page is created (automatically populate createdOn/createdBy and lastUpdatedOn/lastUpdatedBy fields in a page)

Good afternoon,

so I want to automatically populate a createdOn/createdBy and a lastUpdatedOn/lastUpdatedBy fields in a page when the page is created or updated via the panel.

This works easily with the following hooks which I have put into my config.php (N.B. to everyone who tries the same as me beforehand, i.e. displaying these fields via blueprint in the panel - dont do it! It will mix up everything and it wont work or - more realistic - I made some error :slight_smile: ):

   'hooks' => [
        'page.create:after' => function (Kirby\Cms\Page $page) {
            $createdOn = Kirby\Toolkit\Date::now();
            $user = kirby()->user();
            $page->update([
                'createdOn' => $createdOn,
                'createdBy' => $user
              ]);

        },
        'page.update:after' => function (Kirby\Cms\Page $newPage, Kirby\Cms\Page $oldPage) {
            $updatedOn = Kirby\Toolkit\Date::now();
            $updatedBy = kirby()->user();
            $newPage->update([
                'lastUpdatedOn' => $updatedOn,
                'lastUpdatedBy' => $updatedBy
              ]);
        }
    ],

Now when I create a page via the Panel, the createdOn/createdBy fields are populated - wonderful! But also the lastUpdatedOn/lastUpdatedBy were, which should not be the case IHMO when creating a NEW page, right?

Am I doing something wrong or is this a bug?

Thanks
Andreas

1 Like

For this, you don’t need a hook, but can set a default for these fields in your blueprint.

And the second hook is called because you update right after creation.

So not using the first hook and use default values will then also prevent your issue.

Right thanks, but that means in the Panel (via blueprint) either I have to show the disabled createdOn/By fields or come up with a condition to never show them, right?

If you don’t want to show the field value to anyone, use a hidden field type.

Right but then I have to do some customizing, right? I try to avoid that. Actually, I think I will leave as is, I can live with it :slight_smile:

This is exactly what I needed. Thanks, @Andreas_1!