You need to sign in to do that
Don't have an account?
Amitabhleo
Not able to iterate thru the Object in the Map
Hello,
I am trying to create a trigger for understanding Maps as my real life situation has similar Object relationships.
I want all the Opportunity Names to be Populated as a New Contact on insert or update.
My Problem is I have been able to successfuly query the Opportunity Name and create a new Contact. I am not able to iterate thru the Opporunity Object Map or when there are multiple Opportunities only one contact gets created.
I am enclosing the code and I hope this can run on any instance as I am using standard objects.
Thanks in advance.
trigger accountContactFromOpp1 on Account (before insert, before update) { //trigger accountContactFromOpp on Account (before update, before insert) { /* This is a MAP test the objective is to query all Opportunities for an account which has Billing city as Null (just a test) New Contact for each Opportunity Name */ //passing on all Account Id into a set Set<ID> AcctId = new Set<ID>(); //loop thru the trigger set and build a set of all the Accounts with no contacts. for(Account acct : Trigger.new){ if (acct.BillingCity == NULL){ AcctId.add(acct.Id); } } //for query thos Accouts Id and create a map connecting them Map<ID,Opportunity> myOppMap = new Map<ID,Opportunity>(); for(Opportunity thisOpp : [Select Id, Name, AccountId From Opportunity where AccountId IN : AcctId]){ myOppMap.put(thisOpp.AccountId,thisOpp); } //looping thru the Trigger again ok for(Account acct : Trigger.new){ if(acct.BillingCity == NULL){ acct.Description = myOppMap.get(acct.Id).Name; Contact cont = new Contact(LastName = myOppMap.get(acct.Id).Name,AccountId = acct.Id); insert cont; } }//end loop acct Trigger.new }
You need to loop through all the opportunities linked to the accounts as well as the accounts themselves. The code you have written will only ever work correctly when there is one opportunity linked to an accounts.
Additionally, you may want to move the insert contact outside of the for loop or you may have issues with governor limits.
All Answers
You need to loop through all the opportunities linked to the accounts as well as the accounts themselves. The code you have written will only ever work correctly when there is one opportunity linked to an accounts.
Additionally, you may want to move the insert contact outside of the for loop or you may have issues with governor limits.
Thanks scoobie, the problem has been resolved after the changes that you suggested.
I am also adding the modified code.