Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Create a new reference document with parameterised initial Values

By Saskia Bobinska

If you want to make it possible to use parameterised initialValue templates in reference fields, this is how!

CreateNewRefInput.tsx

import {AddIcon} from '@sanity/icons'
import {Button, Flex, useToast} from '@sanity/ui'
import {pathToString, useClient, useFormValue, InputProps} from 'sanity'
import {IntentLink} from 'sanity/router'
import styled from 'styled-components'

const CreateNewRefInput = (props: InputProps) => {
  // in this example we use the language field value as the params later
  const language = useFormValue(['language']) as string

  return (
    <div>
      <Flex gap={2}>
        <FullWidth>{props.renderDefault(props)}</FullWidth>
        {/* You can also add the "Add new" tooltip like this https://www.sanity.io/ui/docs/primitive/tooltip */}{' '}
        <IntentLink
          intent="create"
          params={[{type: 'REFERENCED_DOC_TYPE', template: 'TEMPLATE_USED'}, {language: language}]}
        >
          <Button
            icon={AddIcon}
            mode="ghost"
          />
        </IntentLink>
      </Flex>
    </div>
  )
}
const FullWidth = styled.div`
  width: 100%;
`
export default CreateNewRefInput

Add the CreateNewRefInput to your reference field

    defineField({
      type: 'reference',
      name: 'reference',
      title: 'Reference',
      to: [{type: 'REFERENCED_DOC_TYPE'}],
      components: {
        input: CreateNewRefInput,
      },
      options: {
        disableNew: true,
      },
    }),

define your initialValue template in your sanity.config.ts

    {
      id: 'TEMPLATE_USED',
      title: 'This is a template',
      description: '...',
      schemaType: 'REFERENCED_DOC_TYPE',
      parameters: [{name: 'language', type: 'string'}],
      value: (params) => ({
        language: params.language,
      }),
    },

Using the Create New button in reference fields will only allow you to use initialValue templates but not add any params to the template.

In order to be able to for example, use a value from the document the reference field is used in, you need to set the reference option disableNew: true and add a custom input component, and a parameterised IntentLink button to the input.

Contributor

Other schemas by author