Hide field when initial value exists in Sanity
Yes! You can absolutely hide fields based on whether there's an initial value present. The conditional fields feature in Sanity Studio lets you use a hidden property with a callback function that has access to various context including the initial value.
Here's how you can do it:
{
name: 'myField',
type: 'string',
hidden: ({value}) => {
// Hide the field if there's an initial value
return !!value;
}
}The callback function receives several useful parameters:
value- The current value of the field (which would include any initial value)parent- The parent object containing this fielddocument- The entire document being editedcurrentUser- Information about the current user
If you need to check for initial values in a more complex scenario, like checking if a parent object has certain initial values, you can use the parent parameter:
{
name: 'conditionalField',
type: 'string',
hidden: ({parent}) => {
// Hide if parent has an initial value for a specific field
return !!parent?.someInitialField;
}
}Keep in mind that if you're hiding a field that's marked as required, validation will still run even when hidden. You might need to implement conditional validation to handle this:
validation: (Rule) =>
Rule.custom((currentValue, { parent }) => {
// Only require if the field would be visible
return shouldBeVisible(parent) && !currentValue
? "This field is required."
: true
})This approach works great for reducing cognitive load and showing editors only the fields that are relevant to their current context!
Show original thread4 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.