qbeauperin
qbeauperin

Reputation: 589

NetlifyCMS - How to get a relation item's data within a custom editor component preview?

I'm building a custom "rich link" editor component composed of a single relation widget and displaying the selected item's title, thumbnail, and excerpt:

CMS.registerEditorComponent({ 
    label: 'Rich link',
    id: 'rich_link',
    fields: [
        {
            label: 'Post',
            name: 'post',
            widget: 'relation',
            collection: 'posts',
            value_field: 'slug',
            display_fields: ['title'],
            search_fields: ['title']
        }
    ],
    pattern: /\{% include components\/rich-link\.html post="(.*?)" %\}/,
    fromBlock: function (match) {
        return match ? {
            post: match[1]
        } : '';
    },
    toBlock: function (obj) {
        return `{% include components/rich-link.html post="${obj.post || ''}" %}`
    },
    toPreview: function (obj) {
        return `
            <a class="rich-link" href="${ '' }" title="${ '' }">
                <span class="rich-link__image" style="background-image: url(${ '' })"></span>
                <span class="rich-link__content">
                    <span class="rich-link__tags">${ '' }</span>
                    <span class="rich-link__title">${ '' }</span>
                </span>
            </a>
        `;
    },
});

The problem is that the relation field only store the one value_field value (in my case the post slug), but in order to generate the preview, I need the rest of the post's data.

"Regular" previews have access to the fieldsMetaData prop within the preview component which holds all of the relation item's data, but I can't seem to find an equivalent in the case of an editor component.

I could use some kind of hack and concatenate all the data within the value_field (eg: value_field: '{{slug}}|{{title}}) but on top of being particularly gross, it would also make the content static once the relation is established and any change to the post afterward would not be reflected in that component.

Any idea how to access that data from within the toPreview function?

Upvotes: 1

Views: 160

Answers (0)

Related Questions