Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
    }
  }
}
like image 372
kizoso Avatar asked Feb 19 '19 16:02

kizoso


People also ask

What is sanity backend?

Sanity Datastore This is a schemaless backend that lets you store and query JSON documents, and subscribe to real-time changes. It comes with a query API that uses the query language GROQ to lets you quickly filter down to the documents you want and project exactly the data structured you want your content in.

What is sanity client?

Sanity Client requires the JavaScript runtime to have a global ES6-compliant Promise available. If your runtime environment doesn't provide a spec compliant Promise implementation, we recommend using native-promise-only, es6-promise or another spec-compliant implementation.

What is slug in sanity?

A schema type for slugs, typically used to create unique URLs. A typical slug field with title and description. A slug is a unique string (typically a normalized version of title or other representative string), often used as part of a URL.


1 Answers

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'
    }
  }
}
like image 54
knut Avatar answered Sep 19 '22 00:09

knut