+ Start a Discussion
shikher jainshikher jain 

I created two custom classes class and student. I want to create a trigger for updating some values and delete related students

trigger CustomStatusChanged on Class__c (before update) {

    for(Class__c cls : trigger.new){
        if(cls.Custom_Status__c == 'Reset'){
            delete [Select Name from Student__c where Class_object__c in :trigger.new];
        }
    }
}

I have written this code but got self reference error
Best Answer chosen by shikher jain
ANUTEJANUTEJ (Salesforce Developers) 
What I meant was initially you could get all the class ids that match the condition: cls.Custom_Status__c == 'Reset'  then get all the list of records of the student where the class ids are in the set then in a single DML operation you can simply delete the list of student records.

Generally, soql queries inside a loop is not considered as a best practice that is why I was suggesting the above method.

As your implementation could change this was one way I thought this can be implemented.

 You can find something similar in the link :- [ https://salesforce.stackexchange.com/questions/45566/deleting-child-records-on-a-parent ]

I hope this helps.

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Shikher,

Can you try putting the necessary records in a list and then delete do a DML operation after the loop, let me know if this works and you are doing a soql for every value is an iteration in the trigger.new can you try minimizing it by adding the classes id or such to a set then get the student records that match it and then delete them after the loop.

Do let me know if this helps and in case if it does can you mark this as the best answer so that it can be used by others in the future.

Regards,
Anutej
shikher jainshikher jain
Hi Anutej , I am unable to understand your concern , could you please elaborate it with a slice of code.
ANUTEJANUTEJ (Salesforce Developers) 
What I meant was initially you could get all the class ids that match the condition: cls.Custom_Status__c == 'Reset'  then get all the list of records of the student where the class ids are in the set then in a single DML operation you can simply delete the list of student records.

Generally, soql queries inside a loop is not considered as a best practice that is why I was suggesting the above method.

As your implementation could change this was one way I thought this can be implemented.

 You can find something similar in the link :- [ https://salesforce.stackexchange.com/questions/45566/deleting-child-records-on-a-parent ]

I hope this helps.
This was selected as the best answer