+ Start a Discussion
PrazziePrazzie 

System.FinalException: Record is read-only

Hi I have wrote the following trigger and the exception is throwing in the assignment of values:

 

 

CampaignProductPopulationTrigger on Campaign (after delete, after insert, after update) {
if(Trigger.isAfter){

if(Trigger.isUpdate){
Set<Id> campaignIds = new Set<Id>();
Set<Id> productIds = new Set<Id>();
Set<String> productSet = new Set<String>();
String productNames =

null;
for(Campaign campaign:Trigger.new){
campaignIds.add(campaign.id);

}

for(Campaign_Product__c campro:[Select Product__r.id from Campaign_Product__c where Campaign__r.id IN:campaignIds])
productIds.add(campro.Product__r.id);

for(Product2 proVal:[Select Name from Product2 where id IN:productIds])
productSet.add(proVal.

Name);
for(String setVal:productSet)
productNames+=setVal+

', ';
productNames=productNames.substring(0,productNames.length()-2);

for(Campaign campaign:Trigger.new)
campaign.Campaign_Products__c = productNames;//ERROR LINE

}


}

}

 Please tell me how to get rid of this error

 

Imran MohammedImran Mohammed

Hi,

 

Can you check if the field security is Read only for Campaign_Products field for the profile you are running with?

 

I want you to make the following change as well,

As CampaignIds is a Set that can hole more than one record, you should use the below syntax for handling that.

 

 

for(Campaign_Product__c[] campro:[Select Product__r.id from Campaign_Product__c where Campaign__r.id IN:campaignIds])
{
 for(Campaign_Product__c c: campro)
 productIds.add(c.Product__r.id);
}
for(Product2[] proVal:[Select Name from Product2 where id IN:productIds])
{
 for(Product2 p: proVal)
 productSet.add(proVal.Name);
}

 

EalesieEalesie

Hi

 

You cannot update fields on triggered records when you are in an after trigger - move this into a before trigger, and ensure you are not running any DML statements within for-loops as the code will break with bulk updates.

 

Hope this helps

 

Ealesie