+ Start a Discussion
LaurenP6777LaurenP6777 

Simple Trigger Problems when trying to update OwnerId

I have a problem with a very simple trigger. The error I am getting is:

 

 UpdateownertoCovanceContact: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.UpdateownertoCovanceContact: line 7, column 1

 

When i change to "before update", I get this error:

 

Apex trigger UpdateownertoCovanceContact caused an unexpected exception, contact your administrator: UpdateownertoCovanceContact: data changed by trigger for field Owner ID: owner cannot be blank

 

All I am trying to do is have the Owner be replaced with the Covance Contact, (which is just a lookup field to the user record) upon save. This is such a simple trigger but i just can't figure it out. Thanks!

 

Here is the code:

 

trigger UpdateownertoCovanceContact on Contact_Team__c (after insert, after update) {
for (Contact_Team__c ct: trigger.new) {

if (ct.Rship_to_Covance_Contact__c!='neutral') {


ct.Ownerid= ct.Covance_Contact__r.Id ;
}
}
}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sivaextsivaext

Hi

 

use before insert and before update only  

 

The error "Ownerid is blank " because the field is empty in contact_Team__c

 

change code below 

 

trigger UpdateownertoCovanceContact on Contact_Team__c (before insert, before update) {
for (Contact_Team__c ct: trigger.new) {

if (ct.Rship_to_Covance_Contact__c!='neutral') {

  if(ct.Covance_Contact__c!=null) {

  ct.Ownerid= ct.Covance_Contact__c ;

}

}
}
}

All Answers

sfdcfoxsfdcfox

I'd expect that error. You can't use relationships without a query. Try this instead:

 

trigger UpdateownertoCovanceContact on Contact_Team__c (after insert, after update) {
	for (Contact_Team__c ct: trigger.new) {
		if (ct.Rship_to_Covance_Contact__c!='neutral') {
			ct.Ownerid= ct.Covance_Contact__c;	// This is an ID.
		}
	}
}

 

sivaextsivaext

Hi

 

use before insert and before update only  

 

The error "Ownerid is blank " because the field is empty in contact_Team__c

 

change code below 

 

trigger UpdateownertoCovanceContact on Contact_Team__c (before insert, before update) {
for (Contact_Team__c ct: trigger.new) {

if (ct.Rship_to_Covance_Contact__c!='neutral') {

  if(ct.Covance_Contact__c!=null) {

  ct.Ownerid= ct.Covance_Contact__c ;

}

}
}
}

This was selected as the best answer