Sorry, no results found for "".

Plugin SDK > Config screen

Config screen

Quite often, a plugin needs to offer a set of configuration options to the user who installs it.

DatoCMS offers every plugin a configuration screen and a read-write object that can be used to store such settings. It is a free-form object, with no restrictions in the format. Plugins can store what they want in it, and retrieve its value anytime they need in any hook.

As the configuration parameters are completely arbitrary, it is up to the plugin itself to show the user a form through which they can be changed.

The hook provided for this purpose is called renderConfigScreen, and it will be called by DatoCMS when the user visits the details page of the installed plugin:

Implementing a simple configuration form

To give a very simple example, let's say our plugin wants to provide the end user with a simple boolean flag called debugMode. If this flag is enabled, then the plugin will display a series of debug messages in the console as it works.

The first step is to implement the renderConfigScreen hook, which will simply initialize React by rendering a custom component called ConfigScreen:

1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import { connect, RenderConfigScreenCtx } from 'datocms-plugin-sdk';
4
5
connect({
6
renderConfigScreen(ctx: RenderConfigScreenCtx) {
7
ReactDOM.render(
8
<React.StrictMode>
9
<ConfigScreen ctx={ctx} />
10
</React.StrictMode>,
11
document.getElementById('root'),
12
);
13
},
14
});

The hook, in its ctx argument, provides a series of information and methods for interacting with the main application, and for now we'll just pass the whole object to the component, in the form of a React prop:

1
import { Canvas } from 'datocms-react-ui';
2
3
type PropTypes = {
4
ctx: RenderConfigScreenCtx;
5
};
6
7
function ConfigScreen({ ctx }: PropTypes) {
8
return (
9
<Canvas ctx={ctx}>
10
Hello from the config screen!
11
</Canvas>
12
);
13
}
Always use the canvas!

It is important to wrap the content inside the Canvas component, so that the iframe will continuously auto-adjust its size based on the content we're rendering, and to give our app the look and feel of the DatoCMS web app.

It is now time to setup our form:

1
import { Canvas, SwitchField } from 'datocms-react-ui';
2
3
// configuration object starts as an empty object
4
type FreshInstallationParameters = {};
5
6
// this is how we want to save our settings
7
type ValidParameters = { devMode: boolean };
8
9
// parameters can be either empty or filled in
10
type Parameters = FreshInstallationParameters | ValidParameters;
11
12
export default function ConfigScreen({ ctx }: PropTypes) {
13
const parameters = ctx.plugin.attributes.parameters as Parameters;
14
15
return (
16
<Canvas ctx={ctx}>
17
<SwitchField
18
id="01"
19
name="development"
20
label="Enable development mode?"
21
hint="Log debug information in console"
22
value={parameters.devMode}
23
onChange={(newValue) => {
24
ctx.updatePluginParameters({ devMode: newValue });
25
ctx.notice('Settings updated successfully!');
26
}}
27
/>
28
</Canvas>
29
);
30
}

The important things to notice are that:

  • we can access the currently saved configuration object through ctx.plugin.attributes.parameters

  • we can call ctx.updatePluginParameters() to save a new configuration object.

Once saved, settings are always available as ctx.plugin.attributes.parameters in any of the other hooks, so that your plugin can have different behaviours based on them.

Using a form management library

If you have more complex settings, feel free to use one of the many form management libraries available for React to avoid code repetition.

We recommend react-final-form, as it works well and is quite lightweight (~8kb). Here's a more complete example using it:

1
import { RenderConfigScreenCtx } from 'datocms-plugin-sdk';
2
import {
3
Button,
4
Canvas,
5
SwitchField,
6
TextField,
7
Form,
8
FieldGroup,
9
} from 'datocms-react-ui';
10
import { Form as FormHandler, Field } from 'react-final-form';
11
12
type PropTypes = {
13
ctx: RenderConfigScreenCtx;
14
};
15
16
type FirstInstallationParameters = {};
17
type ValidParameters = { devMode: boolean; title: string };
18
type Parameters = FirstInstallationParameters | ValidParameters;
19
20
export default function ConfigScreen({ ctx }: PropTypes) {
21
return (
22
<Canvas ctx={ctx}>
23
<FormHandler<Parameters>
24
initialValues={ctx.plugin.attributes.parameters}
25
validate={(values) => {
26
const errors: Record<string, string> = {};
27
28
if (!values.title) {
29
errors.title = 'This field is required!';
30
}
31
return errors;
32
}}
33
onSubmit={async (values) => {
34
await ctx.updatePluginParameters(values);
35
ctx.notice('Settings updated successfully!');
36
}}
37
>
38
{({ handleSubmit, submitting, dirty }) => (
39
<Form onSubmit={handleSubmit}>
40
<FieldGroup>
41
<Field name="title">
42
{({ input, meta: { error } }) => (
43
<TextField
44
id="title"
45
label="Title"
46
hint="Title to show"
47
placeholder="Your title"
48
required
49
error={error}
50
{...input}
51
/>
52
)}
53
</Field>
54
<Field name="devMode">
55
{({ input, meta: { error } }) => (
56
<SwitchField
57
id="devMode"
58
label="Enable development mode?"
59
hint="Log debug information in console"
60
error={error}
61
{...input}
62
/>
63
)}
64
</Field>
65
</FieldGroup>
66
<Button
67
type="submit"
68
fullWidth
69
buttonSize="l"
70
buttonType="primary"
71
disabled={submitting || !dirty}
72
>
73
Save settings
74
</Button>
75
</Form>
76
)}
77
</FormHandler>
78
</Canvas>
79
);
80
}

