+ Start a Discussion
Gab SilvermotionGab Silvermotion 

help with trigger that updates a lookup field on the case object

Hello! I am new to apex development and any help is greatly appreciated. 

Here is the issue i am having. 

We are a real estate developer, and we use the case objects to log defiencies in condos (missing a door, scratches in the paint, cracks in a counter, etc)

our assets are in the following format : (project name) - (condo number)

instead of using the standard lookup field functionality (the looking glass, then search for keywords), i'd love to have 2 dropdown custom fields on the case object, one for the project, and one for the unit number, and when we save the new case, an apex trigger would run and concatenate the values of those fields into the (project name) - (condo number) format, and update the asset lookup field. 

I tried with a workflow rule + field update, but it won't let me update lookup fields. 

how would i go into doing that?

thank you very much!








KevinPKevinP
Lookup fields are actually store the ID of the related object. Hence the lookup field to asset actually stores the ID not the name. Your trigger, would only need to adjust the name field of the asset. 
Gab SilvermotionGab Silvermotion
Hello!

Ok then let allow me to rephrase this. all the assets have unique names. 

In the Case object, a trigger that would look at the value of a custom formula field, which will contain an asset name. Then it would retrieve the ID of that asset, and then copy that ID into the asset lookup field, to link it to the right asset. 

so i could use my picklist fields as described in my original post, concatenate the name into a 3rd field, and use the trigger to correctly populate the asset field with it's ID, therefore allowing me to skip the lookup procedure (some users don't like it, i was asked to modify this). 

thanks!
David "w00t!" LiuDavid "w00t!" Liu
You can definitely do this with a trigger!

The key is using SOQL to query for the Asset that has the values in your concatenated field.

Your SOQL query would be something like this:
for (Case c : Trigger.new) {
    Asset a = [SELECT Id FROM Asset WHERE Asset_Custom_Field__c = :c.Case_custom_Field__c];
    c.Asset = a.Id;
}

I simplified it a bunch since you're new, and even though the above will work, it will break if you ever do big batch jobs in your org. "Bulkifying" your code is a little more complicated, but if you want to read more about it you can go here:
http://www.sfdc99.com/beginner-tutorials/#soqlTrigger