function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Hermann OuréHermann Ouré 

Trigger to Delete related child record after status update on the parent

Hello,

I have a child object called Known_Error_Subscription__c and anytime a client subscribe to an Article (parent object : Knowledge__kav), a record is automatically created on the child object Known_Error_Subscription__c
When the Article is archived, meaning when the PublishStatus is updated to 'Archived' on the parent object Knowledge__kav, I would like the related record on Known_Error_Subscription__c to be deleted.

I have created a Trigger but can't figure out what I am doing wrong.
Thanks
 
trigger Knowledge_kavTrigger on Knowledge__kav (after update) {
    
    List<Known_Error_Subscription__c> kesListToDelete = new List<Known_Error_Subscription__c>();
    
    for(Knowledge__kav kav : [SELECT KnowledgeArticleId, PublishStatus, (SELECT Knowledge__c FROM Known_Errors_Subscriptions__r) FROM Knowledge__kav 
             WHERE PublishStatus = 'Archived' AND Id IN :Trigger.New]) {
                 
        kesListToDelete.add(kav.Known_Errors_Subscriptions__r);
       
    }
    delete kesListToDelete;
    
}

 
AnudeepAnudeep (Salesforce Developers) 

Your code should look like this. Let me know if this helps

trigger Knowledge_kavTrigger on Knowledge__kav (after update) {
    
List<Known_Error_Subscription__c> kesListToDelete = new List<Known_Error_Subscription__c>();

List<Id> kvList = new List<Id>();

for(Knowledge__kav kn:Trigger.new) {
       if(kn.PublishStatus=='Archived') {
          kvList.add(kn.id);
    }

kesListToDelete = [Select id from Known_Errors_Subscriptions__c where lookupFieldName IN:kvList];

delete keListToDelete
}

This is based on a simple example on how to delete child record in lookup relationship
trigger DeleteContact on Account (after delete)
{
    List<Contact> contacts = [SELECT AccountId FROM Contact WHERE AccountId IN:Trigger.OldMap.keyset()];
    delete contacts;
}
Hermann OuréHermann Ouré
Thank you Anudeep for your answer but still, the related record is not deleted, unfortunately