Skip to content

[5.x]: Saving element in afterSave results in integrity constraint violation exception #15517

@timkelty

Description

@timkelty

What happened?

Description

If you need to (re)-save an element in its afterSave, you will get an integrity constraint violation on the elements_sites table, unless you manually include isNewForSite = false.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '17-1' for key 'elements_sites.idx_yuhsxkwkfvwtibgopgvkaghhoafftioctgde'
The SQL being executed was: INSERT INTO `elements_sites` (`elementId`, `siteId`, `title`, `slug`, `uri`, `enabled`, `content`, `dateCreated`, `dateUpdated`, `uid`) VALUES (17, 1, 'Entry #17', 'foo', 'blog/foo', 1, NULL, '2024-08-10 20:12:30', '2024-08-10 20:12:30', '8db0279e-b40a-4727-b352-cf5db88f64f4')

This only happens when trying to save something outside of the normal CP entry form, so it may have something to do with saving directly to a live element vs starting as a draft. Craft 4 has no problem with the same code.

Here's a gist of a contrived example where you want to put the entry ID in the title, so you re-save the entry in the afterSave event: https://gist.github.com/timkelty/1cfb09a9611587552ed0f81ab99b1af7

Craft CMS version

5.3

Related Issues

https://github.com/craftcms/craftnet/pull/1098

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions