sanity icon indicating copy to clipboard operation
sanity copied to clipboard

Disable array Add Item button

Open bhargav-bkpatel opened this issue 3 years ago • 1 comments
trafficstars

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.

Screenshot 2022-05-12 at 11 14 03 AM

Screenshot 2022-05-12 at 11 15 32 AM

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.

bhargav-bkpatel avatar May 12 '22 05:05 bhargav-bkpatel

Please I need exactly the same. Can you please implement this feature?

Sulaymon333 avatar Jul 06 '22 16:07 Sulaymon333

This is solved in Sanity Studio v3 https://github.com/sanity-io/sanity/pull/3797

kmelve avatar Jan 11 '23 19:01 kmelve

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 avatar Apr 20 '23 11:04 ptimson

@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?

notflip avatar Mar 17 '24 06:03 notflip