<p>I did some looking into how the <code>EVENT_BEFORE_SAVE</code> is being used and whether or not we can get the entry ID, without having to over complicate things, it was better to use <code>EVENT_AFTER_SAVE</code>, this does mean you will have to resave the entry after saving it, in this case that is very little overhead and it is only for a certain section, if heavier stuff was happening you may want to check on the impact.</p>
<p>I also placed in a check to detect if the action was happening or not, to stop any loops.</p>
<p>Here is what I ended up doing for anyone who wants to know for reference.</p>
<pre><code>use craft\elements\Entry;
use craft\events\ModelEvent;

const SECTION_ID = 4;
public static $entrySlugRenaming = false;

Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE,
    function (ModelEvent $event) {
        $this-&gt;handleEventAfterSave($event);
    }
);

private function handleEventAfterSave($event)
{
    // Get entry
    $entry = $event-&gt;sender;

    // Don't worry about draft or revisions
    if (ElementHelper::isDraftOrRevision($entry)) {
        return;
    }

    // Test if entry renaming is already running
    if (!self::$entrySlugRenaming) {
        self::$entrySlugRenaming = true;

        // Check if there is an entry
        if ($entry !== null) {
            // Test for entry section
            switch ($entry-&gt;sectionId) {
                case self::SECTION_ID:
                    // Update slug here
                break;
            }
        }

        // Resave event
        $elements = Craft::$app-&gt;getElements();
        $elements-&gt;saveElement($entry);

        // Reset $entrySlugRenaming
        self::$entrySlugRenaming = false;
    }
}
</code></pre>

CC BY-SA 4.0
2022-11-02T14:10:33.117Z
Thanks for posting your solution @zizther, it helped me with a similar issue trying to get an id for new entry.
Kirk Roberts
CC BY-SA 4.0
2020-09-17T12:24:27.077Z
2020-09-17T12:24:27.077Z
zizther
<p>I don't know if it was with Craft 3.5, but did something change slightly when using the EVENT_BEFORE_SAVE event?</p>
<p>I have a simple use case where I am encoding the entry ID and updating the slug when the entry is saved.
It does check if a title is empty and if the entry is a draft or revision, if any of those are true, then it does not encode it.</p>
<p>After updating from Craft 3.4.30 to Craft 3.5.5 when saving an entry I have noticed that it throws an error as $entry-&gt;id returns null, however on refreshing the page and then resaving it, it passes the entry ID in fine.</p>
<p>A basic example of what I have is:</p>
<pre><code>Event::on(
    Entry::class,
    Entry::EVENT_BEFORE_SAVE,
    function (ModelEvent $event) {

        $entry = $event-&gt;sender;

        if (ElementHelper::isDraftOrRevision($entry)) {
            return false;
        }

        // Get entry title
        $title = $entry-&gt;title;

       if ($title !== null) {
            // Encode entry ID
            $newSlug = Module::$instance-&gt;hashid-&gt;encode($entry-&gt;id);

            // Update slug to be a hash
            $entry-&gt;slug = $newSlug;
        }
    }
);
</code></pre>
<p>Before hand this worked fine when creating the entry, but now it is requiring me to have to save the entries twice, any thoughts?</p>

