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
34213421 

I would like to insert records based on fields on parent

Hi,

I have the Opportunity record which has a date and frequency fields. I would like to insert child records based on the frequency.

For example: If the stage is Closed/Signed and if the frequncy is 24 Months starting from a date field, I would like to have 24 child records to be inserted based on the start date and amount be distributed accordingly

ANy sample code on how I acheive this?
RKSalesforceRKSalesforce
Hello,

I had a similar requirement. Once Opportunity is Closed/Won I had to create 4 Event Records Under Parent Account.
Please find below code: 
public  void createEventsOnOpportunityClose(list<opportunity> opplist){
    Logger.debug('Entering OpportunityTriggerHelper => createEventsOnOpportunityClose');        
    try{   
		Logger.debug('@@@@Inside try');
        //list<opportunity> oppList=[select id, stagename,accountid,Account.name,Account.id,Contact_Name__c,recordTypeId,iswon from opportunity where id in:oppfuture];
         //Set to hold ids of accounts associated with opportunity
        Set<Id> accIdSet = new Set<Id>();
        //Set to hold ids of contacts associated with opportunity
        Set<Id> conIdSet = new Set<Id>();
        //To map AccountId and associated Primary Contact 
        Map<Id,Contact> accountIdAndPrimaryContactMap = new Map<Id,Contact>();
        Map<Id,Account> accountIdAndAccountMap = new Map<Id,Account>(); 
        Map<Id, Integer> accountIdAndEventListSizeMap = new Map<Id, Integer>();
        //To get latest number of events required to be created from custom setting
        Integer NumberOfEvents = QAR_Event_Count__c.getInstance('QAR Events Count').Event_Count__c.intValue();
		Logger.debug('@@@@NumberOfEvents   '+NumberOfEvents);
        //To get the Event recordTypeID of querterlyAccountReview 
        string QuarterlyEventRecorTypeId=RecordTypeHelper.GetRecordTypeID('Event', 'QuarterlyAccountReview');
		Logger.debug('@@@@QuarterlyEventRecorTypeId   '+QuarterlyEventRecorTypeId);
        List<Event> eventList = New List<Event>();
        List<Contact> contactList = New List<Contact>();   
        //To collect AccountIds associated to Opportunity record
        if(!oppList.isEmpty()){
			Logger.debug('@@@@oppList   '+oppList);
            for(Opportunity opp : oppList) {
                if((opp.IsWon == TRUE || opp.stageName == 'Order Accepted' || opp.stageName == 'Contract Signed') && (opp.recordTypeId == IRTelesalesOppRecordTypeID || opp.recordTypeId == DRClosedOppRecordTypeID || 
                    opp.recordTypeId == SaturnOppRecordTypeID )){
                accIdSet.add(opp.AccountId); 
                conIdSet.add(opp.Contact_Name__c);
                }  
            }
			Logger.debug('@@@@accIdSet   '+accIdSet);
			Logger.debug('@@@@conIdSet   '+conIdSet);
        }
        //Map of Opportunity Id and Contact Id associated with OpportunityContactRole
        Map<Id, Id> oppAndConIdMap = New Map<Id, Id>();
        //Map<Id,List<OpportunityContactRole>> oppAndOppConRolesMap = New Map<Id,List<OpportunityContactRole>>();
        if(!oppList.isEmpty()){
            for(OpportunityContactRole oppConRole : [Select Id , OpportunityId, ContactId, Role from OpportunityContactRole Where (Role = 'Decision maker' OR Role = 'Sold To') AND (OpportunityId IN : oppList)]) {
                if(oppConRole.Role == 'Decision maker'){
				oppAndConIdMap.Put(oppConRole.OpportunityId,oppConRole.ContactId);        
				} else if(oppConRole.Role == 'Sold To'){
				oppAndConIdMap.Put(oppConRole.OpportunityId,oppConRole.ContactId);
				}
            }
			Logger.debug('@@@@oppAndConIdMap   '+oppAndConIdMap);
        }
        //To Map Contact Id and Contact 
        Map<Id,Contact> contactIdAndContactMap = new Map<Id,Contact>([select Id,Role__c from Contact where Id In:conIdSet]);
        //To Map Account id and it's associated Primary Contact
        if(!accIdSet.isEmpty()){
            for(Account acc:[select Id, Name,OwnerId,Owner.TIMEZONESIDKEY,(select Id, Role__c,  Primary_Contact__c, Primary_Indicator__c from Contacts),(select Id  from Events Where (QAR_Status__c != 'Confirmed' OR QAR_Status__c != 'Bypass') AND RecordTypeId=:QuarterlyEventRecorTypeId ) from Account where id in:accIdSet]){
                accOwnerTimeZonesIDKey = acc.Owner.TIMEZONESIDKEY;
                accountIdAndAccountMap.put(acc.Id, acc);
                accountIdAndEventListSizeMap.put(acc.Id, acc.Events.size());
                if(!acc.contacts.isEmpty()){
                    
                    for(contact con : acc.contacts){
                        contactList.add(con);
                        if(con.Primary_Indicator__c==true){    
                            accountIdAndPrimaryContactMap.put(acc.Id,con);
                        }
                    }
                }
				Logger.debug('@@@@acc   '+acc);
				Logger.debug('@@@@acc.Events   '+acc.Events);
            }
			Logger.debug('@@@@accountIdAndPrimaryContactMap   '+accountIdAndPrimaryContactMap);
			Logger.debug('@@@@accountIdAndAccountMap   '+accountIdAndAccountMap);
			Logger.debug('@@@@accOwnerTimeZonesIDKey   '+accOwnerTimeZonesIDKey);
			Logger.debug('@@@@contactList'+contactList);
        }
        //To iterate over Opportunity list and create events mentioned in QAR_Event_Count__c custom setting
        if(!oppList.isEmpty()){			
            for(Opportunity opp : oppList) {
				Logger.debug('@@@@accountIdAndEventListSizeMap.get(opp.AccountId)   '+accountIdAndEventListSizeMap.get(opp.AccountId));
                if((accountIdAndEventListSizeMap.get(opp.AccountId)) == 0 || (accountIdAndEventListSizeMap.get(opp.AccountId)) == null){
					Logger.debug('@@@@accountIdAndEventListSizeMap.get(opp.AccountId)   inside If:   '+accountIdAndEventListSizeMap.get(opp.AccountId));
                    if(!contactList.isEmpty() && (opp.IsWon == TRUE || opp.stageName == 'Order Accepted' || opp.stageName == 'Contract Signed') 
                    && (opp.recordTypeId == IRTelesalesOppRecordTypeID || opp.recordTypeId == DRClosedOppRecordTypeID || 
                    opp.recordTypeId == SaturnOppRecordTypeID )){
						Logger.debug('@@@@inside if of condtions sucessfully  @@@@Recordtype and StageName check ');
						Logger.debug('@@@@opp.IsWon   '+opp.IsWon +' @@@@opp.stageName '+opp.stageName+' @@@@opp.recordTypeId '+opp.recordTypeId);
                        //To create events mentioned in QAR_Event_Count__c custom setting
                        for(Integer i = 1;  i <= NumberOfEvents; i++) {
                            DateTime todaysDateTime = System.now();
                            Date todaysDate = todaysDateTime.date();
                            Event evnt = New Event();
                            evnt.WhatId = opp.AccountId;                           
                            evnt.ownerId = accountIdAndAccountMap.get(opp.AccountId).OwnerId;
                            evnt.Subject = 'Account Review.';
                            evnt.RecordTypeId = RecordTypeHelper.GetRecordTypeID('Event', 'QuarterlyAccountReview');
							Logger.debug('@@@@QAR event initialized and recordtypeid is    '+evnt.RecordTypeId);
                            Contact con = contactIdAndContactMap.get(opp.Contact_Name__c);
							Logger.debug('@@@@Got associated Contact    '+con+' @@@@evnt.QAR_Status__c '+evnt.QAR_Status__c);
                            //To set WhoId of event record depending on conditions
                            if(oppAndConIdMap.get(opp.Id) != null){ 
                                evnt.WhoId = oppAndConIdMap.get(opp.Id);
                            } else if(accountIdAndPrimaryContactMap.get(opp.Account.Id) != null){
                                evnt.WhoId = accountIdAndPrimaryContactMap.get(opp.Account.Id).Id;
                            } else {
                                evnt.WhoId = contactList[0].Id;
                            }
							Logger.debug('@@@@evnt.WhoId    '+evnt.WhoId);
                            //To get TimezoneId of AccountOwner
                            String accOwnerTimeZone = TimeZone.getTimeZone(accOwnerTimeZonesIDKey).getDisplayName();
                            //To set start date of event--If event date is falling on Saturday OR Sunday then it should be pushed to coming Monday  
                            if(i == 1){
                                if(System.now().AddDays(30).format('E') == 'Sat'){ 
                                    DateTime eventTime = todaysDate.AddDays(32);
                                    evnt.StartDateTime = Datetime.valueOf(eventTime.addhours(8).format('yyyy-MM-dd HH:mm:ss', accOwnerTimeZone));                                     
                                } else if(System.now().AddDays(30).format('E') == 'Sun'){
                                    DateTime eventTime = todaysDate.AddDays(31);
                                    evnt.StartDateTime = Datetime.valueOf(eventTime.addhours(8).format('yyyy-MM-dd HH:mm:ss', accOwnerTimeZone));
                                } else {
                                    DateTime eventTime = todaysDate.AddDays(30);
                                    evnt.StartDateTime = Datetime.valueOf(eventTime.addhours(8).format('yyyy-MM-dd HH:mm:ss', accOwnerTimeZone));
                                }
                                evnt.EndDateTime = evnt.StartDateTime.addHours(1);
                                timeInterval = timeInterval + 30;
                            }else {
                                if(System.now().AddDays(timeInterval).format('E') == 'Sat'){  
                                    DateTime eventTime = todaysDate.AddDays(timeInterval + 2);
                                    evnt.StartDateTime = Datetime.valueOf(eventTime.addhours(8).format('yyyy-MM-dd HH:mm:ss', accOwnerTimeZone));
                                } else if(System.now().AddDays(timeInterval).format('E') == 'Sun'){
                                    DateTime eventTime = todaysDate.AddDays(timeInterval + 1);
                                    evnt.StartDateTime = Datetime.valueOf(eventTime.addhours(8).format('yyyy-MM-dd HH:mm:ss', accOwnerTimeZone));
                                } else {
                                    DateTime eventTime = todaysDate.AddDays(timeInterval);
                                    evnt.StartDateTime = Datetime.valueOf(eventTime.addhours(8).format('yyyy-MM-dd HH:mm:ss', accOwnerTimeZone));
                                }
                                evnt.EndDateTime = evnt.StartDateTime.addHours(1);
                                timeInterval = timeInterval + 90;
                            }
                            eventList.add(evnt);        
                        }
						Logger.debug('@@@@eventList    '+eventList);
						Logger.debug('@@@@in Else of map Value' + accountIdAndEventListSizeMap.get(opp.AccountId));	
                    }                  
                }
            }
            if(!eventList.isEmpty()){
				Logger.debug('@@@@QAR Records are about to insert    ');
                insert eventList;
            }
        }                                         
    }
    catch(Exception ex)  {
        AuditErrorHelper.handleException('Error on OpportunityTriggerHelper->createEventsOnOpportunityClose ', ex, AuditErrorHelper.EXCEPTION_SEVERITY_LOW, null); 
        Logger.debug('Error on createEventsOnOpportunityClose method at line: '+ex.getLineNumber()+' error msg: '+ex.getMessage());
        Logger.debug('Trigger Records: '+oppList);
        throw new TriggerException('Error on'+ 'createEventsOnOpportunityClose'+ 'method on OpportunityTriggerHelper class'+ 
                                    'with the following error message'+ ex.getMessage() + 'Stack Trace = '+ ex.getStackTraceString() );  

    }  
  
  }

Please mark as best answer if helped.

Regards,
Ramakant​