How to show filename in image preview and set default position value?
Looking at your code, the issue with the title showing the position string instead of the filename is happening because when you add custom fields to an image in portable text, those fields get prioritized in the preview. To fix this and set a default value for the position field, here's what you need to do:
1. Fix the preview to show filename:
Add a preview configuration to your image block that explicitly selects the asset's original filename:
export default {
name: 'blockContent',
title: 'Content',
type: 'array',
of: [
{
type: 'block',
},
{
type: 'image',
fields: [
{
name: 'position',
title: 'Position',
type: 'string',
options: {
list: [
{title: 'Default', value: 'default'},
{title: 'Left', value: 'left'},
{title: 'Right', value: 'right'},
],
},
initialValue: 'default', // Sets default value
},
{
name: 'alt',
title: 'Alternative text',
type: 'localeString'
},
],
preview: {
select: {
title: 'asset.originalFilename',
subtitle: 'position',
media: 'asset'
}
}
},
]
}The preview configuration uses select to pick which fields to display. By selecting asset.originalFilename as the title, you'll see the actual filename. I've also added the position as a subtitle so you can still see that information at a glance.
2. Set a default value for position:
Simply add initialValue: 'default' to your position field (shown in the code above). This will pre-select "Default" whenever a new image is added.
If you want even more control over the preview display, you can add a prepare function to format the information:
preview: {
select: {
filename: 'asset.originalFilename',
position: 'position',
media: 'asset'
},
prepare({filename, position, media}) {
return {
title: filename || 'Untitled',
subtitle: position ? `Position: ${position}` : undefined,
media: media
}
}
}This gives you complete control over how the preview appears in your portable text editor!
Show original thread2 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.