netlify-cms-widgets icon indicating copy to clipboard operation
netlify-cms-widgets copied to clipboard

Duplicating an item doesn't generate new ID

Open henrikwirth opened this issue 3 years ago • 4 comments

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.

henrikwirth avatar Apr 13 '22 16:04 henrikwirth

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!

d4rekanguok avatar Apr 13 '22 16:04 d4rekanguok

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 avatar Apr 14 '22 08:04 henrikwirth

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?

henrikwirth avatar Apr 14 '22 09:04 henrikwirth

Currently the generate function is coded within the React component that drives the input: https://github.com/d4rekanguok/netlify-cms-widgets/blob/67ac5d4d7076b1c3ac7d1df8bd9336252b056e60/packages/widget-id/src/control.tsx#L26-L39

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

d4rekanguok avatar Apr 14 '22 10:04 d4rekanguok