I have a custom object that is mirrored (Service_Order__c -> Opportunity) to when new records are created, the most part of the apex is bulkified however I am having trouble understanding how maps work and how get get the inserted ID's from Opportunity
so I can update my Service_Order__c
and my OpportunityContactRole
objects.
Could someone explain how to get these ID's and how I update/insert the record in my trigger?
So I need to update Service_Order__c > OpportunityID__c
and insert OpportunityContactRole > OpportunityID__c
.
trigger MirrorOpportunity on Service_Order__c (before insert,after insert){
Id UserId = UserInfo.getUserId();
User user = [select AccountId, ContactId from User where id=:UserId];
String stage = '01 - Pre-Bid';
Stages__c s = [SELECT Id, Name, Value__c FROM Stages__c WHERE Name = :stage];
User uO = [select id, usertype, userroleid from User where userroleid = '00ED0000001WmkV' AND IsActive=true LIMIT 1];
list<Opportunity> oppList = new list<Opportunity>();
list<Status_History__c> statusHistoryList = new list<Status_History__c>();
list<OpportunityContactRole> oppContactList = new list<OpportunityContactRole>();
for(Service_Order__c so : trigger.new) {
if(trigger.isBefore) {
Opportunity opp = new Opportunity();
opp.StageName = stage;
Date oppcloseddate = so.Project_Deadline__c;
so.Account__c = user.AccountId;
so.Contact__c = user.ContactId;
opp.Name = so.Name;
oppcloseddate = oppcloseddate.addDays(120);
opp.CloseDate = oppcloseddate ;
opp.LeadSource = so.Lead_Source__c;
opp.AccountId = so.Account__c;
so.Opp_Status__c = s.Value__c;
opp.Description = so.Description__c;
opp.Customer_Name__c = so.Customer_Name__c;
opp.OwnerId = uO.id;
oppList.add(opp);
so.Opportunity__c = opp.Id;
}
if(trigger.isAfter) {
Status_History__c sh = new Status_History__c();
sh.name = s.Value__c;
sh.Service_Order__c =trigger.new[0].Id;
statusHistoryList.add(sh);
OpportunityContactRole oppContact = new OpportunityContactRole();
oppContact.ContactId = user.ContactId;
oppContact.IsPrimary = true;
oppContact.OpportunityId = '';
}
} // end for loop
insert oppList;
insert statusHistoryList;
insert oppContactList;
}
Stages__c s = [SELECT Id, Name, Value__c FROM Stages__c WHERE Name = :stage];
do? I don't understand this sincestage
is a string constant. Also, are you able to combine any of your queries into single queries? This is a lot of queries to run with each execution of the trigger! – crmprogdev Feb 5 '15 at 14:17Value__c
from a Custom Setting and inserts into myStage_History__c
object. It is used inside theisAfter
part of the trigger. – Deployment Failure Feb 5 '15 at 14:19isAfter
code so that it is only used inside that portion of your code and not every time your trigger runs. Are you unable to use something likeStages__c s = Stages__c.getValues('01 - Pre-Bid');
to return your custom settings and save a query? – crmprogdev Feb 5 '15 at 14:36