Activity › Forums › Salesforce® Discussions › How can i call relationship object fields in Salesforce trigger?
Tagged: Account, Relationship Object, Salesforce Apex, Salesforce Fields, Salesforce SOQL, Salesforce Trigger
-
How can i call relationship object fields in Salesforce trigger?
Posted by Naman on April 30, 2016 at 5:43 PMHow can i call relationship object fields in trigger?
William replied 7 years, 5 months ago 4 Members · 3 Replies -
3 Replies
-
Hi Naman,
Here is the solution for what I understand from your question:
Suppose you have a trigger on Contact and you want to access Account fields.
trigger afterInsertContact on Contact (after insert){
for(Contact conObj : trigger.new){
system.debug(conObj.AccountId);
}
}For standard relationships, you can simply use the . (dot) notation and refer to the fields.
However for a custom relationship, you need to use __c and __r.Thanks
- [adinserter block='9']
-
You should be specifying more details, however at a high level this is how you do it
Supposing your trigger is on Contact and you want to access Account fields, this is how you do it.
trigger triggerContact on Contact (after insert){
for(Contact cont : trigger.new){
system.debug(cont.AccountId);
}
}The bold text is where I am fetching the account id for each contact in trigger. Similarly you can refer other fields.
NOTE: for standard relationships, you simply use the . (dot) notation and refer the fields.
However for a custom relationship, you need to use __c and __rexample: custom object patient__c is related to Account standard object (relationship field : Account__c).
patient__r.Account__c – this will give me account id for a patient record.Hope this helps!
-
We have two object account and contact. In this scenario, you have a contact object which has a lookup relationship to account. When processing the contact records in your trigger, you want to access some fields on the account via the relationship. Your trigger might look something like this:
trigger parent2child on Account (after update) { list<id>ids = new list<id>(); list<contact>conlist = new list<contact>(); for(account a:trigger.new){ ids.add(a.id); list<contact>con =[select id,phone,account.phone from contact where accountid in:ids]; for(contact c:con) { c.Phone=c.account.phone; conlist.add(c); } update conlist; } }-
This reply was modified 7 years, 5 months ago by
William.
-
This reply was modified 7 years, 5 months ago by
Log In to reply.