Ordered Galleries

Last updated 5 months ago

References are a powerful concept in GraphCMS. You can connect and reuse nearly any content model imaginable. Further, through the power of GraphQL, you can sort your content on nearly any field in that model. But sometimes, you need more control. There's simply not a derivable logic to account for taste, style and preference. A common issue for this is with photo galleries. Sorting by upload date is too brittle, and your content editors and art directors demand a more intuitive experience and control.

Sortable fields will become a native part of the experience very soon.

Until native support for this feature is built into the editor, here's a simply way to create sortable galleries. Here's a simple Gallery model and a Gallery Item model. It is possible to extend the internal Asset model, but we want to maintain the maximum flexibility with our data and therefore don't want to attach arbitrary data to our content.

"Gallery Models"

Do note that the relationship between Gallery and Gallery Item is a one-to-many relationship. Each Gallery Item can only belong to a single gallery. An image, which is an asset reference in our model, can be in as many Gallery Items as it wants, but the Gallery Item needs to be unique to each Gallery so that it can hold a sorting field.

Here's the settings for that sorting field that we'll add now.

"Sort Field"

Don't forget to make sure the field is required! You will have to handle making them unique on your own. If you have two entries with the same sorting number, they won't know their order!

Ok, content time. Let's make a gallery!

From there, all we need to do is query our gallery and apply the orderBy on our sort field.

{
galleries {
title
galleryItems(orderBy: sort_ASC) {
sort
image {
url
}
}
}
}

Try changing your sort numbering and run the query again. You can also reverse the order with sort_DESC as well.

Fork the CodePen below to try it out yourself! Just be sure to add in your own url, otherwise all you'll get are the dogs. Enjoy!