+ Start a Discussion
Mike_EMike_E 

Read Only Error Message on OpportunityLine Trigger

I am trying to update a custom field on an OpportunityLine using an APEX trigger.  I am receiving an error message stating that the record is Read Only.  The sharing settings on the Opportunity are Public Read/Write.  Don't quite understand why the record is Read Only.  Any ideas?  The code in the Trigger follows.

 

trigger AddAssetTagOnOpportunityProduct on OpportunityLineItem (after insert) {

    if(Trigger.isInsert ){ 
    
        for(OpportunityLineItem lineItem : Trigger.new){
        
            String wppItemNumber = lineItem.WPP_Item_Number__c;
            
            System.debug('WPP Item Number : ' + wppItemNumber);
            
            sm1e__smEquipment__c maintenanceAsset = [SELECT Id, Name FROM sm1e__smEquipment__c WHERE
                                                     sm1e__External_Asset_ID__c = :wppItemNumber];
                                                     
            System.debug('Asset Tag : ' + maintenanceAsset.Name);
            
            lineItem.Asset_Tag__c =  maintenanceAsset.Id;
            
            update lineItem;
       
        }
    }
Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

The records in after triggers are read only, as they have already been written to the database.  Can you turn this into a before trigger?

All Answers

bob_buzzardbob_buzzard

The records in after triggers are read only, as they have already been written to the database.  Can you turn this into a before trigger?

This was selected as the best answer
shruthishruthi

Try this!

 

trigger AddAssetTagOnOpportunityProduct on OpportunityLineItem (before insert) {
    if(Trigger.isInsert ){    
        for(OpportunityLineItem lineItem : Trigger.new){       
            String wppItemNumber = lineItem.WPP_Item_Number__c;           
            System.debug('WPP Item Number : ' + wppItemNumber);           
            sm1e__smEquipment__c maintenanceAsset = [SELECT Id, Name FROM sm1e__smEquipment__c WHERE
                                                     sm1e__External_Asset_ID__c = :wppItemNumber];                                                    
            System.debug('Asset Tag : ' + maintenanceAsset.Name);           
            lineItem.Asset_Tag__c =  maintenanceAsset.Id;                  
        }
    }