This will be the final result:

renderConfigScreen(ctx)

This function will be called when the plugin needs to render the plugin's configuration form.

Context object

The following properties and methods are available in the ctx argument:

Every hook available in the Plugin SDK shares the same minumum set of properties and methods.

Information about the current user using the CMS.

The current DatoCMS user. It can either be the owner or one of the collaborators (regular or SSO).

View on Github

The role for the current DatoCMS user.

View on Github

The access token to perform API calls on behalf of the current user. Only available if currentUserAccessToken additional permission is granted.

View on Github
These methods can be used to open custom dialogs/confirmation panels.

Opens a custom modal. Returns a promise resolved with what the modal itself returns calling the resolve() function.

View on Github
1
const result = await ctx.openModal({
2
id: 'regular',
3
title: 'Custom title!',
4
width: 'l',
5
parameters: { foo: 'bar' },
6
});
7
8
if (result) {
9
ctx.notice(`Success! ${JSON.stringify(result)}`);
10
} else {
11
ctx.alert('Closed!');
12
}

Opens a UI-consistent confirmation dialog. Returns a promise resolved with the value of the choice made by the user.

View on Github
1
const result = await ctx.openConfirm({
2
title: 'Custom title',
3
content:
4
'Lorem Ipsum is simply dummy text of the printing and typesetting industry',
5
choices: [
6
{
7
label: 'Positive',
8
value: 'positive',
9
intent: 'positive',
10
},
11
{
12
label: 'Negative',
13
value: 'negative',
14
intent: 'negative',
15
},
16
],
17
cancel: {
18
label: 'Cancel',
19
value: false,
20
},
21
});
22
23
if (result) {
24
ctx.notice(`Success! ${result}`);
25
} else {
26
ctx.alert('Cancelled!');
27
}
These properties provide access to "entity repos", that is, the collection of resources of a particular type that have been loaded by the CMS up to this moment. The entity repos are objects, indexed by the ID of the entity itself.

All the models of the current DatoCMS project, indexed by ID.

View on Github

All the fields currently loaded for the current DatoCMS project, indexed by ID. If some fields you need are not present, use the loadItemTypeFields function to load them.

View on Github

All the fieldsets currently loaded for the current DatoCMS project, indexed by ID. If some fields you need are not present, use the loadItemTypeFieldsets function to load them.

View on Github

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.

View on Github

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.

View on Github
These methods let you open the standard DatoCMS dialogs needed to interact with records.

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.

View on Github
1
const itemTypeId = prompt('Please insert a model ID:');
2
3
const item = await ctx.createNewItem(itemTypeId);
4
5
if (item) {
6
ctx.notice(`Success! ${item.id}`);
7
} else {
8
ctx.alert('Closed!');
9
}

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.

View on Github
1
const itemTypeId = prompt('Please insert a model ID:');
2
3
const items = await ctx.selectItem(itemTypeId, { multiple: true });
4
5
if (items) {
6
ctx.notice(`Success! ${items.map((i) => i.id).join(', ')}`);
7
} else {
8
ctx.alert('Closed!');
9
}

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.

View on Github
1
const itemId = prompt('Please insert a record ID:');
2
3
const item = await ctx.editItem(itemId);
4
5
if (item) {
6
ctx.notice(`Success! ${item.id}`);
7
} else {
8
ctx.alert('Closed!');
9
}
These methods can be used to asyncronously load additional information your plugin needs to work.

Loads all the fields for a specific model (or block). Fields will be returned and will also be available in the the fields property.

View on Github
1
const itemTypeId = prompt('Please insert a model ID:');
2
3
const fields = await ctx.loadItemTypeFields(itemTypeId);
4
5
ctx.notice(
6
`Success! ${fields
7
.map((field) => field.attributes.api_key)
8
.join(', ')}`,
9
);

Loads all the fieldsets for a specific model (or block). Fieldsets will be returned and will also be available in the the fieldsets property.

View on Github
1
const itemTypeId = prompt('Please insert a model ID:');
2
3
const fieldsets = await ctx.loadItemTypeFieldsets(itemTypeId);
4
5
ctx.notice(
6
`Success! ${fieldsets
7
.map((fieldset) => fieldset.attributes.title)
8
.join(', ')}`,
9
);

Loads all the fields in the project that are currently using the plugin for one of its manual field extensions.

