This blog post explains how you can add a custom field to the Contentstack SaaS headless content management system, in this case to render a message set by code to the CMS user as a read-only HTML element while editing the entry that contains that value. You can use this technique to provide guidance to the user, such as to apply custom validation or provide writing and other suggestions. You can build more complex custom field types that store values to the entry edited by the CMS user.
The Contentstack UI supports three kinds of extensions:
- Dashboard widgets, which appear in the stack dashboard
- Custom widgets, which appear in a separate windowpane while editing entries
- Custom field types, which appear as fields while editing entries.
To display read-only content to the CMS user, you could use a custom widget or a custom field type. I found that for both, the implementations for showing a read-only field were basically the same.
Custom field types are simple to understand, implement, and configure. You can add custom field types based on the default field types and some custom field types that are disabled by default. You can host custom the user interface for custom fields in Contentstack solution or at a separate URL that you manage. You can enable custom field types provided by Contentstack, such as for a color picker, and review their source code.
To implement a custom field type, write HTML for a web page that:
- Loads the https://www.contentstack.com/sdks/contentstack-ui-extensions/dist/latest/ui-extension-sdk.css stylesheet
- Loads the https://www.contentstack.com/sdks/contentstack-ui-extensions/dist/latest/ui-extension-sdk.js script
Beyond the read-only custom field type described in this blog post, the color picker from Contentstack may provide the simplest example.
Because the custom field runs as its own page, we do not need to generate unique DOM element IDs even if the content type uses the custom field type more than once.
To use this solution:
- In the Contentstack UI, click the gear icon, and then click Extensions.
- Click Add Extension, and then click Create new.
- Click Custom Field.
- Enter field properties including a title and then click Save.
- In a content type, create a field of type Custom.
- In field properties, set Select Extension to the title of the custom field type that you created.
Here is the code, which simply retrieves the field value into an HTML <div> element and suggests a height for the field to display in the Contentstack user interface.
To use the same code as a widget, comment the two lines about sizing and change the line that retrieves the value to specify the name of the field in the entry.
I believe that field types are best for controlling field values; widgets are more appropriate for for evaluating field values.