You need to sign in to do that
Don't have an account?
aditya prasad
How to use lookup field in a trigger?
I need to insert ContactRole record for an opportunity while creating an opprtunity from some custom object.I have written a trigger i.e after insert on opportunity.
if (trigger.isinsert)
{
oppty = trigger.new;
for(opportunity Opt:oppty)
{
system.debug('Dealer'+Opt.Installed_Product__r.Dealer_1__c);
if(Opt.Installed_Product__c !=null){
system.debug('Method Entry'); OpportunityContactRole OCR1 = new OpportunityContactRole(ContactId=Opt.Installed_Product__r.Dealer_1__c, OpportunityId=Opt.Id,IsPrimary=TRUE);
NewOppCRole.add(OCR1);
}
But every time I get ContactId = null.So insertion failed since it is a mandatory field.
Is there any way to solve this issue?
Thanks in advance.
if (trigger.isinsert)
{
oppty = trigger.new;
for(opportunity Opt:oppty)
{
system.debug('Dealer'+Opt.Installed_Product__r.Dealer_1__c);
if(Opt.Installed_Product__c !=null){
system.debug('Method Entry'); OpportunityContactRole OCR1 = new OpportunityContactRole(ContactId=Opt.Installed_Product__r.Dealer_1__c, OpportunityId=Opt.Id,IsPrimary=TRUE);
NewOppCRole.add(OCR1);
}
But every time I get ContactId = null.So insertion failed since it is a mandatory field.
Is there any way to solve this issue?
Thanks in advance.
I see you are setting "ContactId" by a field which is not present on opportunity itself, and that is the problem. Apex trigger does not provide data from relationships. Thus if you need "Dealer_1__c" from "Installed_Product__r", then you may do it in following two ways.
- Recommended way - Create a formula field on opportunity that stores "Dealer_1__c" from related "Installed_Product" object, and then you may use this formula field to set "ContactId" for "OpportunityContactRole" in above trigger.
- In above trigger, query the all required "Installed Products" parents and get its "Dealer_1__c" from query and set it "ContactId" for "OpportunityContactRole"
HTH,Suraj
All Answers
I see you are setting "ContactId" by a field which is not present on opportunity itself, and that is the problem. Apex trigger does not provide data from relationships. Thus if you need "Dealer_1__c" from "Installed_Product__r", then you may do it in following two ways.
- Recommended way - Create a formula field on opportunity that stores "Dealer_1__c" from related "Installed_Product" object, and then you may use this formula field to set "ContactId" for "OpportunityContactRole" in above trigger.
- In above trigger, query the all required "Installed Products" parents and get its "Dealer_1__c" from query and set it "ContactId" for "OpportunityContactRole"
HTH,Suraj
Here is code you need to write for trigger.
-Thanks
Ashlekh Gera
It solved my problem
Aditya