2

I have a plugin where I'm creating custom entries based on user submitted data. Saving these entries works well. As does modifying their titles after saving to add the entry's ID to the title (using craft()->on('entries.saveEntry', function(Event $event) { ... }). The problem I'm having now is that I'd like to also update the slug at this point, so that each entry's slug is just its ID.

I've tried using:

$entry->setContentFromPost(array(
    'slug' => $entryId,
));

and

$entry->getContent()->slug = $entryId;

but neither do anything — even though the title change is getting saved successfully. Either I'm missing something, or the slug is handled differently than both entry fields and entry base content.

My question: How do I update the entry slug from a plugin to be just the entry's ID?


Here's the code I currently have in my plugin's base class:

public function init()
{
    craft()->on('entries.saveEntry', function(Event $event)
    {
        $entry = $event->params['entry'];
        $entryId = $entry->id;

        $newTitle = str_replace('Name: ', $entryId . ' - ', $entry->title);

        $entry->getContent()->title = $newTitle;

        $entry->setContentFromPost(array(
            'slug' => $entryId,
        ));

        // Here I use elements->saveElement() because using entries->saveEntry 
        // cased an infinite loop.
        // It would be great to have this sanity checked as well, please :)
        craft()->elements->saveElement($entry);
    });
}
2

If you set the slug directly on the entry element, it should work!

public function init() {
    craft()->on('entries.saveEntry', function(Event $event) {
        $entry = $event->params['entry'];
        $entryId = $entry->id;

        $newTitle = str_replace('Name: ', $entryId . ' - ', $entry->title);

        $entry->getContent()->title = $newTitle;

        $entry->slug = $entryId;

        craft()->elements->saveElement($entry);
    });
}
| improve this answer | |
  • Awesome! That works perfectly. Thank you! – Gavin Anderegg Oct 5 '15 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.