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
DaveAdams2DaveAdams2 

Preventing a dupe by concatenating fields on a custom object

Hi All,

 

I have a custom object called "Account_Activity_Plans" with which I would like to prevent duplicate records when a user creates a new record or updates an existing record. The way i had planned to do this was make a trigger that populates a field called UniqueKey (set as unique in the field properties) before insert and before update with a concatenation of several fields in the record so that the record will not save if the concatenation of the various values already exists on another record.

 

The fields i would like to concatenate are called:-

AcccountID(a master detail relationship exists with the account
Enterprise (picklist)
Activity (picklist)
Month (picklist)
The combination of these 4 fields defines a unique record.
Could you please let me know how i would approach the code to do this, or if there is a better way to achive what i want to do.
Dave
Ispita_NavatarIspita_Navatar

Hi Dave,

The best way of achieving your requirement is through a trigger as you have rightly indicated in your post,but you need to think to store the contatenated value in a formula field and in the trigger to need to check if there exists any data which has (F1+F2+F3+F4 ) {concatenation of 4 fields} in any instance of the custom object , if it does then we raise an error.

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.

DaveAdams2DaveAdams2

Hi Ispita,

 

thanks so much for your reply. I have now made the custom formula field  that concatenates the other 4 fields and called it Unique_Key__c . I am very new to triggers and unsure how to write the trigger you have suggest, are you able to suggest the code i should use or point me to a similar scenario sample code that already exists?

 

The names of everything is per below:-

 

Custom object name - AccountActivityPlans__c

Field to check if unique before inserting or saving a record - Unique_Key__c 

Error message to display - "An record already exists with the same details, so you cannot save this record"

 

 

Ispita_NavatarIspita_Navatar

Hope this snippet will help you.

Trigger UniqueKeyCheck on AccountActivityPlans__c (before insert, before update)

{

string tmpKey= trigger.new[0].field1  + trigger.new[0].field2 + trigger.new[0].field3 +trigger.new[0].field4

AccountActivityPlans__c arrObj[] =['Selct id, Unique_Key__c from AccountActivityPlans__c where Unique_Key__c =:tmpKey]

if(arrObj.size>0)

{

   trigger.new[0].Unique_Key__c.addError('An record already exists with the same details, so you cannot save this record');

}
}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.