You need to sign in to do that
Don't have an account?
Trigger using a reference field
I have custom object called "Locations" from which my team can create Opportunities. "Locations" contains a "LocationDescription__c" field that's usually full of great notes, so I'd like to build a trigger to copy those notes into my Opportunity.Description field. Simple enough right?
I expect that I have to build a Map<>, maybe do a SOQL query to store the related object data into the trigger, but I'm very new to this.
Here's my code, which stores a null value into Opportunity.Description when it's executed:
trigger OppUdate on Opportunity(before insert, before update) {
for(Opportunity opp : Trigger.new){
if (opp.Description == null) {
opp.Description = opp.Location__r.LocationDescription__c;
}
}
}
Thanks in advance!
You're perfectly right. Here's how it goes:
Note, Location__c is the presumed data type name for the lookup's data type; adjust as necessary.
Brackets are omitted for brevity, but please feel free to include them if necessary.
All Answers
You're perfectly right. Here's how it goes:
Note, Location__c is the presumed data type name for the lookup's data type; adjust as necessary.
Brackets are omitted for brevity, but please feel free to include them if necessary.
You could also have a formula field in the opportunity pointing to the location description: Location__r.LocationDescription__c
You can also pass this value to the opportunity in the URL using a custom button: *Change code in red with the id of the location field in opportunity
/006/e?retURL=%2F{!Location__c.Id}&ent=Opportunity&&opp4={!Account.Id}&opp14={!Location__c.Description__c}&CF00NZ0000000Y2DK={!Location__c.Name}&CF00NZ0000000Y2DK_lkid={!Location__c.Id}
Hope this helps!
Thanks, that's the stuff! I edited my post a tiny bit so here's your code updated with those changes too (for posterity):
trigger OppUpdate on Opportunity(before insert, before update) {
Map<Id,Location__c> locations = new Map<Id,Location__c>();
for(Opportunity record:Trigger.new)
locations.put(record.Location__c,null);
locations.putAll([SELECT Id,LocationDescription__c FROM Location__c WHERE Id IN :locations.keySet()]);
for(Opportunity record:Trigger.new)
if(record.Description == null)
record.Description = locations.get(record.Location__c).LocationDescription__c;
}
if(string.isblank(record.description)&&record.location__c!=null)
Izay, you're right, that a formual field would actually solve this problem too, but I built a whole bunch of formula fields on this object already and I am running out references. I learned about the magical power of formula fields early on, and, well, when you only have a hammer, every problem looks like a nail right?