function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

DML Update error on Trigger issue

I have created a custom object that operates similiar to the Account Contact role object.


What is want the code below to do is to make sure that only one record can be marked as Primary at time.

I a user updates a record and marks it as Primary the trigger code will in turn find other records where Primary is equal to true and will change it to false.


I get the following error implement the trigger code as shown below

Developer script exception from 'test' : AccountContactRole_SetPrimary : AccountContactRole_SetPrimary: execution of BeforeUpdate caused by: System.SObjectException: DML statment cannot operate on or trigger.old Trigger. AccountContactRole_SetPrimary: line 17, column


trigger AccountContactRole_SetPrimary on Account_Contact_Role__c (after update) { // Validate if the Primary and the combination of the contact and the role is not duplicated for the relevant account List <Account_Contact_Role__c> acrList = new List<Account_Contact_Role__c>(); for (Account_Contact_Role__c acr: Trigger.New){ Id CurrentId = acr.Id; if (acr.Primary__c == true){ for (Account_Contact_Role__c acrP : [SELECT Id FROM Account_Contact_Role__c WHERE Id !=: acr.Id and Primary__c = true]){ acrP.Primary__c = false; acrList.add(acr); } } } if (!acrList.isEmpty()){ update acrList; } }





Is this going wrong in a bulk test?


In your loop, you are excluding the id of the object that is being processed by the for loop, but this will allow all other members of to appear.  You may want to change your soql to exclude all objects from the list. 


As the error log says, you can't use objects in for update. You need to newly create Account_Contact_Role__c objects and update.



Always ThinkinAlways Thinkin

The old Apex Dev guide has a Quoting Application that did exactly the IsPrimary one-and-only-one behavior you're describing. Surely it's coded better than anything I would suggest!


Quoting Application



Good Luck!


Luke C 


Thanks for helping with this request.


I can confirm that the following trigger now works


trigger AccountContactRole_SetPrimary on Account_Contact_Role__c (before insert, before update) { // Make sure that only one record can have a Primary field checked List <Account_Contact_Role__c> acrList = new List<Account_Contact_Role__c>(); for (Account_Contact_Role__c acr: Trigger.New){ if (acr.Primary__c == true){ for (Account_Contact_Role__c acrP : [SELECT Id, Primary__c FROM Account_Contact_Role__c WHERE Primary__c = true and Id != : acr.Id Limit 1]){ acrP.Primary__c = false; acrList.Add ( acrP); } } }