function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ElcalvoMikeElcalvoMike 

Query of object on before insert trigger

This seems like a layup but cant figure out the syntax.

Since I cant use a formula field to reference cross-objects on standard objects (we like the case to be related to the opportunity) I need to populate two fields that I will use in a simple mail template.

How do i reference the value that is in case field Order_Number__c?

trigger addOppFields on Case (before insert) {
Case mycase=trigger.new[0];
Opportunity opp=[select ID,Webpartner__c from Opportunity where name = :mycase.Order_Number__c];
mycase.XMWebPartner__c=opp.Webpartner__c;
mycase.Merge_OpportunityID__c=opp.ID;

 

Best Answer chosen by Admin (Salesforce Developers) 
grigri9grigri9

Order_number__c is a lookup to opportunity? In that case the value in there is the opportunity ID so you just need to filter on ID instead of name.

All Answers

grigri9grigri9

Use a colon when referencing variables in soql I.E.

 

Opportunity opp=[select ID,Webpartner__c from Opportunity where name = :mycase.Order_Number__c];

 

ElcalvoMikeElcalvoMike

Sorry that was a typo on my part. It does have the colon.

The issue is it is returning no records, if I hardcode a value it works.

 

Thanks,

grigri9grigri9

Is order_number__c being filled out by a workflow rule? It will be null in a before insert trigger if that is the case. Try system.debugging the value of mycase.Order_number__c and check if it's null.

ElcalvoMikeElcalvoMike

It is being typed in by the case creator prior to saving a new case.

 

ElcalvoMikeElcalvoMike

it is returning null, but not because it is in workflow.

this field is a look up field and im trying to take the entered value, like AAA-1234, and find the opp ID for that opp name.

maybe this is not possible with kind of field?

grigri9grigri9

Order_number__c is a lookup to opportunity? In that case the value in there is the opportunity ID so you just need to filter on ID instead of name.

This was selected as the best answer
ElcalvoMikeElcalvoMike

Yep, I didnt realize the Lookup happend prior to before insert.

Thanks!