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
munna123munna123 

apex trigger to create child record when we delete parent record

Hi all...

       my requirement is when we delete a record in parent object, a new record with the deleted parent record values should be created in child object.
ManojjenaManojjena
Hi Munna,

I have one question here ,you ar etelling you want to create child record with th evalu eof parent record when you delete the parent record right ?
So your child record will map to which parent record ? Or simply you wnat  to create a child and left the record without relationship .
Which type of relation ship you have ?MD or Lookup ?
munna123munna123
actually its a MD relationship. when we delete record in parent. we should get the child record created with the values of deleted parent record
ManojjenaManojjena
Hi Munna ,
Problem is in Master detail relationship the relationship field is mandatory in child .So Can you tell me one thing which parent record will link to your child record ?
munna123munna123
am not understanding what u r trying to ask. actually when we delete a record in parent object, child object record should be created with that parent record values. This should be done using apex triggers. I tried to some extent and here is my code: trigger tgr_updatetax on customer__c (after delete) { list conlist = new list(); for(customer__c acc : trigger.old){ test__c con = new test__c(); if(acc.Id== con.Id ){ con.Name = acc.name; con.Customer_del__c = acc.OwnerId; system.debug(acc.name); con.phone__c = acc.phone__c; system.debug(acc.phone__c); con.salary__c = acc.salary__c; system.debug(acc.salary__c); con.Billingcity__c = acc.Billing_city__c; system.debug(acc.Billing_city__c); con.Tax__c = acc.Tax__c; system.debug(acc.Tax__c); con.IT_Tax__c = acc.IT_Tax__c; system.debug(acc.IT_Tax__c); } conlist.add(con); } insert conlist; }
Anupam RastogiAnupam Rastogi
Hi Munna,

You can query for the deleted parent record, retrieve its field values and then use them to create the child record. As you have already created an 'after' trigger, just add the code to retrieve the deleted parent record as shown below - 
 
Database.GetDeletedResult result = Database.getDeleted('customer__c', Datetime.now().addHours(-1), Datetime.now());

Database.DeletedRecord[] deleterec = result.getDeletedRecords();

Id custId = deleterec[0].getId();

//--- Include all the fields of the parent in this query which are needed for creating the child
customer__c cust = [select Id, Name from customer__c where Id = :custId ALL ROWS];

System.debug('Output = ' + cust.Name);
Once you have the fields of the deleted parent record, use them for creating a new child record.

Thanks
AR

If the reply was useful and solved your problem then please mark it as best answer.