defaultValue for a collection

default discord avatar
akacronoslast year
4

I'm trying to set a relationship field with a default value, but I don't know what exactly I have to pass.




// This is the field
{
      name: 'format',
      type: 'relationship',
      relationTo: 'categories',
      label: 'Formato',
      defaultValue: { category: 'Artículo' }, // use the text field of the relationship.
      admin: {
        // readOnly: true,
        position: 'sidebar',
      },
    },

// Relationship
fields: [
    {
      name: 'collectionFor',
      type: 'select',
      label: 'Colección',
      required: true,
      hasMany: true,
      index: true,
      options: [
        {
          label: 'Actividades',
          value: 'activities',
        },
        {
          label: 'Convocatorias',
          value: 'calls',
        },
        {
          label: 'Comunidades',
          value: 'communities',
        },
        {
          label: 'Proyectos',
          value: 'projects',
        },
        {
          label: 'Blog',
          value: 'blog',
        },
        {
          label: 'Formato',
          value: 'format',
        },
      ],
    },
    {
      name: 'category',
      type: 'text',
      label: 'Categoría',
      required: true,
      unique: true,
      index: true,
    },
  ],
  • default discord avatar
    thghlast year

    It's the id of the category:


    defaultValue: "abc123..."

    You will probably want to fetch a category each time that relationship is rendered and the value is empty. Then set the value. Maybe defaultValue takes an async function, would have to check the typing

  • default discord avatar
    ccz82last year

    Hi, I've had to implement this myself and this is how I did it:


    {
          name: 'categories',
          type: 'relationship',
          relationTo: 'categories',
          hasMany: true,
          defaultValue: async () => {
            const response = await fetch(`/api/categories`);
            const { docs } = await response.json();
            const categories = docs.map((category) => category.id);
            return categories;
          },
    }
  • default discord avatar
    akacronoslast year

    Thanks, I'm going to try this, I need to set a default and set to read only because thats the only category for that collection type.



    Thanks, this is how I did it:


    defaultValue: async () => {
      const response = await fetch(`/api/categories?where[category][equals]=Artículo`);
      const { docs } = await response.json();
      const category = docs[0].id;
    
      return category;
    },
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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