[cp 2] generate slug when saving collection

Reason for this topic: The addons BetterSlugs and Unique Slug do not work yet with our new and improved codebase. Secondly, I need slugs for my routes.

Purpose for this topic: I want to have a simple bootstrap.php file in my config folder to generate the slug for me.

My idea: Having a field of type ‘text’ named ‘slug’ and in its options a key ‘slugField’ with the name of the field to generate the slug from. When I create/update an entry, cockpit needs to generate and save the (unique) slug if field slug is empty.

Progress:
I have cockpit-core (2.0.2) installed and created different collections like posts, pages, etc.
In my pages collection, there are several fields like title and slug. (top part of picture)
And in the options of the ‘slug’ field, I added ‘slugField’ as the key and ‘title’ as the value. (bottom part of picture)

This was rather simple thanks you our devs of cockpit.

Help needed:
I have tried to put together a ‘bootstrap.php’ to act when a collection is being saved, but it still isn’t generating a slug.
Simple slugs for collections in Cockpit CMS

What am I missing here? Somebody push me in the right direction please :slight_smile:

:rotating_light: NOT TESTED :rotating_light:

in your config/bootstrap.phpadd the following snippet:

<?php

$app->on('content.item.save', function($modelName, $data) {

    $model = $this->module('content')->model($modelName);
    $collection = $model['type'] == 'singleton' ? 'content/singletons' : "content/collections/{$modelName}";
    $fields = $model['fields'] ?? [];

    foreach ($fields as $field) {

        // check if slug field and referenced field is in data
        if (isset($field['opts']['slugField'], $data[$field['opts']['slugField']])) {
            
            $data[$field['name']] = $this->helper('utils')->sluggify($data[$field['opts']['slugField']]);
            
            $this->dataStorage->save($collection, $data);
            break;
        }
    }
});
1 Like

Thank you @artur for your time.
I can confirm this works.

next step for me is to make sure the slug is unique within the model and then update my gist so others can use this if needed. :smiley: