Skip to content

Instantly share code, notes, and snippets.

@elliott-w
Last active August 9, 2024 12:11
Show Gist options
  • Save elliott-w/ba3af93a6ed535a7bdfc065db80b0870 to your computer and use it in GitHub Desktop.
Save elliott-w/ba3af93a6ed535a7bdfc065db80b0870 to your computer and use it in GitHub Desktop.
Payload v3 Custom Form in Admin
import { FC } from 'react'
import { Form, FormSubmit, Gutter, RenderFields } from '@payloadcms/ui'
import { mapFields } from '@payloadcms/ui/utilities/buildComponentMap'
import { AdminViewProps, Field, WithServerSidePropsComponentProps } from 'payload'
import { WithServerSideProps as WithServerSidePropsGeneric } from '@payloadcms/ui/shared'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { buildStateFromSchema } from '@payloadcms/ui/forms/buildStateFromSchema'
type WithServerSidePropsPrePopulated = React.FC<
Omit<WithServerSidePropsComponentProps, 'serverOnlyProps'>
>
const fields: Field[] = [
{
name: 'test',
type: 'text',
},
]
const CustomAdminView: FC<AdminViewProps> = async ({ initPageResult }) => {
const {
req: {
i18n,
payload: { config },
payload,
},
req,
visibleEntities,
} = initPageResult
const WithServerSideProps: WithServerSidePropsPrePopulated = ({ Component, ...rest }) => {
return (
<WithServerSidePropsGeneric
Component={Component}
serverOnlyProps={{
i18n,
payload,
}}
{...rest}
/>
)
}
const fieldMap = mapFields({
WithServerSideProps,
config,
i18n,
fieldSchema: fields,
disableAddingID: true,
payload,
})
const initialState = await buildStateFromSchema({
fieldSchema: fields,
preferences: { fields: {} },
req,
})
return (
<DefaultTemplate visibleEntities={visibleEntities} i18n={i18n} payload={payload}>
<Gutter>
<Form method="POST" action="/api/custom-action" fields={fields} initialState={initialState}>
<RenderFields fieldMap={fieldMap} path="" schemaPath="" readOnly={false} />
<FormSubmit>Submit</FormSubmit>
</Form>
</Gutter>
</DefaultTemplate>
)
}
export default CustomAdminView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment