You need to sign in to do that
Don't have an account?
Gaurish Gopal Goel
Accessing the Parents field in an After Insert Trigger
I am writing a trigger on Contract. When a contract is inserted an opportunity should be inserted under the same Account. Opportunity's name should be the Account's name.
I am trying to access the account's fields in this way:
For(Contract con:Trigger.new)
{
Opportunity opp = new Opportunity;
opp.name = con.Account.name;
opp.accountid = con.accountid;
insert opp;
}
But con.Account.name always return Null value. How should i accomplish this task and Why can't I access the account's name in this way ?
I tried it like this:
For(Contract con: [select id,account.name,accountid from contract where id in:Trigger.new])
{
//Code
}
It worked fine. But Trigger.new is also a list of Contract, so why we cannot access Account's fields from Trigger.new ?
All Answers
Hello,
Try this:
for(Contract con : [Select Id, aacount.name, account.id from Contract] : Trigger.new)
{
....
code...
{
I tried it like this:
For(Contract con: [select id,account.name,accountid from contract where id in:Trigger.new])
{
//Code
}
It worked fine. But Trigger.new is also a list of Contract, so why we cannot access Account's fields from Trigger.new ?
Ok thanks dapanchal.
Hello,
We can refer related fields, that is relationship fields in trigger. For code snippets please refer following links:
http://blog.wdcigroup.net/tag/salesforce-apex-trigger/
http://salesforce.stackexchange.com/questions/15244/access-field-on-lookup-relationship-in-trigger
Please share your code.
Hi Vinita,
Thanks for reply.
Below is my code. It is just for testing purpose. But in past couple of time I have queried to get related field value in trigger. If this work then it would be great.
If I use below code then it works fine (as per your example given in link). But in this case still we have to query for related field values.