Can you programmatically create blocks in plugins?

I was trying to create a plugin that would add template buttons, and clicking one would add a bunch of blocks to a modular content field. However, I’m not sure if this is possible.

I don’t want to create and save them, I just want to populate a modular block field with some empty blocks of a given type.

I tried using the buildModularBlock function per this example. But that example is for API calls.

When I try and use it in a plugin, I keep getting buildModularBlock is not a function.

Is this possible?

Here are the relevant lines of code (I removed unrelated lines):

const { buildModularBlock } = require('datocms-client');

window.DatoCmsPlugin.init((plugin) => {
  // ...
  // setup code
  // ...
  button.addEventListener('click', () => {
    const block = buildModularBlock({ itemType: 'text' });
    plugin.setFieldValue(modularContentFieldApiKey, [block])
1 Like

Hello @dewyze

You can do this, but you will have to do it through the CMA, you can’t do it directly through the plugin.
That is, you will have to prompt the user for their API token, create a client from the API token, and then, create the modular block like in the record like you would in the CMA.


I know this process is a bit long, and can be cumbersome both for the developer and the user of the plugin, and we are planing on addressing this and much more in the next plugin SDK update.

Okay, that will be helpful.

What I’m really trying to do is create Templates for modular content fields. Or even a default value would be nice.

For example, for a Page model that has a content modular field it would be nice if for most people who use it, it comes just prepopulated with a structured text field and that will be enough for most.

Is there anything like default values for modular fields, or templates available? Or is the best option waiting for the plugin SDK update?

1 Like

You can do it by attaching the plugin to another non modular field and from there prompt for the API tokens to do the other interactions through the CMA.
It is possible but i would wait for the SDK update, as it will streamline much of this process, making it much easier both for you, and for the users of your plugin