0

I am looking to create a trigger off of a custom object (ObjA - Looks up to Accounts and Opportunities) that will create a record in custom object (ObjB) based on fields from ObjA and some related fields from Accounts/Opportunities.

I receive errors that my related fields do not exist. Can anyone provide insight?

trigger ObjBCreate on ObjA (after insert) {
List<ObjB> recordsToInsert = new List<ObjB>();
for (ObjA l : Trigger.new) {
    if (l.IsInsert) {
        ObjB la = new ObjB();
        v.Account__r.Name = o.Account_Name__c;
        v.Name = o.Account__c;
        v.Account__r.Enterprise_Account__r.Name = o.Enterprise_Account__c;
        v.Account__r.Billing_Location__r.Name = o.Main_Account__c;
        v.Opportunity__c = o.Opportunity__c;


        recordsToInsert.add(la);
    }
}
insert recordsToInsert;

}
  • a bit puzzled here with OP, variable o is never declared – cropredy Oct 2 '16 at 19:49
  • @cropredy I modified it to "l" and "la" – Awesome User2 Oct 3 '16 at 13:21
  • I'm still not seeing variable o declared, see line 6 – cropredy Oct 3 '16 at 16:16
0

When inserting a record, you do not reference relationship fields (__r) like that. If you have to reference an Account, for example, then you just pass the account Id into the account lookup field on the object you are manipulating.

You can do this:

v.Account__c = o.Account.Id

but you can't do this:

v.Account__r.Name = 'A name for this account'

After inserting the v record, you will be able to query it and bring the account name because now the records have a relationship, like:

SELECT Id, Account__c, Account__r.Name FROM Custom_Object_B__c

| improve this answer | |
  • thanks! What about the others fields: v.Account__r.Enterprise_Account__r.Name = o.Enterprise_Account__c; v.Account__r.Billing_Location__r.Name = o.Main_Account__c; – Awesome User2 Sep 29 '16 at 23:15
  • When you set the reference into the account field, the other fields become populated automatically. You only need to set the reference to the account and insert the record. – Renato Oliveira Sep 29 '16 at 23:16
  • However, I got this compile error now: Error: Compile Error: Arithmetic expressions must use numeric arguments at line 9 column 12 for v.Account__r.Enterprise_Account__r.Name = o.Enterprise_Account__c; v.Account__r.Billing_Location__r.Name = o.Main_Account__c; – Awesome User2 Sep 30 '16 at 1:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.