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,
},
],
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
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;
},
}
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
Discord
online
Get dedicated engineering support directly from the Payload team.