You need to sign in to do that
Don't have an account?
Violet
Auto-populate lookup field from Custom object on Standard Object
Trying to auto-populate Custom_Object on Asset from Opportunity before insert. Getting errors, any help would be appreciated
Asset has lookup to Opportunity
Asset has lookup to Custom_Object
Custom_Objet has lookup to Opportunity
Asset has lookup to Opportunity
Asset has lookup to Custom_Object
Custom_Objet has lookup to Opportunity
trigger AutoPopulate on Asset (before insert) { Map <Id, Opportunity> mapidopp= new map<id,Opportunity> ([select Id,(select Id,Name from Custom_Object__r where Is_Primary__c=true ),(select Id,Name from Assets__r where Id IN: Trigger.new)from Opportunity where (Id IN (SELECT Opportunity_Name__c from Custom_Object__c))]); List <Asset> listasst=new List <Asset> (); for(Id i: mapidopp.keyset()){ for (Custom_Object__c obj:mapidopp.get(i).Custom_Object__r){ for (Asset asst:mapidopp.get(i).Assets__r ){ System.debug('test7' + obj.Id); //getting error here that Custom_Object_r.Id was not retrieved in SOQL //but when I add it to SOQL get Attempt to de-refernece a null point asst.Custom_Object__r.Id=obj.Id; listasst.add(asst); System.debug('test4' + asst.Custom_Object__r.Id); } } } insert listasst; }
I have updated the code, and I am populating the value in before insert. Try this code: Let me know, if you need any other help.
Thanks,
Neetu
All Answers
As your trigger with before insert so record is not in data base so ID is not generated that is the reason you got first error .
BAsically in apex you should not write loop inside loop inside loop which have max chance to hit the LIMIT .
Can you explain your requirment So that we can help you .
- Asset has lookup relationship to Opportunity (You can create Assets from Opportunity)
- Asset has lookup relationship to A (Custom_Object)
- A(Custom_Objet_c) has lookup relationship to Opportunity: A has Is_Primary flag
I even tried a simpler approach but getting: System.StringException: Invalid id when trying to assign the Lookup field to a text valueI have updated the code, and I am populating the value in before insert. Try this code: Let me know, if you need any other help.
Thanks,
Neetu
@Neetu-It worked! It is amazing! Thank you so much! I see you used Sets in your code if there are any good resources to understand Maps and Sets for this type of triggers I would appreciate it if you could send me the links.