Is it possible to add some custom config in a field config?

default discord avatar
Stupidism
last year
1 1

We're building a custom UI field. It looks like this:

import { merge } from 'lodash';
import { Field } from 'payload/types';

import { LinkTo } from './ui/LinkTo';

interface Options {
  collectionSlug: string;
}

// By dynamically building fields in code configurations are reusable and concise
export const linkTo = (options: Options, overrides?: Partial<Field>): Field => {
  const { collectionSlug } = options;

  return merge<Field, Partial<Field> | undefined>(
    {
      name: 'linkTo',
      type: 'ui',
      admin: {
        position: 'sidebar',
        components: {
          Field: (props: Field) => (
            <LinkTo {...props} collectionSlug={collectionSlug} />
          ),
        },
      },
    },
    overrides
  );
};

// usage

const Tag = {
  slug: 'tags',
  fields: [
    //...
    linkTo({ collectionSlug: 'tags' }),
    //...
  ]
}

You can see two twisted place:

  1. linkTo({ collectionSlug: 'tags' }) I already passed a slug in to collection config, but I still need to pass it again.

I think if I can get the current collection slug directly in the LinkTo component would be much easier.

const config = useCollectionConfig();
  1. LinkTo already gets the field config as the input props, but I cannot pass any additional config to it except writing a wrapper component like this.

I think if I can pass some custom configurations would be much easier:


    {
      name: 'linkTo',
      type: 'ui',
      admin: {
        position: 'sidebar',
        collectionSlug,
        components: LinkTo,
      },
      // or an explicit field to pass custom configs
      custom: {
        collectionSlug,
      }
    },

// Get collectionSlug from custom config
const LinkTo = ({ admin: { collectionSlug } }) => {

}
  • default discord avatar
    Stupidism
    last year

    I found I can get the current collection info with hook: useDocumentInfo. It can solve this specific issue for now:

      const { collection } = useDocumentInfo();
      const collectionSlug = collection?.slug || '';
    
    // or in non react component
    
    
    const getCurrentCollectionSlug = () => {
      const match =
        /\/admin\/collections\/([a-z-]*)\/.*/.exec(window.location.pathname) || [];
    
      if (!match) return '';
    
      return match[1];
    };
    
Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.