Skip to content

Instantly share code, notes, and snippets.

@fofoy
Last active May 4, 2025 14:50
Show Gist options
  • Select an option

  • Save fofoy/32aa05450fb976cd584a56496214e27b to your computer and use it in GitHub Desktop.

Select an option

Save fofoy/32aa05450fb976cd584a56496214e27b to your computer and use it in GitHub Desktop.
Reorder Payload Collection items witthout any plugin
// collection
import { Offer } from '@/payload-types'
import { slugify } from '@/utils/slugify'
import type { CollectionConfig, FieldHookArgs } from 'payload'
export const Offers: CollectionConfig = {
slug: 'offers',
labels: {
singular: {
en: 'Offer',
},
plural: {
en: 'Offers',
},
},
admin: {
useAsTitle: 'title
},
access: {
read: () => true,
},
fields: [
{
name: 'title',
type: 'text',
required: true,
},
{
name: 'slug',
type: 'text',
},
{
name: 'priority',
type: 'number',
min: 0,
admin: {
readOnly: true,
}
},
],
}
// global
import { GlobalConfig } from 'payload'
const OffersConfig: GlobalConfig = {
slug: 'offers-config',
label: {
en: 'Offers Config',
},
fields: [
{
type: 'array',
name: 'offers',
label: {
en: 'Offers',
},
access: {
create: () => false,
},
admin: {
description: {
en: 'Drag and drop to reorder the offers',
},
components: {
RowLabel: {
path: 'src/components/RowLabel.ts',
},
},
},
fields: [
{
type: 'row',
admin: {
readOnly: true,
},
fields: [
{
name: 'title',
label: 'Offre',
type: 'text',
},
{
name: 'promotions',
type: 'text',
},
]
}
],
virtual: true,
validate: () => true,
maxRows: 1,
}
],
hooks: {
afterRead: [
async ({ doc, req }) => {
const offers = await req.payload.find({collection: 'offers', sort: 'priority'});
doc.offers = offers.docs
return doc
},
],
beforeChange: [
async ({ data, req }) => {
for (let i = 0; i < data.offers.length; i++) {
const offer = data.offers[i];
await req.payload.update({
collection: 'offers',
id: offer.id,
data: { priority: i + 1 },
});
}
return data;
},
],
}
}
export default OffersConfig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment