Preventing duplicates of a reference type from being entered into an array in Sanity.io
7 replies
Last updated: Jan 24, 2022
D
Hey!
Is it possible to prevent duplicates of a reference type from being entered into an array? I'm making a quiz and in the quiz there is a question where a user is allowed to choose images. Each image needs to be tagged with a collection. I'm able to get this to work, but I would like to prevent the tag("collection") from being added to an image more than once. I'll post my code in a comment below.
Is it possible to prevent duplicates of a reference type from being entered into an array? I'm making a quiz and in the quiz there is a question where a user is allowed to choose images. Each image needs to be tagged with a collection. I'm able to get this to work, but I would like to prevent the tag("collection") from being added to an image more than once. I'll post my code in a comment below.
Jan 24, 2022, 1:46 PM
D
export default { name: "imageOptions", title: "Image Options", type: "object", fields: [ { name: "images", title: "Images", type: "array", of: [ { name: "image", title: "Image", type: "image", fields: [ { name: "alt", title: "Alternative text", type: "localeString", }, { name: "tags", title: "tags", type: "array", of: [ { type: "reference", to: [{ type: "collections" }], }, ], }, ], }, ], }, ], };
Jan 24, 2022, 1:46 PM
A
Hey User. This should be possible by adding a
You'd add it like this:
And then you should see that Studio starts validating it accordingly:
unique()validation rule (https://www.sanity.io/docs/array-type#unique()-49ee9907c730 ) to the
tagsarray.
You'd add it like this:
{ name: "tags", title: "tags", type: "array", validation: Rule => Rule.unique(), of: [ { type: "reference", to: [{ type: "collections" }], }, ], },
Jan 24, 2022, 1:55 PM
D
WOW!! That is exactly what I needed. Thank you so much for the quick reply.
Jan 24, 2022, 2:00 PM
D
Can I ask a quick follow up? is it possible to setup the reference as a tags layout? I haven't been able to get it to work.
something like...
something like...
{ name: "tags", title: "tags", type: "array", options: { layout: 'tags' }, validation: Rule => Rule.unique(), of: [ { type: "reference", to: [{ type: "collections" }], }, ], }
Jan 24, 2022, 2:02 PM
A
Unfortunately the tag layout only works for an array of strings at the moment, not references š.
Jan 24, 2022, 2:12 PM
D
NP, Thanks for the help!
Jan 24, 2022, 2:13 PM
A
No problem. Let us know if you have any other questions!
Jan 24, 2022, 2:14 PM
Sanityā build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.