Set initial value of reference field to current document in Sanity schema

14 replies
Last updated: Aug 8, 2022
Hi all! We’re trying to figure out a way to include redirects as part of our schema. My initial thought is to reference a redirect document type, one of the fields being a reference to the current document. Is there a way to set the initial value from the current document?
AI Update

Yes, you can absolutely set initial values from the current document when creating a referenced redirect document! The key is using parameterized Initial Value Templates defined in your schema.templates configuration.

Configuration in sanity.config.ts

Define your parameterized template in the schema.templates array in your Sanity config:

// sanity.config.ts
import {defineConfig} from 'sanity'

export default defineConfig({
  // ...rest of config
  schema: {
    templates: (prev) => [
      ...prev,
      {
        id: 'redirect-from-document',
        title: 'Create Redirect',
        schemaType: 'redirect',
        parameters: [
          {name: 'sourceDocId', type: 'string'}
        ],
        value: (params) => ({
          sourceDocument: {
            _type: 'reference',
            _ref: params.sourceDocId
          }
        })
      }
    ]
  }
})

Schema Definition

Your redirect schema might look like:

defineType({
  name: 'redirect',
  type: 'document',
  fields: [
    defineField({
      name: 'sourceDocument',
      type: 'reference',
      to: [{type: 'page'}, {type: 'post'}] // whatever types you're redirecting from
    }),
    defineField({
      name: 'targetUrl',
      type: 'url'
    })
  ]
})

Using the Template in Structure Builder

To trigger this template from within a document's context, you can use the Structure Builder to pass the current document's ID as a parameter:

// structure.ts
export const structure = (S) =>
  S.list()
    .title('Content')
    .items([
      S.documentTypeListItem('page').child((pageId) =>
        S.document()
          .schemaType('page')
          .documentId(pageId)
          .views([
            S.view.form(),
            S.view.component(() => /* your custom view */).title('Redirects')
          ])
      ),
      // ... other items
    ])

Within a custom document action or view, you can create a new redirect using the template:

.initialValueTemplates([
  S.initialValueTemplateItem('redirect-from-document', {sourceDocId: documentId})
])

Async Values with Additional Data

If you need to fetch additional data from the parent document (not just the reference), you can make the value function async:

{
  id: 'redirect-from-document',
  title: 'Create Redirect',
  schemaType: 'redirect',
  parameters: [
    {name: 'sourceDocId', type: 'string'}
  ],
  value: async (params, context) => {
    const client = context.getClient({apiVersion: '2024-11-01'})
    const sourceDoc = await client.fetch(
      `*[_id == $id][0]{_id, slug}`,
      {id: params.sourceDocId}
    )
    
    return {
      sourceDocument: {_type: 'reference', _ref: params.sourceDocId},
      // Pre-populate other fields based on the source doc
      oldSlug: sourceDoc?.slug?.current
    }
  }
}

The context parameter provides access to getClient, currentUser, schema, dataset, and projectId, giving you full flexibility to build sophisticated initialization logic based on the parent document's data.

This approach ensures that when creating a redirect from a specific document's context, the reference is automatically populated, making the editorial workflow much smoother!

Show original thread
14 replies
Hey
user Q
! To clarify, are you trying to set a redirect reference initial value on the document?
Yes.
Got it. Then, if you're setting it on the document level:
export default {
  name: 'yourDocument',
  title: 'Your Document',
  type: 'document',
  initialValue: {
    redirect: {
      _type: 'reference',
      _ref: <_id-of-redirect-document>
    }
  }
  //...
}
Excellent! Thank you. Is there anyway to get the current document _ref ?
The current document _ref would be the _id of the current document. Or am I misunderstanding your question?
For example I can’t get access to the current document like this:
initialValue: ({ document }) =&gt; { console.log(document);
},
We want to view the redirects for the article on the article document, so we added an array field to reference the redirect document type.
Ah, I see. You won't be able to get the document Id in an initial value, because a document does not have an id when it's first created. An Id will be assigned after an edit is made.
Ahh I see. How would one do it after it is created? Could you do it if you were to edit the already created doc?
I think you'd need to create a custom input component. I can put an example together in about 30 mins for you!
wow thanks!
This is just an example and doesn't have any functionality for editing the incoming redirects, but it's an example of how you'd begin putting together the component:
import React, { useState, useEffect } from 'react';
import { withDocument } from 'part:@sanity/form-builder';
import { FormField } from '@sanity/base/components';
import client from 'part:@sanity/base/client';

const studioClient = client.withConfig({ apiVersion: '2021-10-21' });

const Redirects = React.forwardRef((props, ref) => {
  const [redirects, setRedirects] = useState([]);

  const {
    type, // Schema information
    value, // Current field value
    readOnly, // Boolean if field is not editable
    markers, // Markers including validation rules
    presence, // Presence information for collaborative avatars
    compareValue, // Value to check for "edited" functionality
    onFocus, // Method to handle focus state
    onBlur, // Method to handle blur state
    onChange, // Method to handle patch events,
    parent,
    document,
  } = props;

  // Creates a change handler for patching data

  const inputId = useId();

  useEffect(() => {
    const getRedirects = async () => {
      if (!document._id) return;
      await studioClient
        .fetch(`*[_type =='redirect' && references($id)]`, { id: document._id })
        .then(setRedirects);
    };

    getRedirects();
  }, [document._id]);

  return (
    <FormField
      description={type.description} // Creates description from schema
      title={type.title} // Creates label from schema title
      __unstable_markers={markers} // Handles all markers including validation
      __unstable_presence={presence} // Handles presence avatars
      compareValue={compareValue} // Handles "edited" status
      inputId={inputId} // Allows the label to connect to the input field
    >
      {redirects && redirects.map(redirect => <p>{redirect.title}</p>)}
    </FormField>
  );
});

export default withDocument(Redirects);
Perfect. Thanks so much!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?