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
AngiB.ax1285AngiB.ax1285 

Am I asking for Trouble? – Trigger to Set Field Values ONLY when record number 2 added

We have a managed application and we are expanding a custom object that used to allow ONLY ONE RECORD to allow multiple records.

 

So that means when one of our customers gets the soon to be new version of the application I can GUARANTEE that they either have 0 or 1 record in the AcctSol__Configuration__c object.

 

We are also adding a lookup relationship to AcctSol__Fixed_Asset__c to AcctSol__Configuration__c and I that will be mandatory on all records.

 

I am nothing if not lazy so I was looking for the easiest way to get that lookup relationship populated and I came up with the following trigger on AcctSol__Configuration__c:

 

trigger MoreThanOneConfig on AcctSol__Configuration__c (Before Insert) {
 
List<AcctSol__Configuration__c> lstCF = [SELECT Id, Name FROM AcctSol__Configuration__c];
List<AcctSol__Fixed_Asset__c> lstFA = [SELECT Id, Name, AcctSol__Configuration__c FROM AcctSol__Fixed_Asset__c where AcctSol__Configuration__c=null];
List<AcctSol__Fixed_Asset__c> AssetsToUpdate = new List<AcctSol__Fixed_Asset__c>();
 
 if(Trigger.isInsert)
 {
   for(AcctSol__Configuration__c objFA : Trigger.new)
   {
         if (lstCF.size() == 1)
         {
             for(AcctSol__Fixed_Asset__c FA: lstFA)
             {
                FA.AcctSol__Configuration__c = lstCF.get(0).Id;
                AssetsToUpdate.add(FA);
             }
             update AssetsToUpdate;
         }
   }
 }
}



It appears to work.

So when you create the SECOND AcctSol__Configuration__c record this will set all EXISTING AcctSol__Fixed_Asset__c.Configuration__c lookups to the previously existing AcctSol__Configuration__c value.

On the 1st, 3rd, 4th etc records it will do nothing.

 

From a business logic point of view this is perfect.

 

My question is… is there anything wrong with this approach from a technical standpoint?