You need to sign in to do that
Don't have an account?
Shavi Dabgotra
I have created a checkbox on opportunity as 'IsDeleted'. Whenever Whenever user mark this checkbox as true, opportunity record should get deleted.
Hi everyone!
I have created a checkbox on opportunity as 'IsDeleted'. Whenever user mark this checkbox as true, opportunity record should get deleted.
I am new to apex trigger. Can someone help me?
Thank you
I have created a checkbox on opportunity as 'IsDeleted'. Whenever user mark this checkbox as true, opportunity record should get deleted.
I am new to apex trigger. Can someone help me?
Thank you
Trigger
trigger DeleteonChecked on Opportunity (after update) {
if(trigger.isAfter && trigger.isUpdate){
OpportunityTriggerHandler.deleteOpportunities(trigger.newMap.keyset());
}
}
Class
public class OpportunityTriggerHandler{
public static void deleteOpportunities(Set<Id> oppIdSet) {
List<Opportunity> deleteOppsList = [Select Id,IsDeleted__c from Opportunity where IsDeleted__c=true And Id In: oppIdSet];
if(!deleteOppsList.isEmpty()) {
delete deleteOppsList;
}
}
}
All Answers
trigger OpportunityTrigger on Opportunity (after update) {
List<Opportunity> deleteOppList = new List<Opportunity>();
for(Opportunity opp: trigger.new) {
if(opp.IsDeleted__c) {
deleteOppList.add(opp);
}
}
if(!deleteOppList.isEmpty()) {
delete deleteOppList;
}
}
In case if you want to delete multiple records you can check this implementation that has a way to select records and delete,
>> http://help.taskfeedapp.com/knowledgebase/articles/1108435-custom-mass-delete-board-button-classic-only
Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
Thanks.
I have tried as you suggested but it is giving me error as DeleteonChecked: execution of AfterUpdate caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old Trigger.DeleteonChecked: line 10, column 1 salesforce
How to fix it?
Can someone help me in this?
Thanks in advance
Below is my code:
trigger DeleteonChecked on Opportunity (after update) {
if(trigger.isAfter && trigger.isUpdate){
List<Opportunity> deleteOppList = new List<Opportunity>();
for(Opportunity opp: trigger.new) {
if(opp.IsDeleted__c) {
deleteOppList.add(opp);
}
}
delete deleteOppList;
}
}
Thank you
Trigger
trigger DeleteonChecked on Opportunity (after update) {
if(trigger.isAfter && trigger.isUpdate){
OpportunityTriggerHandler.deleteOpportunities(trigger.newMap.keyset());
}
}
Class
public class OpportunityTriggerHandler{
public static void deleteOpportunities(Set<Id> oppIdSet) {
List<Opportunity> deleteOppsList = [Select Id,IsDeleted__c from Opportunity where IsDeleted__c=true And Id In: oppIdSet];
if(!deleteOppsList.isEmpty()) {
delete deleteOppsList;
}
}
}
In either case, it's recommended to put the actual code in helper classes instead of putting the logic in trigger.
Please mark my answer as the best answer if it was helpful.