Adding multiple categories to a product in Sanity.io
11 replies
Last updated: Jun 15, 2023
A
Hello devs, How I can assign two categories to the same product? like a shirt could be in Featured Category as well as Shirt category
Jun 14, 2023, 10:07 PM
Jun 14, 2023, 10:09 PM
A
import { defineType } from "sanity";
export const category = defineType({
name: "category",
title: "Category",
type: "array",
fields: [
{
name: "name",
title: "Category Name",
type: "string",
},
],
});
Jun 14, 2023, 10:17 PM
A
getting this error on fields:Argument of type '{ name: "category"; title: string; type: "array"; fields: { name: string; title: string; type: string; }[]; }' is not assignable to parameter of type '{ type: "array"; name: "category"; } & Omit<ArrayDefinition, "preview">'.
Jun 14, 2023, 10:18 PM
A
Also, I'm referencing this into my product file
Jun 14, 2023, 10:19 PM
A
Like this
export const products = {
name: "products",
title: "Products",
type: "document",
fields: [
{
name: "title",
title: "Product Title",
type: "string",
},
defineField({
name: "category",
title: "Product Category",
type: "reference",
to: [
{
type: "category",
},
],
}),
],
};
Jun 14, 2023, 10:22 PM
A
Sorry if I'm disturbing with this huge code coz I'm new to this:)
Jun 14, 2023, 10:22 PM
References can only be to documents, but it looks like your reference in
productsis to an array type. One way I might do this is to make
categorya document type containing a string (
titleis a convention), and then add an array of references (to
category) in your
productsschema.
Jun 14, 2023, 10:51 PM
A
All I want is to add an option so that I can attach 2 categories to the same product. Stucked since yesterday😟
Jun 15, 2023, 8:22 AM
From those two recent screenshots,
categorylooks good. Can you open
productsand replace lines 38-47 with this?
defineField({ name: "categories", title: "Product Categories", type: "array", of: [ defineArrayMember({ name: "category", title: "Product Category", type: "reference", to: [{ type: "category" }], }), ], })
Jun 15, 2023, 2:50 PM
(Note that the
defineArrayMemberwrapper function isn’t necessary, so omit it if you want. It improves support in your editor, like
defineType).
Jun 15, 2023, 2:51 PM
A
Thank you very much, Amazing support you're providing at Sanity.❤️
Jun 15, 2023, 4:34 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.