Created
December 15, 2018 17:09
-
-
Save cynthiabellmcgillis/96adb55a10f11cb2c6e41bb0f70654a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if(Trigger.isInsert && Trigger.isBefore) { | |
//call the class in your handler for before insert | |
// StockItemHandler.onBeforeInsert(Trigger.new); | |
//We create a set to accept all the incoming records. Sets don't allow duplicates, | |
//so this is good for bulk uploads--imagine somemone uploading a CSV of 1000 pot holders. | |
//We only want the record once! | |
Set<String> stockItemSet = new Set<String>(); | |
//Starting a for loop to inspect the records coming into the trigger. | |
for(Stock_Item__c si : Trigger.new){ | |
//Adding the Stock Item Name to the set. This is what we are deduping on. | |
stockItemSet.add(si.Item_Name__c); | |
} | |
//Created a new list where we are looking at all our existing stock items and only grabbing those | |
//where the Item Name matches the Item Name in our above set. | |
List<Stock_Item__c> stockItemList = New List<Stock_Item__c>([SELECT Id, Item_Name__c | |
FROM Stock_Item__c | |
WHERE Item_Name__c | |
in: stockItemSet]); | |
//So now we're creating a Map. In theory, we could have used another Set since | |
//we are comparing on one value but a Map allows you to access all | |
//other related information on the record which could be useful. | |
// | |
//Key goes first (in this case, Stock Item Name) then value (Stock Item record). | |
//Remember, you can have ONE unique key, but many values. | |
Map<String, Stock_Item__c> stockItemMap = New Map<String, Stock_Item__c>(); | |
//Okay, entering another loop where we are talking about all the items that were in our list above. | |
//We are going to iterate over all the records in the list. | |
for(Stock_Item__c si: stockItemList){ | |
//Using the .put method, we are putting the Stock Item Name and Stock Item record into our set. | |
//When we exit the loop, we'll have a bunch of Stock Items and their names linked together | |
//(remember: key/value pair!) | |
stockItemMap.put(si.Item_Name__c, si); | |
} | |
//Another loop! Notice we are back to Trigger.new this is because we need to assess all the records | |
//that have been created in Trigger | |
for(Stock_Item__c si : Trigger.new) { | |
if(stockItemMap.containsKey(si.Item_Name__c)) | |
//si.Item_Name__c = 'DUPLICATE ' + si.Item_Name__c; | |
si.addError('Looks like you\'re trying to add a dupe record!'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment