Hide field when initial value exists in Sanity

4 replies
Last updated: Feb 12, 2024
Does anyone know how to hide a field if you're in a context where there is an initial value?
AI Update

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 field
  • document - The entire document being edited
  • currentUser - 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 thread
4 replies
What I'm trying to do is to hide a field if an initial value is passed. Meaning if that the field has a predetermined value, the display of the field is not needed.
I ended up doing something very ugly! I checked the URL to see if I was in the context that I was looking for.
I have an entity called person, and the person must belong to a company. The person can be edited from the root of the menu, but it can also be edited when going to a company, and be selected as a sub-page. This means that the reference-field to the company on the person would only be relevant when not editing from a sub-page.
Ugly AF, but it works, and it will work as long a the URL structure does not change.

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.

Was this answer helpful?