RD Pennell
Community Engineer at Sanity.io
RD is located at Richmond, CA
Use a publishedOnce field to control other fields.
This schema is for an older version of Sanity Studio (v2), which is deprecated.
Learn how to migrate to the new Studio v3 →{
name: 'publishedOnce',
type: 'boolean',
hidden: true
},
{
title: 'Read-only sometimes',
name: 'readOnlySometimes',
type: 'string',
readOnly: ({ document }) => !document?.publishedOnce
},
//...
"parts": [
//...
{
"implements": "part:@sanity/base/document-actions/resolver",
"path": "resolveDocumentActions.js"
}
]
import {useState, useEffect} from 'react'
import {useDocumentOperation} from '@sanity/react-hooks'
export default function SetAndPublishAction(props) {
const {patch, publish} = useDocumentOperation(props.id, props.type)
const [isPublishing, setIsPublishing] = useState(false)
useEffect(() => {
// if the isPublishing state was set to true and the draft has changed
// to become `null` the document has been published
if (isPublishing && !props.draft) {
setIsPublishing(false)
}
}, [props.draft])
return {
disabled: publish.disabled,
label: isPublishing ? 'Publishing…' : 'Publish',
onHandle: () => {
// This will update the button text
setIsPublishing(true)
// Set publishedAt to current date and time
patch.execute([{set: {publishedOnce: true}}])
// Perform the publish
publish.execute()
// Signal that the action is completed
props.onComplete()
}
}
}
import defaultResolve, { PublishAction } from 'part:@sanity/base/document-actions'
import SetAndPublishAction from './setAndPublishAction'
export default function resolveDocumentActions(props) {
return defaultResolve(props)
.map(Action =>
Action === PublishAction ? SetAndPublishAction : Action
)
}
It can be pretty hard to use an existing field in your document to distinguish whether or not something has been published before. The simplest solution is to add a hidden publishedOnce
boolean field that updates via a document action.
Community Engineer at Sanity.io
Use the renderDefault method to show or hide fields.
Go to Conditionally show a field based off of a value inside of a referenceThis will allow you to display an array of references as a checklist from which you can multi-select.
Go to V3 version of Display an array of references as a checklistPopulate your list options in a string schema using an external API
Go to Asynchronous List Options ComponentUse the renderDefault function to easily control your available array options.
Go to Filter Array Options Based on the Current User Role