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
TraceyTracey 

Field not updating via trigger - Help

I have created a custom field caled Related Product on the Asset object. The Trigger below is not updating this field when an Asset is inserted or updateed. Could someboby please explain to me what is wrong with this code?

trigger AssetRelatedProduct_BeforeUpdate on Asset (before insert, before update) {
    
            
    
    for ( Asset assetdata : [Select a.Related_Product__c, a.Product2Id, a.Id From Asset a  where  a.id in :Trigger.New])
   {
        for (Product2 productdata : [Select p.Name, p.Id From Product2 p where p.id = : assetdata.Product2id])
        {
            assetdata.Related_Product__c = productdata.Name;
        }
   }
   
}
HarmpieHarmpie
Why would you create a trigger here? What about a formula field (on Asset) containing Product2.Name ?
JimRaeJimRae

I would agree with Harmpie that a cross object formula field is a much simpler solution.

However, if you really need to use the trigger, there are a few issues to address with your current code.

First, and probably biggest, the code is not bulk safe.  For each element of your outer for loop, you are executing another SOQL query.  You will quickly it the governer limit with this method.  Second, your outer query is invalid, you are using the Trigger.new as an include parameter for the query.  Trigger.new returns a list of objects (in your case Assets, what you need is a list of ID's, which would actually be the Trigger.newMap.keySet().  Lastly, you need to update the Trigger.new list of objecs directly, you are trying to update an indirect reference created by your query.