Skip to content
This repository has been archived by the owner on Apr 3, 2024. It is now read-only.

Duplicating an item doesn't generate new ID #143

Open
henrikwirth opened this issue Apr 13, 2022 · 4 comments
Open

Duplicating an item doesn't generate new ID #143

henrikwirth opened this issue Apr 13, 2022 · 4 comments

Comments

@henrikwirth
Copy link

Hi there, thanks for creating these widgets, I think NetlifyCMS is lacking behind with lots of things for sure.

I am using the ID Widget to generate unique IDs for collection items. Now the issue I am running into is that once I duplicate one of the items it copies the ID field too. Since it is supposed to be the unique identifier obviously this causes issues.

2 options i see:

  1. Is there a way to add a regenerate directly once someone duplicates an item?
  2. Is there a way to add a Regenerate Button next to the ID field to do this manually?

I'd be happy to help with a PR, but I since I never wrote a Widget I am not well aware of the possibilities.

@d4rekanguok
Copy link
Owner

Hi @henrikwirth, thanks for opening this issue!

It looks like there's a 'prepublish' event we can hook into to generate a uuid for a field. I think this could potentially solve this issue:
https://www.netlifycms.org/docs/beta-features/#registering-to-cms-events

This repo is quite outdated so I'm hesitate to dive back in, if you want to take a crack at setting something up (a new widget, or an update to this one) I'm happy to assist with any issues you might run into!

@henrikwirth
Copy link
Author

I think I might have found a way. There is a newRecord: true on the data that is passed to the prePublish hook if the item is newly created/duplicated. If we check for that, we can trigger the generation of the ID right there instead of initially pre-populated.

@henrikwirth
Copy link
Author

henrikwirth commented Apr 14, 2022

CMS.registerEventListener({
  name: "preSave",
  handler: ({ entry }) => {
    const data = entry.get("data");

    if (entry.get("newRecord")) {
      return data.set("id", "test-1234");
    }
  },
});

Not sure how we would access the Control Object to generate the ID according to the props. Any idea?

@d4rekanguok
Copy link
Owner

Currently the generate function is coded within the React component that drives the input:

public generateId() {
const { field, onChange } = this.props
const usePrefix = field.get('prefix')
const usePostfix = field.get('postfix')
const useTimestamp = field.get('timestamp')
const prefix = usePrefix ? usePrefix + '-' : ''
const timestamp = useTimestamp ? Date.now() + '-' : ''
const postfix = usePostfix ? '-' + usePostfix : ''
const id = prefix + timestamp + shortid() + postfix
onChange(id)
}

I think it'd be good to extract it out into a util function & export it

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants