I have input for selecting users, but I want to see their avatars in the options
Hello, I need your advice please 🥺
is this on the admin panel you want to do this?
And you have a field on a collection with type relationship to the users collection?
something like that?
yes!!!
youll want to create a custom component for this. Look into the docs here about it:
https://payloadcms.com/docs/fields/overview#custom-componentsheres a super rough idea. Make this as the server comp which you add in the field
admin.components.Field
import { RelationshipFieldServerProps } from 'payload'
import Client from './comp.client'
export default async function CustomUserRelationshipField({
path,
field,
payload,
}: RelationshipFieldServerProps) {
if (field.type === 'relationship') {
const { relationTo } = field
if (Array.isArray(relationTo)) {
throw new Error('relationTo must be a single collection slug')
}
if (relationTo !== 'users') {
throw new Error('relationTo must be a equal to the users collection')
}
const res = await payload.find({
collection: 'users',
where: {},
})
const docs = res.docs
return <Client docs={docs} path={path} />
}
return <>NOT SETUP</>
}then the Client component, this is where you use the
useFieldhook passing it the path.
'use client'
import React from 'react'
import { User } from '@payload-types'
import { useField } from '@payloadcms/ui'
export default function Client({ docs, path }: { docs: User[]; path: string }) {
const { value, setValue } = useField({ path })
return (
<div className="custom-select-container">
<select
value={value as string}
onChange={(e) => setValue(e.target.value)}
className="custom-select"
>
<option value="">Select a user</option>
{docs.map((doc) => (
<option key={doc.id} value={doc.id.toString()}>
{doc.email} (ID: {doc.id})
</option>
))}
</select>
</div>
)
}then add this to the field you want to do it on assuming its a field with relationship to the users collection.
admin: {
components: {
Field: 'path-to-server-comp/CustomUserRelationshipField',
},
},this is just a basic implementation and doesn't show any image. but if you can get to this point you would be able to change the component ui and use the
doc.avatarfield to either show a payload Media comp or an img if its just a src string. Might also have to make a custom select because I know you can't put
<img/>comps directly inside a html
<option/>tag.
oh, thanks a lot for such extensive answer!
I appreciate that
and will try to implement as you've said
Let me know if you can get what you want working.
Anytime 👍🏽
that's really kind from you! thanks, and best wishes!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.