What is the best way to order collections on the front end? I'm currently considering making a new collection which has an array with a relationship to the required collection, but wondering if there is better ways?
when you say front end, do you mean a separate app/site, or the admin UI of Payload?
I guess technically the UI of payload. I'm using
const getPosts = async () => {
const posts = await payload.find({
collection: 'blog-posts',
})
return posts
}
and I
thinkthis reflects what is shown in the admin (i'm about to confirm) - but there is no way to reorder this
yeah, it does reflect the order shown in the admin UI
but for example on the blog listing page, we want to order them differently, and I can't work out a good way to do so
Since the admin UI uses the fields to sort items in a collection, you could create a field to represent the sort order. As far as
reorderingthose, I don't believe there's a way of doing that out of the box, but I imagine you could create a global that has a relationship field, with
isSortable
set to true (that way you could drag and drop them into the order you want) and then run a hook on update that sets a sort order value to your collection items.
okay thanks, that's a great help. I've got this, and it works, but it gets a bit messy (especially with a lot of items) - is it possible to hide an item if it's present in the global array? i.e so I can't select an item that has already been added
const OrderedBlogPosts: GlobalConfig = {
slug: 'orderedBlogPosts',
fields: [
{
name: 'blogPostsOrder',
type: 'array',
minRows: 1,
maxRows: 999,
fields: [
{
name: 'blogPost',
type: 'relationship',
relationTo: 'blog-posts',
required: true,
unique: true,
},
],
},
],
}
Obviously
unique
stops it being saved, but a way to hide it from the relationship selection would be very helpful
You could remove the array altogether and just use the relationship field, but add
hasMany: true
to be able to select multiple and
isSortable: true
to allow you to change their order.
const OrderedBlogPosts: GlobalConfig = {
slug: 'orderedBlogPosts',
fields: [
{
name: 'blogPostsOrder',
type: 'relationship',
relationTo: 'blog-posts',
required: true,
unique: true,
hasMany: true,
admin: {
isSortable: true,
},
},
],
}
That's the ticket 🙌
Star
Discord
online
Get dedicated engineering support directly from the Payload team.