πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Create a dynamic 'Unmapped fields' group in your document definition

By William Iommi

A dynamic group filled with fields that don't have any defined group.

Custom function to enhance your Document definitions with an 'unmapped fields' group

import {DocumentDefinition, FieldGroupDefinition, ObjectDefinition} from 'sanity'
import {LinkRemovedIcon} from '@sanity/icons'

// this is the definition of our custom group for unmapped fields
const unmappedFieldsGroup: FieldGroupDefinition = {
  name: 'unmapped-fields',
  icon: LinkRemovedIcon,
  title: 'Unmapped Fields',
}


type DocumentObjectDefinitionType = DocumentDefinition | ObjectDefinition

export const enhancedGroupsDefinition = (definitions: DocumentObjectDefinitionType[]): DocumentObjectDefinitionType[]  => {
  
  const doMagic = (def: DocumentObjectDefinitionType) => {
    // Check if your document/object has any groups defined.
    if (def.groups && Array.isArray(def.groups) && def.groups.length > 0) {
      
      // Check if every field has a group defined.
      const everyFieldsHaveGroup = !!def.fields.every(
        (field) =>
          typeof field.group === 'string' || (Array.isArray(field.group) && field.group.length > 0)
      )

      // If some fields don't have a group, we can add our custom group.
      if (!everyFieldsHaveGroup) {
        // Add our custom group at the end of the list.
        def.groups.push(unmappedFieldsGroup)
        // Loop through all fields and add the unmapped group if a group is not defined.
        def.fields = def.fields.map((field) => {
          if (!field.group || (Array.isArray(field.group) && field.group.length === 0))
            field.group = unmappedFieldsGroup.name
          return field
        })
      }
    }
    return def
  }

  return definitions.map(doMagic)
}

Your sanity.config.js file with the applied function

import {enhancedGroupsDefinition} from '../../some-utility-method-file-blah-blah'

defineConfig({
  // your configuration
 schema: {
    types: [
      ...enhancedGroupsDefinition([Document1, Document2]),
    ],
  },
})

This is a small customization that allows you to have a dynamic group that only contains fields without an associated group. You can also choose to apply this customization only to a subset of documents.

For some workarounds to remove the 'all fields' tab, you can refer to this GitHub discussion.

Contributor

Other schemas by author

Is your Microcopy unique?

A custom validation to check if your Microcopy documents have unique keys and values for a specific namespace.

William Iommi
Go to Is your Microcopy unique?