decaporg / decaporg/decap-cms

Unexpected behavior with `preSave` event listener resulting in missing identifier_field

Open
#6,775 0 comments 0 reactions 0 assignees View on GitHub
area: docs area: error-handling type: bug
Dominant language
JavaScript
Stars
19.4k
Forks
3.1k
Avg merge
1d 14h
Merged PRs (30d)
9

Description

Long story short: It seems `preSave` expects a specific return value to work and this issue can be avoided through better documentation

**Describe the bug**

I've set up a `preSave` handler that assigns custom `id` to saved objects
I started getting an error:
```
Error: Collection must have a field name that is a valid entry identifier, or must have `identifier_field` set
```

I thought maybe assigning the `id` used as `identifier_field` was not possible to be done in `preSave`

Finally I figured out that I have to return `entry.get('data')` instead of the `entry` I get as a input parameter
Also it wasn't obvious that the `Map` type used was not the native mutable `Map` type, but an Immutable one

I couldn't find much information about the available event listeners, but the short examples here: https://decapcms.org/docs/beta-features/#registering-to-cms-events

**To Reproduce**

1. Set up a `preSave` event handler `CMS.registerEventListener`
2. Have a collection with `identifier_field` set to `id`
3. In the `preSave` handler try to set the `id` like `entry.set('id', 'some-random-id)`
4. Observe the error message from the description

**Expected behavior**

An error message clearly explaining a value for the `identifier_field` is missing
```
Error: The field "{name}" specified as `identifier_filed` has no value set
```

Or a warning indicating the returned value from `preSave` handler does not match the collection schema
```
Warn: The object returned from the `preSave` event handler does not match all fields defined on the collection schema
```

Or maybe both

The existing error message (_"Collection ..., or must have `identifier_field` set"_) sounds like we haven't defined `identifier_field` in the collection schema

**Screenshots**

**Applicable Versions:**
- OS: macos Ventura 13.1
- Node.JS version: 18.7
- netlify-cms-app: 2.15.72
- Git provider: local-backend

**CMS configuration**

N/A

**Additional context**

N/A

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.