This section is for legacy plugins, which have been deprecated. For the current version of the Plugin SDK, please visit the Plugin SDK documentation.
If you require the script from the web without any module system you can include the SDK like this:
<html lang="en"><head><meta charset="UTF-8" /><script src="https://unpkg.com/datocms-plugins-sdk"></script></head><body><input type="text" /><script type="text/javascript">DatoCmsPlugin.init(function(plugin) {/* ... */});</script></body></html>
If you use Webpack or Browserify, you'll need to require the datocms-plugins-sdk
npm package:
const DatoCmsPlugin = require('datocms-plugins-sdk');DatoCmsPlugin.init(function(plugin) {/* ... */});
The SDK exposes the DatoCmsPlugin.init()
method, which is the main entry point for all plugin related code. The .init
method also returns a Promise, so the following code is equivalent:
DatoCmsPlugin.init().then(function(plugin) {/* ... */});
If you have doubts regarding how to structure the logic of your plugin, please take a look at some examples we already made available in our Github repository.
plugin.site
Returns information about the current DatoCMS project. The object takes the same format as the CMA Site object.
// returns the name of the current siteconsole.log(plugin.site.attributes.name);
plugin.environment
Returns the ID of the current environment
.
// returns the name of the current environment (ie. "main")console.log(plugin.environment);
plugin.itemType
Returns information about of the current DatoCMS model. The object takes the same format as the CMA Model object.
// returns the API identifier of the current modelconsole.log(plugin.itemType.attributes.api_key);
plugin.itemTypes
Returns all the models of the current DatoCMS project, indexed by ID. The objects take the same format as the CMA Model object.
// returns info about all the models of the current DatoCMS projectplugin.site.relationships.item_types.data.forEach(function(link) {console.log(plugin.itemTypes[link.id].attributes.api_key);});
plugin.fields
Returns the subset of fields that are already loaded, indexed by ID. The objects take the same format as the CMA Field object. 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 you need fields coming from other models/blocks than the current one, use the plugin.loadItemTypeFields()
method to load them.
// returns info about all the fields of the current modelplugin.itemType.relationships.fields.data.forEach(function(link) {console.log(plugin.fields[link.id].attributes.api_key);});
plugin.item
Returns the full record entity (only if the plugin is attached to an already existing record).
// returns the last updated timeconsole.log(plugin.item.meta.updated_at);
plugin.itemId
Returns the ID of the record the plugin is attached to (only if the plugin is attached to an already existing record).
// returns the ID of the recordconsole.log(plugin.itemId);
plugin.itemStatus
Returns the publishing status of the record the plugin is attached to.
console.log(plugin.itemStatus);// => "published"
plugin.isSubmitting
Returns true or false depending on the current form submission status.
plugin.field
Returns the fields the plugin is attached to. The object takes the same format as the CMA Field object.
// returns info about the fieldconsole.log(plugin.field.attributes.api_key);
plugin.currentUser
Returns information about of the current DatoCMS user. It can either be the owner or one of the collaborators.
// returns the email of the current userconsole.log(plugin.currentUser.attributes.email);
plugin.disabled
Returns whether the field must be disabled or not.
const input = document.querySelector("input");input.disabled = plugin.disabled;
plugin.parameters
Returns the configuration parameters values for the plugin.
console.log(plugin.parameters);// returns parameters in the following shape:// {// global: {// developmentMode: true// },// instance: {// sentences: 2// }// }
plugin.locale
The current locale of a field the plugin is attached to.
// returns ie. "en_US"console.log(plugin.locale);
plugin.fieldPath
Returns the path of the field the plugin is attached to. Useful to set or get the value of the field itself:
// get field's current valueconsole.log(plugin.getFieldValue(plugin.fieldPath));// change field's current valueplugin.setFieldValue(plugin.fieldPath, 'New value!');
plugin.placeholder
Returns the default placeholder for the field the plugin is attached to.
const input = document.querySelector("input");input.placeholder = plugin.placeholder;
plugin.theme
Returns the site current color scheme.
console.log(plugin.theme);// returns the color scheme in the following form:// {// accentColor: 'rgb(20, 179, 204)',// darkColor: 'rgb(47, 59, 59)',// lightColor: 'rgb(227, 249, 252)',// primaryColor: 'rgb(20, 152, 172)',// semiTransparentAccentColor: 'rgb(20, 179, 204, 0.1)',// }
plugin.getFieldValue(...pathChunks)
Returns the value of a specific field. To get the value of the current field the plugin is attached to, use the plugin.fieldPath
option.
// get the value of the 'title' fieldconsole.log(plugin.getFieldValue('title'));// if the field is multi-language, both of these methods are fine:console.log(plugin.getFieldValue('title.en'));console.log(plugin.getFieldValue('title', 'en'));// get field's current valueconsole.log(plugin.getFieldValue(plugin.fieldPath));
plugin.setFieldValue(...pathChunks, newValue)
Sets the value of a specific field.
The type of the value must match the expected field type. For example, if the plugin is attached to a "single-line string" field you must pass a string.
The method returns a Promise that resolves once the change has been acknowledged by the DatoCMS webapp.
You can get the path of the field the plugin is attached to using the method plugin.fieldPath
.
// set the value of the 'title' fieldplugin.setFieldValue('title', 'New title!');// if the field is multi-language, both of these methods are fine:plugin.setFieldValue('title.en', 'New title!');plugin.setFieldValue('title', 'en', 'New title!');// set field's current valueplugin.setFieldValue(plugin.fieldPath, 'New title!');// if multi-language, and you need to set the value of the field in a different locale (ie. `it`):const alternativeLanguageFieldPath = plugin.fieldPath.replace(new RegExp(`\.${plugin.locale}$`), `.it`);plugin.setFieldValue(alternativeLanguageFieldPath, 'New title!');
plugin.addFieldChangeListener(...pathChunks, callbackFn)
Calls the callbackFn
every time the value of the field specified is changed by an external event (e.g. when multiple editors are working on the same entry) or when setFieldValue()
is called.
The method returns a function you can call to stop listening to changes.
You can get the path of the field the plugin is attached to using the method plugin.fieldPath
.
const input = document.querySelector("input");const unsubscribe = plugin.addFieldChangeListener(plugin.fieldPath, (newValue) => {input.value = newValue;});// stop being notifiedunsubscribe();
plugin.addChangeListener(...pathChunks, callbackFn)
Calls the callbackFn
every time one of the plugin options is changed by an external event. The method returns a function you can call to stop listening to changes.
const input = document.querySelector("input");const unsubscribe = plugin.addFieldChangeListener('disabled', (newValue) => {input.disabled = newValue;});// stop being notifiedunsubscribe();
plugin.toggleField(...pathChunks, visible)
Hides/shows a specific field. The method returns a Promise that resolves once the change has been acknowledged by the DatoCMS webapp.
You can get the path of the field the plugin is attached to using the method plugin.fieldPath
.
// hide the title fieldplugin.toggleField('title', false);// show the title fieldplugin.toggleField('title', true);// if the field is multi-language, both of these methods are fine:plugin.toggleField('title.en', true);plugin.toggleField('title', 'en', true);
plugin.disableField(...pathChunks, disable)
Disables/enables a specific field. The method returns a Promise that resolves once the change has been acknowledged by the DatoCMS webapp.
You can get the path of the field the plugin is attached to using the method plugin.fieldPath
.
// disable the title fieldplugin.disableField('title', true);// re-enable the title fieldplugin.disableField('title', false);// if the field is multi-language, both of these methods are fine:plugin.disableField('title.en', true);plugin.disableField('title', 'en', true);
plugin.scrollToField(...pathChunks)
Smoothly navigates to a specific field. If the field is localized it will switch language tab and then navigate to the chosen field.
You can get all field paths and data using the method plugin.fields
and all current model's field IDs using plugin.itemType.relationships.fields.data
//scroll to title fieldplugin.scrollToField('title');// if the field is multi-language, both of these methods are fine:plugin.scrollToField('title.en');plugin.scrollToField('title', 'en');
plugin.startAutoResizer()
Listens for DOM changes and calls updateHeight()
when the size changes.
plugin.stopAutoResizer()
Stops resizing the iframe automatically.
plugin.updateHeight()
Calculates the body's scrollHeight
and sets the containers height to this value.
plugin.updateHeight(height)
Sets the iframe height to the given value in pixels. height
must be an integer.
plugin.createNewItem(itemTypeId)
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.
// open modal to create a new record of model with ID=999plugin.createNewItem(999).then(function(item) {if (item) {console.log('Item created: ', item);} else {console.log('Model closed!');}});
plugin.selectItem(itemTypeId, { multiple })
Opens a dialog for selecting one or multiple records from a list of existing records of type itemTypeId
. multiple
is a boolean and it is false
by default. It returns a promise resolved with the selected record, an array of selected records or null
if the user closes the dialog without persisting any change.
🔍 Available since datocms-plugins-sdk
v0.1.0
// open modal to select a record with itemTypeId #4941// For example in the case of a single link, itemTypeId is// plugin.field.attributes.validators.item_item_type.item_types[0]plugin.selectItem(4941).then(function(item) {if (item) {console.log('Item selected: ', item);} else {console.log('Modal closed!');}});// open modal to select records with itemTypeId #4941// For example in the case of a multiple links, itemTypeId is// plugin.field.attributes.validators.items_item_type.item_types[0]plugin.selectItem(4941, { multiple: true }).then(function(items) {if (items) {console.log('Items selected: ', items);} else {console.log('Modal closed!');}});
plugin.editItem(itemId)
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.
// open modal to edit record #4941plugin.editItem(4941).then(function(item) {if (item) {console.log('Item edited: ', item);} else {console.log('Model closed!');}});
plugin.saveCurrentItem()
Triggers a submit form for current record. It returns a promise that will be rejected if form is invalid.
plugin.saveCurrentItem().then(() => console.log('Record saved!')).catch(() => console.log('Could not save this record'));
plugin.selectUpload({ multiple })
Opens a dialog for selecting one or multiple existing uploads. multiple
is a boolean and it is false
by default. It returns a promise resolved with the selected upload, an array of selected uploads or null
if the user closes the dialog without selecting any upload.
🔍 Available since datocms-plugins-sdk
v0.1.0
// open modal to select an uploadplugin.selectUpload().then(function(upload) {if (upload) {console.log('Upload selected: ', upload);} else {console.log('Modal closed!');}});// open modal to select multiple uploadsplugin.selectUpload({ multiple: true }).then(function(uploads) {if (uploads) {console.log('Uploads selected: ', uploads);} else {console.log('Modal closed!');}});
plugin.editUpload(uploadId)
Opens a dialog for editing a upload
(image). It returns a promise resolved with the updated upload information or null
if the user closes the dialog without persisting any change.
When the user deletes the upload the returned promise resolves with an upload object with a deleted
property set to true
.
🔍 Available since datocms-plugins-sdk
v0.1.0
plugin.editUpload(plugin.getFieldValue(plugin.fieldPath).upload_id).then(function(upload) {if (upload) {if (upload.upload_id === null) {console.log("Upload deleted")} else {console.log("Updated upload: ", upload);}} else {console.log("Modal closed!");}});
plugin.editUploadMetadata(uploadMetadata)
Opens a dialog for editing the upload metadata that are associated to an upload (image). It returns a promise resolved with the updated upload metadata or null
if the user closes the dialog without persisting any change.
🔍 Available since datocms-plugins-sdk
v0.1.0
plugin.editUploadMetadata({upload_id: '345',alt: 'Alt',title: 'Title',custom_data: {},focal_point: null,}).then(function(metadata) {if (metadata) {console.log("Updated upload metadata: ", metadata);} else {console.log("Modal closed!");}});
plugin.loadItemTypeFields(itemTypeId)
Loads all the fields for a specific model (or block) . To be used if plugin.fields
does not already has them cached.
plugin.notice(message)
Triggers a UI consistent notification popup displaying the selected message and returns a promise.
plugin.alert(message)
Triggers a UI consistent alert popup displaying the selected message and returns a promise.