We do have some parallel blocks, which basically has a parent-child relationship, would like to convert to nested block. I like to do this programmatically as there are a lot. Can we just get the blocks, and create nested blocks with those block id? or just nested modular blocks? Couldn’t see the API here: Update a record - Record - Content Management API
1 Like
Hello @rislam
I’ve made a sample script on how to turn a given 2 sibling blocks relation in a model, into a parent/child block relation on all records from said model, it may need some adjustments for your use case, but the general idea is this one:
const { SiteClient, buildModularBlock } = require("datocms-client");
const client = new SiteClient("YOUR_DATO_FULL_ACCESS_TOKEN");
const getAllRecordsFromModel = async (modelApiKey) => {
const records = await client.items.all({
filter: {
type: modelApiKey, //the name of the model you want to make that change
},
});
return records;
};
const updateRecord = async (recordId, block1Id, block2Id) => {
//updates a single record with the 2 sibling blocks
client.items.update(recordId, {
block1field: [
buildModularBlock({
//the now parent block
itemType: block1Id,
block1title: "block1 title test", //the other fields of the now parent block
block2: [
buildModularBlock({
//the now child block
itemType: block2Id,
block2title: "block2 title test", //all fields of the now child block, here you may also get the old values from the sibling block if you want
}),
],
}),
],
});
};
const updateAllRecordsFromAModel = async (
modelApiKey,
childBlockFieldId,
block1Id,
block2Id
) => {
//updates all records from te model
for (record of await getAllRecordsFromModel(modelApiKey)) {
await updateRecord(record.id, block1Id, block2Id);
}
await client.field.destroy(modelApiKey + "::" + childBlockFieldId); //removes the sibling block field, as it is now a child block
};
//now the function call itself
updateAllRecordsFromAModel(
"MODEL_API_KEY",
"CHILD_BLOCK_FIELD_ID",
"BLOCK_1_ID",
"BLOCK_2_ID"
);
1 Like
So buildModularBlock
inside buildModularBlock
works. Thank you very much mate, appreciate it very much.
2 Likes