
Deleting records in Knack can be a fragile process. If you delete a parent record, any child records connected to that may become orphaned and you can lose visibility or see missing data within your live app. On the other hand, if you want to safely delete all your child records before deleting the parent record, you would need to manually delete each record one at a time.
This solution is great for use cases where you want to delete a parent record (e.g. Project) and all its related child records (e.g. Tasks, Notes) with the click of a button.
Here is what the deleteParentAndChildRecords function looks like
// Purpose: Delete a parent record and its connected child records
async function deleteParentAndChildRecords({ parentId, parentSceneKey, parentViewKey, childSceneKey, childViewKeys = [] }) {
if (!parentId || !parentSceneKey || !parentViewKey || !childSceneKey) throw new Error('deleteParentAndChildRecords: missing required parameter(s)');
for (viewKey of childViewKeys) { // For each child view key...
const childRecords = await KnackAPI.makeRequest('getMany', { scene: childSceneKey, view: viewKey, sceneRecordId: parentId }); // Get child records
const recordsToDelete = childRecords.map(r => ({ id: r.id }));
await KnackAPI.makeRequest('deleteMany', { scene: childSceneKey, view: viewKey, records: recordsToDelete }); // Delete child records
}
await KnackAPI.makeRequest('delete', { scene: parentSceneKey, view: parentViewKey, recordId: parentId }); // Delete parent record
}
Here is an example of the function call
Knack.on('form:submit', async ({ record, viewKey, isEdit }) => {
if (viewKey === 'view_aa') {
await deleteParentAndChildRecords({
parentId: record.id,
parentSceneKey: 'scene_bb',
parentViewKey: 'view_bb',
childSceneKey: 'scene_cc',
childViewKeys: ['view_cc', 'view_dd']
});
window.location.href = 'https://apps.knack.com/domain-name/app-name/page-url'; // Redirect to another page after deletion
}
});
Click here to access the free installation instructions for both Classic and Next-Gen.
Also feel free to check out my full library of Knack resources here.