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
Malli GMalli G 

triggers to avoid the delete of contacts records in case of masterdetail relationships

hai hall
we know incase  of masterdetailrelationship if delete the parentrecords child will also deleted
i have  a requirement if i delete the account record account will be deleted but  i dont want to delete the contacts records in case of masterdetailrelationship please can any one helpme
Rohit K SethiRohit K Sethi
Hi Malli G,

This is nice question. As we know that whenever we delete the master record automatically all child records will deleted. 
According to requirement we can handle this thing by using before delete trigger on account .

Here is the code of trigger :
trigger AccountTrigger1 on Account (before delete) {
    List<Contact> lstContact = [select id,name,AccountId from contact where accountId in : trigger.oldMap.keySet()];
    for(Contact cont : lstContact){
        cont.accountId=null;
    }
    if(lstContact.size()>0)
        update lstContact;
}
Note : this trigger first filling those contact whose account is deleted and remove the relation between them. When account is deleted there relation will allready remove through this way we can prevent the child record from delete.


If this post solves your problem kindly mark it as solution.
Thanks.
Malli GMalli G
thank you Rohit sethi20
i have adoubt i have a two custom objects but there is  no relation between them we can update object1, can we update the object2 i think it is not possible right but object2  having lookup to user now can we update  to object2
 
Malli GMalli G
Hai
Rohit K sethi
But it will not delete the account record it will throws an exception
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger delll caused an unexpected exception, contact your administrator: delll: execution of BeforeDelete caused by: System.DmlException: Update failed. First exception on row 1 with id 0032800000GMtfpAAD; first error: FIELD_INTEGRITY_EXCEPTION, A portal user's contact record must include an account. Furthermore, the owner of the account must be associated with a role.: Account ID: [AccountId]: Trigger.delll: line 7, column 1". 

Click here to return to the previous page.