While the DatoCMS interface does offer basic controls for specifying which fields of a model should be used as the record title and "image preview" within the interface, you may encounter scenarios where you need more advanced control over the presentation of your content.
To address this, you can use the buildItemPresentationInfo
hook, which enables you to customize the presentation of your records according to your specific needs. This level of flexibility empowers you to create a unique and tailored user experience that aligns with your goals.
The buildItemPresentationInfo
hook can be used in numerous ways. For example, you can:
Combine multiple fields to present a record;
Generate a preview image on the fly;
Perform asynchronous API requests to third parties to compose the presentation.
These are just a few examples of what you can do with the buildItemPresentationInfo
hook. The possibilities are limitless, and you can use this hook to create the exact presentation you need.
The buildItemPresentationInfo
hook is called every time a record needs to be presented, and it can return an object with title
and imageUrl
attributes, or undefined
, if the plugin does not want to interfere with the default presentation:
import { connect , Item , OnBootCtx } from "datocms-plugin-sdk" ;
connect ( {
async buildItemPresentationInfo ( item : Item , ctx : OnBootCtx ) {
return {
title : '' ,
imageUrl : '' ,
}
} ,
} ) ;
imageUrl can also be a Data URL While the imageUrl
attribute normally is a normal URL starting with https://
, you can also pass a Data URL . Data URLs can be useful to generate an image on-the-fly in JavaScript (for example, using canvases ).
A basic example Suppose that one of the models in a DatoCMS project is used to represent products in a ecommerce frontend, and that each product record in DatoCMS is linked to a particular Shopify product via its handle.
Shopify holds information like inventory availability, prices and variant images. We don't want to replicate the same information in DatoCMS, but it would be nice to show them inside the DatoCMS interface.
Since the buildItemPresentationInfo
hook can be an async function, we can easily make a fetch
call to the Shopify Storefront API and use this information:
import { connect , Item , OnBootCtx } from "datocms-plugin-sdk" ;
type ProductRecord = Item & {
attributes : {
shopify_product_handle : string ;
}
}
function isProductRecord ( item : Item , ctx : OnBootCtx ) : item is ProductRecord {
return ctx . itemTypes [ item . relationships . item_type . data . id ] ? . attributes . api_key === 'product' ;
}
connect ( {
async buildItemPresentationInfo ( item : Item , ctx : OnBootCtx ) {
if ( ! isProductRecord ( item , ctx ) ) {
return undefined ;
}
const { title , imageUrl , availableForSale } = await fetchShopifyProduct (
item . attributes . shopify_product_handle ,
ctx . plugin ,
) ;
return {
title : ` ${ title } ( ${ availableForSale ? '🛍️' : '🚫' } ) ` ,
imageUrl ,
}
} ,
} ) ;
To perform the actual API call to Shopify, we need an API token and the Shopify store domain. Both can be specified by the final user by adding some settings to the plugin .
The final fetchShopifyProduct
function:
import { Plugin } from "datocms-plugin-sdk" ;
type PluginParameters = {
shopifyDomain : string ;
shopifyAccessToken : string ;
}
async function fetchShopifyProduct ( handle : string , plugin : Plugin ) {
const parameters = plugin . attributes . parameters as PluginParameters ;
const res = await fetch (
` https:// ${ parameters . shopifyDomain } .myshopify.com/api/graphql ` ,
{
method : 'POST' ,
headers : {
'Content-Type' : 'application/json' ,
'X-Shopify-Storefront-Access-Token' : ` ${ parameters . shopifyAccessToken } ` ,
} ,
body : JSON . stringify ( {
query : ` query getProduct($handle: String!) {
product: productByHandle(handle: $handle) {
title
availableForSale
images(first: 1) {
edges {
node {
src: transformedSrc(crop: CENTER, maxWidth: 200, maxHeight: 200)
}
}
}
}
} ` ,
variables : { handle } ,
} ) ,
} ,
) ;
const body = await res . json ( ) ;
return {
title : body . data . product . title ,
availableForSale : body . data . product . availableForSale ,
imageUrl : body . data . product . images . edges [ 0 ] . node . src ,
} ;
}
Function Reference buildItemPresentationInfo()
Use this function to customize the presentation of a record in records
collections and "Single link" or "Multiple links" field.
Properties available in context The following information and methods are available:
ctx.account The account that is the project owner.
ctx.currentRole The role for the current DatoCMS user.
ctx.currentUser The current DatoCMS user. It can either be the owner or one of the
collaborators (regular or SSO).
ctx.currentUserAccessToken The access token to perform API calls on behalf of the current user. Only
available if currentUserAccessToken additional permission is granted.
ctx.environment The ID of the current environment.
ctx.fields All the fields currently loaded for the current DatoCMS project, indexed by
ID. It will always contain the current model fields and all the fields of
the blocks it might contain via Modular Content/Structured Text fields. If
some fields you need are not present, use the loadItemTypeFields function
to load them.
ctx.fieldsets All the fieldsets currently loaded for the current DatoCMS project, indexed
by ID. It will always contain the current model fields and all the fields
of the blocks it might contain via Modular Content/Structured Text fields.
If some fields you need are not present, use the loadItemTypeFieldsets
function to load them.
ctx.itemTypes All the models of the current DatoCMS project, indexed by ID.
ctx.owner The account that is the project owner.
ctx.plugin The current plugin.
ctx.site The current DatoCMS project.
ctx.ssoUsers All the SSO users currently loaded for the current DatoCMS project, indexed
by ID. It will always contain the current user. If some users you need are
not present, use the loadSsoUsers function to load them.
ctx.theme An object containing the theme colors for the current DatoCMS project.
ctx.ui UI preferences of the current user (right now, only the preferred locale is
available).
ctx.users All the regular users currently loaded for the current DatoCMS project,
indexed by ID. It will always contain the current user. If some users you
need are not present, use the loadUsers function to load them.
Methods available in context The following information and methods are available:
ctx.alert() Triggers an "error" toast displaying the selected message.
ctx.createNewItem() Opens a dialog for creating a new record. It returns a promise resolved
with the newly created record or null if the user closes the dialog
without creating anything.
ctx.customToast() Triggers a custom toast displaying the selected message (and optionally a
CTA).
ctx.editItem() Opens a dialog for editing an existing record. It returns a promise
resolved with the edited record, or null if the user closes the dialog
without persisting any change.
ctx.editUpload() Opens a dialog for editing a Media Area asset. It returns a promise
resolved with:
The updated asset, if the user persists some changes to the asset itself
null, if the user closes the dialog without persisting any change
An asset structure with an additional deleted property set to true, if
the user deletes the asset.
ctx.editUploadMetadata() Opens a dialog for editing a "single asset" field structure. It returns a
promise resolved with the updated structure, or null if the user closes
the dialog without persisting any change.
ctx.loadFieldsUsingPlugin() Loads all the fields in the project that are currently using the plugin for
one of its manual field extensions.
ctx.loadItemTypeFields() Loads all the fields for a specific model (or block). Fields will be
returned and will also be available in the the fields property.
ctx.loadItemTypeFieldsets() Loads all the fieldsets for a specific model (or block). Fieldsets will be
returned and will also be available in the the fieldsets property.
ctx.loadSsoUsers() Loads all SSO users. Users will be returned and will also be available in
the the ssoUsers property.
ctx.loadUsers() Loads all regular users. Users will be returned and will also be available
in the the users property.
ctx.navigateTo() Moves the user to another URL internal to the backend.
ctx.notice() Triggers a "success" toast displaying the selected message.
ctx.openConfirm() Opens a UI-consistent confirmation dialog. Returns a promise resolved with
the value of the choice made by the user.
ctx.openModal() Opens a custom modal. Returns a promise resolved with what the modal itself
returns calling the resolve() function.
ctx.selectItem() Opens a dialog for selecting one (or multiple) record(s) from a list of
existing records of type itemTypeId. It returns a promise resolved with
the selected record(s), or null if the user closes the dialog without
choosing any record.
ctx.selectUpload() Opens a dialog for selecting one (or multiple) existing asset(s). It
returns a promise resolved with the selected asset(s), or null if the
user closes the dialog without selecting any upload.
ctx.updateFieldAppearance() Performs changes in the appearance of a field. You can install/remove a
manual field extension, or tweak their parameters. If multiple changes are
passed, they will be applied sequencially.
Always check ctx.currentRole.meta.finalpermissions.canedit_schema
before calling this, as the user might not have the permission to perform
the operation.
ctx.updatePluginParameters() Updates the plugin parameters.
Always check ctx.currentRole.meta.finalpermissions.canedit_schema
before calling this, as the user might not have the permission to perform
the operation.