View on Github
1
const fields = await ctx.loadFieldsUsingPlugin();
2
3
ctx.notice(
4
`Success! ${fields
5
.map((field) => field.attributes.api_key)
6
.join(', ')}`,
7
);

Loads all regular users. Users will be returned and will also be available in the the users property.

View on Github
1
const users = await ctx.loadUsers();
2
3
ctx.notice(`Success! ${users.map((user) => user.id).join(', ')}`);

Loads all SSO users. Users will be returned and will also be available in the the ssoUsers property.

View on Github
1
const users = await ctx.loadSsoUsers();
2
3
ctx.notice(`Success! ${users.map((user) => user.id).join(', ')}`);
These methods can be used to take the user to different pages.

Moves the user to another URL internal to the backend.

View on Github
1
await ctx.navigateTo('/');
Information about the current plugin. Useful to access the plugin's global configuration object.

The current plugin.

View on Github

The current DatoCMS project.

View on Github

The ID of the current environment.

View on Github

The account/organization that is the project owner.

View on Github

UI preferences of the current user (right now, only the preferred locale is available).

View on Github

An object containing the theme colors for the current DatoCMS project.

View on Github
A number of methods that you can use to control the size of the plugin frame.

Listens for DOM changes and automatically calls setHeight when it detects a change. If you're using datocms-react-ui package, the <Canvas /> component already takes care of calling this method for you.

View on Github

Stops resizing the iframe automatically.

View on Github

Triggers a change in the size of the iframe. If you don't explicitely pass a newHeight it will be automatically calculated using the iframe content at the moment.

View on Github
These methods can be used to show UI-consistent toast notifications to the end-user.

Triggers an "error" toast displaying the selected message.

View on Github
1
const message = prompt(
2
'Please insert a message:',
3
'This is an alert message!',
4
);
5
6
await ctx.alert(message);

Triggers a "success" toast displaying the selected message.

View on Github
1
const message = prompt(
2
'Please insert a message:',
3
'This is a notice message!',
4
);
5
6
await ctx.notice(message);

Triggers a custom toast displaying the selected message (and optionally a CTA).

View on Github
1
const result = await ctx.customToast({
2
type: 'warning',
3
message: 'Just a sample warning notification!',
4
dismissOnPageChange: true,
5
dismissAfterTimeout: 5000,
6
cta: {
7
label: 'Execute call-to-action',
8
value: 'cta',
9
},
10
});
11
12
if (result === 'cta') {
13
ctx.notice(`Clicked CTA!`);
14
}
These methods can be used to update both plugin parameters and manual field extensions configuration.

Updates the plugin parameters.

Always check ctx.currentRole.meta.final_permissions.can_edit_schema before calling this, as the user might not have the permission to perform the operation.

View on Github
1
await ctx.updatePluginParameters({ debugMode: true });
2
await ctx.notice('Plugin parameters successfully updated!');

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.final_permissions.can_edit_schema before calling this, as the user might not have the permission to perform the operation.

View on Github
1
const fields = await ctx.loadFieldsUsingPlugin();
2
3
if (fields.length === 0) {
4
ctx.alert('No field is using this plugin as a manual extension!');
5
return;
6
}
7
8
for (const field of fields) {
9
const { appearance } = field.attributes;
10
const operations = [];
11
12
if (appearance.editor === ctx.plugin.id) {
13
operations.push({
14
operation: 'updateEditor',
15
newParameters: {
16
...appearance.parameters,
17
foo: 'bar',
18
},
19
});
20
}
21
22
appearance.addons.forEach((addon, i) => {
23
if (addon.id !== ctx.plugin.id) {
24
return;
25
}
26
27
operations.push({
28
operation: 'updateAddon',
29
index: i,
30
newParameters: { ...addon.parameters, foo: 'bar' },
31
});
32
});
33
34
await ctx.updateFieldAppearance(field.id, operations);
35
ctx.notice(`Successfully edited field ${field.attributes.api_key}`);
36
}
These methods let you open the standard DatoCMS dialogs needed to interact with Media Area assets.

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.

View on Github
1
const item = await ctx.selectUpload({ multiple: false });
2
3
if (item) {
4
ctx.notice(`Success! ${item.id}`);
5
} else {
6
ctx.alert('Closed!');
7
}

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.
View on Github
1
const uploadId = prompt('Please insert an asset ID:');
2
3
const item = await ctx.editUpload(uploadId);
4
5
if (item) {
6
ctx.notice(`Success! ${item.id}`);
7
} else {
8
ctx.alert('Closed!');
9
}

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.

View on Github
1
const uploadId = prompt('Please insert an asset ID:');
2
3
const result = await ctx.editUploadMetadata({
4
upload_id: uploadId,
5
alt: null,
6
title: null,
7
custom_data: {},
8
focal_point: null,
9
});
10
11
if (result) {
12
ctx.notice(`Success! ${JSON.stringify(result)}`);
13
} else {
14
ctx.alert('Closed!');
15
}