Skip to content

Commit 710fe09

Browse files
authored
fix: duplicate with orderable (#12274)
Previously, duplication with orderable collections worked incorrectly, for example Document 1 is created - `_order: 'a5'` Document 2 is duplicated from 1, - `_order: 'a5 - copy'` (result from https://github.com/payloadcms/payload/blob/47a1eee765e554db29a9370927bf90f0fb4947f2/packages/payload/src/fields/setDefaultBeforeDuplicate.ts#L6) Now, the `_order` value is re-calculated properly.
1 parent 4a56597 commit 710fe09

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

packages/payload/src/config/orderable/index.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ export const addOrderableFieldsAndHook = (
8383
hidden: true,
8484
readOnly: true,
8585
},
86+
hooks: {
87+
beforeDuplicate: [
88+
({ siblingData }) => {
89+
delete siblingData[orderableFieldName]
90+
},
91+
],
92+
},
8693
index: true,
8794
required: true,
8895
// override the schema to make order fields optional for payload.create()
@@ -275,5 +282,6 @@ export const addOrderableEndpoint = (config: SanitizedConfig) => {
275282
if (!config.endpoints) {
276283
config.endpoints = []
277284
}
285+
278286
config.endpoints.push(reorderEndpoint)
279287
}

test/sort/int.spec.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,43 @@ describe('Sort', () => {
444444
parseInt(ordered.docs[1]._order, 16),
445445
)
446446
})
447+
448+
it('should allow to duplicate with reordable', async () => {
449+
const doc = await payload.create({
450+
collection: 'orderable',
451+
data: { title: 'new document' },
452+
})
453+
454+
const docDuplicated = await payload.create({
455+
duplicateFromID: doc.id,
456+
collection: 'orderable',
457+
data: {},
458+
})
459+
expect(docDuplicated.title).toBe('new document')
460+
expect(parseInt(doc._order!, 16)).toBeLessThan(parseInt(docDuplicated._order!, 16))
461+
462+
await restClient.POST('/reorder', {
463+
body: JSON.stringify({
464+
collectionSlug: orderableSlug,
465+
docsToMove: [doc.id],
466+
newKeyWillBe: 'greater',
467+
orderableFieldName: '_order',
468+
target: {
469+
id: docDuplicated.id,
470+
key: docDuplicated._order,
471+
},
472+
}),
473+
})
474+
475+
const docAfterReorder = await payload.findByID({ collection: 'orderable', id: doc.id })
476+
const docDuplicatedAfterReorder = await payload.findByID({
477+
collection: 'orderable',
478+
id: docDuplicated.id,
479+
})
480+
expect(parseInt(docAfterReorder._order!, 16)).toBeGreaterThan(
481+
parseInt(docDuplicatedAfterReorder._order!, 16),
482+
)
483+
})
447484
})
448485

449486
describe('Orderable join', () => {

0 commit comments

Comments
 (0)