+ Start a Discussion
sfdc newbiesfdc newbie 

Creating multiple assets at account level

Can anyone tell me where is this error occuring as Everytime a user edits their opportunity value after they set their deal to Award Close 100% according to the opportunity history, a new asset is created for each value edit that is shown in the opportunity history section.

By this Assets are creating multiple times at account object.

trigger CreateAssetonClosedWon on Opportunity (after insert, after update) {
     for(Opportunity o: trigger.new){
      if(o.isWon == true && o.HasOpportunityLineItem == true){
         String opptyId = o.Id;
         OpportunityLineItem[] OLI = [Select UnitPrice, Quantity, PricebookEntry.Product2Id, PricebookEntry.Product2.Name, Description, Converted_to_Asset__c 
                                      From OpportunityLineItem
                                      where OpportunityId = :opptyId  and Converted_to_Asset__c = false];
       List<Asset> ast = new List<Asset>();
      /*  Asset[] ast = new Asset[]{}; */
         Asset a = new Asset();
         for(OpportunityLineItem ol: OLI){
            a = new Asset();
        a.AccountId = o.AccountId;
            a.Product2Id = ol.PricebookEntry.Product2Id;
            a.Quantity = ol.Quantity;
            a.Price =  ol.UnitPrice;
            a.PurchaseDate = o.CloseDate;
            a.Status = 'Purchased';
            a.Description = ol.Description;
            a.Name = ol.PricebookEntry.Product2.Name;
            ol.Converted_to_Asset__c = true;
      update OLI;
      insert ast;
John WestenhaverJohn Westenhaver
There are several issues here:

1. The reason this is creating new assets for each update on the Opportunity is that aren't checking to see if this is the FIRST time that isWon = true. Add "and trigger.oldMap.get(o.Id).isWon = false" to the third line and that will take care of that.
2. This trigger is not bulk safe because you're doing a query inside the for loop. Move that outside the for loop and create a map<Id, OpportunityLineItem> so you can reference your OLI records
3. You're doing DML inside the for loop. Instead, update lists of SObjects outside the for loop and you're less likely to trip over governor limits.