[SalesForce] Trigger to prevent duplication of records in Salesforce

I need to see an apex code of trigger, on say object 'Account' to prevent any new records from saving. Existing records do have duplicates but we cannot clean/ remove the data, as the requirement has come midway.

The unique feature applies to 2 fields say A(picklist) and B(text) of object Account, (concatenated) where A is a picklist, having values 1,2,3,4 where we need only values (TEXT) 1,2,3 of A to be unique alongside (concatenated with) text field B, and not the value 4.

Again, the requirement is to prevent any new records from saving which match any of the existing records. Duplicates within the existing records can be ignored.

Thanks in advance.

Best Answer

You can potentially do this via config. Create a text field for a composite primary key and mark this as External Id, Unique.

Create a workflow that concatenates the two values and write it to this field on everytime a record is created or updated.

This should automatically give you an error owing to the uniqueness constraint on the field.

Related Topic