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
bob4bob4 

Enforce Uniqueness on a field

I am trying to create a trigger that only allows user to enter unique values with in a field. I cannot make it unique at field level because of restrictions. Now consider if there are already existing records in a object with the field values as 1,2,3,4...10 , consider the field as unique__c. now if user inserts other record with value say 3, now the record which is already existing with value 3 should become 4, 4 should become 5 and.... can any one help me with the logic. It should happen after inser and after update. Thanks
Sonam_SFDCSonam_SFDC
Hi Bob, 

If I understand correctly, suppose you have 10,000+ records in your database, would you really want to updates each one, for instance, if the user enters 1, it will get all the records and try to update all..

if it is a number you want to be in continuation, why not use autonumber - this will be unique always and it will also be something not entered by the user such that uniqueness is maintained..



bob4bob4
Sonam, I cannot do that according to my requirement i need that particular field to be updated. It is never going to be more than 1000 records as they will be handled immediately.
Sonam_SFDCSonam_SFDC
No worries, try it this way(Pseudocode) -
1)Create an after insert, after update trigger on that object 
2)Run an SOQL to get all the records which have the value of the field higher than that of the field vaue being entered
3)Once you get that list, create a for loop and update the value of this field for each record inside the for loop
4)Make an update statement and update the list of records you've worked on in the for loop.


bob4bob4
Hi sonam I am stuck at the comparision as soql is not allowing me to compare fields with in query. Here is my code please help me with it. Thanks.

trigger priority on Book__c (After insert, before Update) {
  
List<book__c> oldValues=new List<book__c>();
List<book__c> newValues=new List<book__c>();
Book__c maxval =[select priority__c from book__c  order by priority__c desc limit 1];
for (Book__c oldprior : trigger.old)
{
  oldvalues.add(oldprior);
}
for(Book__c newprior : trigger.new)
{
   
}
   
}