How to have custom slugs on page creation/duplication?

I want to create custom slugs, when pages are created or duplicated.

This works for the renaming part:

return [
    'hooks' => [
        'page.create:after' => function (Kirby\Cms\Page $page) {
            // just an example
            $page->changeSlug('foobar-' . rand());
        },
    ]
];

… but then the panel complains, right after the page was created

because, of course the page slug is not original-slug anymore, but the new one changed by the hook.

How would I go about it?

Thanks

Changing slugs in a hook is not a good idea, because of this issue. You’d better do this in a page model in the writeContent() method.

Thanks @texnixe.

So now I have this in config.php, but it has no effect whatsoever:

class Product extends \Kirby\Cms\Page
{
    public function writeContent(array $data, string $languageCode = null) : bool
    {
        $this->changeSlug('foobar-' . rand());
        return parent::writeContent($data, $languageCode);
    }
}

return [
    'product' => 'Product'
];

The following works, but results in the same error in the panel:

class Product extends \Kirby\Cms\Page
{
    public function writeContent(array $data, string $languageCode = null) : bool
    {
        $bool = parent::writeContent($data, $languageCode);
        $this->changeSlug('foobar-' . rand());
        return $bool;
    }
}

Can you nudge me in the right direction?

Thanks

Oops, sorry, messed up the method, should be the static create() method of course.

You can create a model in the /site/models folder…

Thanks @texnixe,

I don’t know how to first re-implement the create method, since neither Kirby\Cms\Model not Kirby\Cms\ModelWithContent nor Kirby\Cms\Page has a create-method. What am I not seeing. Or do you mean the constructor, hence __construct?

Thanks

Check out this thread: Auto-append to URL-Appendix - #4 by texnixe

1 Like

Thanks @texnixe that worked. I am still puzzled where the static create method comes from.

This here: kirby/PageActions.php at 481349feff0248fbb37419c6fd844f83496f129d · getkirby/kirby · GitHub

1 Like