#Payload V3 : how to get the custom Field component save the value in type Array

3 messages · Page 1 of 1 (latest)

amber rose
#

Hi there, trying to get that when i am in collection array type and need a custom field and it showing and adding to the field that i need but when i trying to save the changes in browser, it reset to empty value. I think mybe someting with useField path is wrong?

export const CustomPublishOnVersion: Field = {
    name: 'publishOnVersion',
    type: 'array',
    label: 'Publish on Version',
    minRows: 1,
    maxRows: 7,
    interfaceName: 'PublishOnVersion',
    admin: {
        position: 'sidebar',
    },
    fields: [
        {
            name: 'getVersion',
            type: 'text',
            label: 'get Version',
            admin: {
                components: {
                    Field: FindVersion,
                },
            },
            required: true,
        },
    ]
}

in FindVersion.tsx

'use client'
import React, { useEffect, useState } from 'react'
import { useField } from '@payloadcms/ui/forms/useField'
import { TextFieldProps, TextInput, TextInputProps } from '@payloadcms/ui/fields/Text'
import { Button, Drawer, DrawerToggler } from '@payloadcms/ui/elements'

type Props = { path: string }

export const FindVersion: React.FC<Props> = ({path}) => {
    const {value, setValue} = useField<string>({path})

    useEffect(() => {
        // some functions
    })

return (
        <>
          <TextInput value={value} path={path} name={path} onChange={e => setValue(e.target.value)} ></TextInput>
          <a onClick={() => {setValue('Hello')}}>Click</a>
        </>
    )
}
misty cypressBOT
amber rose
#

ok, found it:

just import useFieldProps

import { useFieldProps } from '@payloadcms/ui/forms/FieldPropsProvider'

export const FindVersion: React.FC = () => {
  const {indexPath, path: pathFromContext, permissions, readOnly: readOnlyFromContext, schemaPath} = useFieldProps()
  const {value = '', setValue} = useField<string>({path: pathFromContext})
}

return (
<>
  <TextInput
                name={pathFromContext}
                path={pathFromContext}
                value={value}
                onChange={e => {
                    setValue(e.target.value)
                }}
            />
</>
)