kizoso
kizoso

Reputation: 1246

How to create default value in field using sanity.io?

Is it possible to add to sanity field with default value? How can I extend it? I want to create some fields with default variables. For example I have this code:

export default {
  name: 'name',
  title: 'name',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'title',
      type: 'string',
      validation: Rule => Rule.required(),
    },
    {
      name: 'key',
      title: 'key',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      }
    },
    {
      name: 'geo',
      title: 'geo',
      type: 'geopoint',
      //default: {"lat": 1,"lng": 2}
    },
    {
      name: 'tel',
      title: 'tel',
      type: 'string',
      //default: '122334554565'
    },
  ],
  preview: {
    select: {
      title: 'title'
    }
  }
}

Upvotes: 7

Views: 5487

Answers (1)

knut
knut

Reputation: 391

You can now use Initial Value Templates to do this:

export default {
  name: 'name',
  title: 'name',
  type: 'document',
  initialValue: {
    tel: 122334554565,
    geo: {
      _type: 'geopoint',
      lat: 1,
      lng: 2
    }
  },
  fields: [
    {
      name: 'title',
      title: 'title',
      type: 'string',
      validation: Rule => Rule.required(),
    },
    {
      name: 'key',
      title: 'key',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      }
    },
    {
      name: 'geo',
      title: 'geo',
      type: 'geopoint',
    },
    {
      name: 'tel',
      title: 'tel',
      type: 'string',
    },
  ],
  preview: {
    select: {
      title: 'title'
    }
  }
}

Upvotes: 7

Related Questions