sanity
sanity copied to clipboard
Disable array Add Item button
I want to disable array Add Item button after adding limited number of items , I am using validation Rule.length() method provided by sanity to limit the length of array but that's not working. It only shows the error but user can see Add Item button and also can add items which is not the desired performance.
Image I have added below, where i want to disable array button after adding 1 item into it.


You can see in above image that after adding 2 items in array, But it only showing error instead I want to disable an array add button after adding a single item into it.
Please I need exactly the same. Can you please implement this feature?
This is solved in Sanity Studio v3 https://github.com/sanity-io/sanity/pull/3797
For future reference:
Grabs the max items from validation and compares against total items.
// ArrayMaxItems.tsx
import {ArrayOfPrimitivesInputProps, ArrayOfPrimitivesFunctions, ArrayInputFunctionsProps, ArraySchemaType} from 'sanity'
function ArrayFunctions(props: ArrayInputFunctionsProps<string | number | boolean, ArraySchemaType>) {
const valRules = props?.schemaType?.validation?.[0]?._rules || []
const max = valRules.find(r => r.flag === 'max')?.constraint
const total = props?.value?.length || 0
if (!isNaN(max) && total >= max) return null
return <ArrayOfPrimitivesFunctions {...props} />
}
export default function ArrayMaxItems(props: ArrayOfPrimitivesInputProps) {
return props.renderDefault({...props, arrayFunctions: ArrayFunctions})
}
// schema
defineField({
type: 'array',
name: 'myArray',
title: 'My Array Max 1 item',
components: { input: ArrayMaxItems },
of: [{ type: 'myObject' }],
validation: (rule) => rule.max(1),
}),
@ptimson I'm getting Deprecated symbol used, consult docs for better alternative for the const valRules = props?.schemaType?.validation?.[0]?._rules || [] line, and idea how to fix this?