+ Start a Discussion
ABakABak 

Field is not writeable

I have a Custom Object called KeyEvents. On key events there is a lookup field called Account that has a Master Detail relationship with the Account Object.

I can create a new Key Event and set the Account__c field on creation . But when I want to update the Account__c field on the key event through a trigger , I get an error message saying field is not writeable.

Any Idea whats going on. Heres the code

 

 

trigger UpdateKeyEventOnContactUpdate on Contact (after update) 
{
    For(Contact contact : Trigger.new)
    {
        if(Trigger.isUpdate)
        {
           if(contact.AccountId != Trigger.oldMap.get(contact.Id).AccountId)
           {	
	           Key_Event__c[] keyEvents = [Select k.Contact__c,k.Account__c, k.Id from Key_Event__c k Where k.Contact__c =: contact.Id ];
	           
	           For(Key_Event__c keyEvent : keyEvents)
	           {
	                keyEvent.Account__c = contact.AccountId;
	                update keyEvent;
	           }
           }
       }
       
    }
}

 

 

I am getting the following error:

Error:Apex trigger UpdateKeyEventOnContactUpdate caused an unexpected exception, contact your administrator: UpdateKeyEventOnContactUpdate: execution of AfterUpdate caused by: System.SObjectException: Field is not writeable: Key_Event__c.Account__c: Trigger.UpdateKeyEventOnContactUpdate: line 16, column 19

GuyClairboisGuyClairbois

Hi,

the reference to the master object cannot be changed once it has been set. This is how salesforce currently works.

 

Depending on the goal you are trying to accomplish (why do you want to change the value?) there might be other ways to do this.

 

There are also numerous suggestions on the Idea Exchange to enable changing the reference to master object on a child object. So you might want to vote on those as well.

 

Rgrds,

Guy