Creating this from
#967097582721572937(
https://discord.com/channels/967097582721572934/967097582721572937/1089952369497878608).
CC:
@364124941832159242Hey
@107749572717092864i'd just build a custom
Fieldcomponent for your
codefield that's just a little "wrapper" around the built-in Code field
there, you can use the
useFormFieldshook to retrieve the field's value that will determine your code field's language
and then adjust the props, and send to the built-in Code field
That's awesome 😱
Is it a package?
no, you want to render the built-in field straight from Payload itself
we don't expose the built-in Code field directly, but you can easily import it from dist
import CodeField from 'payload/dist/admin/components/forms/field-types/CodeOk, perfect. Thank you!
To render this custom field i need to use the
uitype?
no, you would want to use the
codefield itself
because you still want to store the data in the same way that the
type: 'code'field will do
the
uifield type will not store anything in the database at all
that field type is good for cases where you just wanna inject a button, or a third-party integration, or something, into the admin UI - - but not store data
instead, what you want to do is just have a code field, but simply render a custom code field component
Ok, got it. I have to use the
admin.components.Fieldproperty 😅
I made it works with the following code.
import {useFormFields} from 'payload/components/forms'
import CodeField from 'payload/dist/admin/components/forms/field-types/Code'
import type {Block, SelectField} from 'payload/types'
import {createElement} from 'react'
import type {Entries} from 'type-fest'
const LANGUAGES = {
go: 'Go',
javascript: 'JavaScript',
php: 'PHP',
rust: 'Rust',
typescript: 'TypeScript',
}
export default {
fields: [
{
name: 'language',
options: (Object.entries(LANGUAGES) as Entries<typeof LANGUAGES>).map(
([key, value]) => ({
label: value,
value: key,
})
),
required: true,
type: 'select',
},
{
name: 'code',
required: true,
type: 'code',
admin: {
components: {
Field(field: SelectField & {path?: string}) {
const language = useFormFields(
([fields]) => fields[`${field.path?.replace('code', 'language')}`]
)
const value = language.value as keyof typeof LANGUAGES
if (LANGUAGES[value] === undefined) {
return null
}
return createElement(CodeField, {
admin: {
language: value,
},
name: field.name,
path: field.path,
})
},
},
language: 'php',
},
},
],
slug: 'code',
} satisfies BlockStar
Discord
online
Get dedicated engineering support directly from the Payload team.