Question about page.update:before parameters

Hi,

Every page has a field linkid that I use as a shortcut for the actual URL in a custom link kirbytag.

fields:
  linkId:
    label: LinkID  
    type: text
    required: true

Therefore, I need every linkid value to be unique.

I opted for using a page.update:before hook where I first get all linkid values to check if the current page’s value (which might not have been saved yet) is already present in the list of all link IDs.

However, I’m not sure how to get the the current page’s value.

This is the code I’ve written so far:

'hooks' => [
    'page.update:before' => function(Kirby\Cms\Page $page, array $values, array $strings) {

        // Verify that there are not duplicate link IDs.
        $fieldName = option('sanofan.linkid-kirbytag.id-field-name');

        function getFieldValue(Kirby\Cms\Page $page, string $fieldName) {
            return $page->content()->fields()[$fieldName]->value;
        }

        $allLinkIds = [];

        foreach(kirby()->site()->index() as $p) {
            $id = getFieldValue($p, $fieldName);
            $allLinkIds[] = $id;
        }
           
        $linkId = getFieldValue($page, $fieldName);

        // ...
        }

My questions:

  • What values do the parameters $values and $strings contain? If they contain the value that are not saved yet, how could I get the value of the linkid field?
  • Does $allLinkIds contain the link ID of the current page that was previously saved?

Cheers,

Stefan

That sounds like you might run into a performance issue sooner or later if you check in the complete site if something already exists. Why don’t you use the autoid plugin?

Thanks for pointing me to the plugin.

The site only has 10 pages, so performance is currently not an issue.

Most importantly, the main reason I’m overriding a KirbyTag and want to use the page.update:before hook is to get to know different parts of Kirby.

Looking for a code example, I searched the getkirby.com repo, but page.update:before doesn’t seem to be used there.

So, I’m still wondering what $values and $strings are used for.

If you have a link to some code making use of these parameters inside page.update:before that would be great.

Both $strings and $values contain the new page values, only in different format. $strings contains an array of field values as strings, $values contains for example the structure field as array instead as of string.

In any case you cannot modify the result that is saved from a before hook if that’s what you are trying to do.

1 Like

That’s good to know. Thanks a lot!

So you can either use a page.create.after hook like the autoid plugin is doing it to automatically save some id after updating.

Or you use the page.update:before hook just to throw an error if the value the user entered is not unique.