Unlock seamless workflows and faster delivery with our latest releases- get the details

Using initialValueTemplates to reference parent document fields

2 replies
Last updated: Nov 1, 2024
Hi, I want to use initialValueTemplates and create a document using the values in the parent document. According to the doc https://www.sanity.io/docs/initial-value-templates#febce15880e2 I can pass the id of the parent document, but it is just a string. Is there any way I can get the values of the specifications field (it's a ref array) to insert it in the current document?
Nov 1, 2024, 2:20 PM
i think i can use context.getClient and get field using groq, but is it the right way?
Nov 1, 2024, 2:34 PM
if interesting, i solve this like that
templates: (prev, context) => [
      ...prev,
      {
        id: 'product-by-category',
        title: 'Product by Category',
        schemaType: 'product',
        parameters: [{name: 'category', type: 'string'}],
        value: async(params: any) => {
          const category = await context.getClient({apiVersion: '2024-11-01'}).fetch(`*[_type == "category" && _id == $category][0]{_id, characteristics}`, {category: params.category})
          const characteristics = category.characteristics;
          return{
          category: {_type: 'reference', _ref: category._id},
          characteristics: characteristics.map((c: any) => ({_type: 'partCharacteristic', characteristic: {_type: 'reference', _ref: c._ref}})),
        }},
      },
    ],
  },
Nov 1, 2024, 3:03 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.

Was this answer helpful?