CC BY-SA 4.0
2020-08-27T19:00:22.450Z
If it's a _new_ entry, then `$entry->id` wouldn't have been set yet (because it hasn't been saved yet) and it doesn't look like your code is taking that into account. Are you sure that's not what you're seeing?
Brad Bell
CC BY-SA 4.0
2020-08-28T10:26:45.737Z
This does sound like what the issue is related to. If I were to check isNew, could I then use this Event, or would I have to use EVENT_AFTER_SAVE in this case?
zizther
CC BY-SA 4.0
2020-08-28T19:09:35.733Z
You could keep it in this event as long as you checked its newness.
Brad Bell
CC BY-SA 4.0
2020-09-02T18:52:43.470Z
Thanks. What is the best way to do this?
I want this to apply for new entries which then get an Entry ID and for existing entries.
The first part is why i was thinking EVENT_AFTER_SAVE maybe the better solution as it would definitely have an entry ID. Unless there is a nice way to check it with the current event.
zizther
<events><modules>
EVENT_BEFORE_SAVE event not getting $entry-id when creating an entry
# EVENT_BEFORE_SAVE event not getting $entry-id when creating an entry

(Asked by: username_0 on 2020-08-27)

I don't know if it was with Craft 3.5, but did something change slightly when using the EVENT_BEFORE_SAVE event?
I have a simple use case where I am encoding the entry ID and updating the slug when the entry is saved.
It does check if a title is empty and if the entry is a draft or revision, if any of those are true, then it does not encode it.
After updating from Craft 3.4.30 to Craft 3.5.5 when saving an entry I have noticed that it throws an error as $entry->id returns null, however on refreshing the page and then resaving it, it passes the entry ID in fine.
A basic example of what I have is:
Event::on(
    Entry::class,
    Entry::EVENT_BEFORE_SAVE,
    function (ModelEvent $event) {

        $entry = $event->sender;

        if (ElementHelper::isDraftOrRevision($entry)) {
            return false;
        }

        // Get entry title
        $title = $entry->title;

       if ($title !== null) {
            // Encode entry ID
            $newSlug = Module::$instance->hashid->encode($entry->id);

            // Update slug to be a hash
            $entry->slug = $newSlug;
        }
    }
);

Before hand this worked fine when creating the entry, but now it is requiring me to have to save the entries twice, any thoughts?

**Tags:** events, modules

> **Comments:**
> **username_1**: If it's a _new_ entry, then `$entry->id` wouldn't have been set yet (because it hasn't been saved yet) and it doesn't look like your code is taking that into account. Are you sure that's not what you're seeing?  
> **username_0**: This does sound like what the issue is related to. If I were to check isNew, could I then use this Event, or would I have to use EVENT_AFTER_SAVE in this case?  
> **username_1**: You could keep it in this event as long as you checked its newness.  
> **username_0**: Thanks. What is the best way to do this? I want this to apply for new entries which then get an Entry ID and for existing entries. The first part is why i was thinking EVENT_AFTER_SAVE maybe the better solution as it would definitely have an entry ID. Unless there is a nice way to check it with the current event.  

---

## 1 answers

### Answer by username_0 on 2020-09-17. Score: 3 | Accepted answer

I did some looking into how the EVENT_BEFORE_SAVE is being used and whether or not we can get the entry ID, without having to over complicate things, it was better to use EVENT_AFTER_SAVE, this does mean you will have to resave the entry after saving it, in this case that is very little overhead and it is only for a certain section, if heavier stuff was happening you may want to check on the impact.
I also placed in a check to detect if the action was happening or not, to stop any loops.
Here is what I ended up doing for anyone who wants to know for reference.
use craft\elements\Entry;
use craft\events\ModelEvent;

const SECTION_ID = 4;
public static $entrySlugRenaming = false;

Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE,
    function (ModelEvent $event) {
        $this->handleEventAfterSave($event);
    }
);

private function handleEventAfterSave($event)
{
    // Get entry
    $entry = $event->sender;

    // Don't worry about draft or revisions
    if (ElementHelper::isDraftOrRevision($entry)) {
        return;
    }

    // Test if entry renaming is already running
    if (!self::$entrySlugRenaming) {
        self::$entrySlugRenaming = true;

        // Check if there is an entry
        if ($entry !== null) {
            // Test for entry section
            switch ($entry->sectionId) {
                case self::SECTION_ID:
                    // Update slug here
                break;
            }
        }

        // Resave event
        $elements = Craft::$app->getElements();
        $elements->saveElement($entry);

        // Reset $entrySlugRenaming
        self::$entrySlugRenaming = false;
    }
}

> **Comments:**
> **username_2**: Thanks for posting your solution @username_0, it helped me with a similar issue trying to get an id for new entry.  

---

