+ Start a Discussion
dnakonidnakoni 

Accessing referenced objects on a custom object

I created a custom object AccountContactAssociation that servers as a many-to-many join. It has two custom Master-Detail fields. 

 

One is named Account and is a Master-Detail(Account).

One is named Contact and is a Master-Detail(Contact).

 

I'm trying to create a trigger as follows:

 

 

trigger AccountContactAssociationTrigger on AccountContactAssociation__c (after insert) {

AccountContactAssociation__c ac = Trigger.new[0];

 

  

  ac.Contact.FirstName = ac.Account.Name;

 

 

 

 

What I am basically trying to do is to access a field in the Account that is referenced by the junction object (in this case string Name) and assign it to a FirstName field in the referenced Contact object.

 

 

The above code does not compile, and I have a hard time figuring how to access the abovementioned fields.

 

 

I would greatly appreciate any suggestions.

 

Thanks! 

Best Answer chosen by Admin (Salesforce Developers) 
dnakonidnakoni

Ok everyone, I found a solution:

 

 

 

 

AccountContactAssociation__c ac = Trigger.new[0];

 

Account a = [select id, name, from account where id = :ac.Account__c];

Contact c = [select id, firstname, from contact where id = :ac.Contact__c];

c.firstname = a.name;

update c; 

All Answers

wesnoltewesnolte

Hey

 

Try this:

 

 ac.Contact__r.FirstName = ac.Account__r.Name;

 

Cheers,

Wes 

dnakonidnakoni

Thanks! I tried that, and received no compilation error. However, when I go to my object, and select an Account in one field, and select a Contact in the other field, and then click Save, it gives me the following error:

 

AccountContactAssociationTrigger: execution of AfterInsert 

caused by: System.NullPointerException: Attempt to de-reference a null object 

Trigger.AccountContactAssociationTrigger: line 4, column 2 

 

 

Line 4 column 2 is the beginning of the code I'm trying to use:

 

ac.Contact__r.FirstName = ac.Account__r.Name;

 

 

After looking on the internet, I saw that Contact__r is the proper way of accessing referenced objects, so I'm wondering why it doesn't work here. Does anyone have any ideas?

 

Thanks! 

dnakonidnakoni

Ok everyone, I found a solution:

 

 

 

 

AccountContactAssociation__c ac = Trigger.new[0];

 

Account a = [select id, name, from account where id = :ac.Account__c];

Contact c = [select id, firstname, from contact where id = :ac.Contact__c];

c.firstname = a.name;

update c; 

This was selected as the best answer
dkndkn

How do you write a trigger for this ?

I am new to salesforce , trying to figure this ?

I would appreciate if you could tell me the test case for this trigger of yours.