+ Start a Discussion
Christos KolonisChristos Kolonis 

How to iterate through a map and create a record for each iteration


I need to create a contract record when a triggering event is occured. In the bellow code i need to loop through subscription records  and create a record for each subscription. However the services object can also have many records which each is associated with one subscription. So for example i have two subscriptions and two services, how can i create two records? one for each? (the subscription and services are fields in the contract object). Here is a snippet of my code:
map<Id, csord__Order__c> orderMap = new map<Id, csord__Order__c>([select id, name, csordtelcoa__Opportunity__c, csordtelcoa__Opportunity__r.AccountId, csordtelcoa__Opportunity__r.Account.name from csord__Order__c where id in:orderIds]);
            map<Id, csord__Subscription__c> subsMap = new map<Id, csord__Subscription__c>([select id, name from csord__Subscription__c where id in: subsIds]);
            system.debug('The subscriptions are ' + subsMap);
            map<Id, csord__Service__c> servicesMap = new map<Id, csord__Service__c>([select id, name, csord__Subscription__c from csord__Service__c where id in: serviceIds AND csord__Subscription__c =: subsMap.values().id AND csord__Service__c = null]);
            system.debug('The services are ' + servicesMap);
            map<Id, OpportunityContactRole> oppRoleMap = new map<Id, OpportunityContactRole>([select id, OpportunityId, ContactId, isPrimary from OpportunityContactRole where OpportunityId =: orderMap.values().csordtelcoa__Opportunity__c AND isPrimary = true limit 1]);
            for(csord__Subscription__c sub: subsList){
                csconta__Contract__c contract = new csconta__Contract__c();
                contract.csconta__Contract_Name__c = orderMap.Values().csordtelcoa__Opportunity__r.Account.name + ' Contract';
                contract.csconta__Account__c = orderMap.Values().csordtelcoa__Opportunity__r.AccountId;
                contract.csconta__Valid_From__c = system.today();
                contract.csconta__Status__c = 'Open';
                contract.csconta__Contact__c = oppRoleMap.Values().ContactId;
                contract.csconta__Order__c = orderMap.values().id;
                for(Id servi: servicesMap.keySet()){
                contract.csconta__Service__c = servicesMap.get(servi.id).id;    
                //contract.csconta__Service__c = servicesMap.values().id;
                contract.csconta__Subscription__c = sub.id;
            insert contrList;
            return contrList;