Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //A Utility class to process Stock Item records from the Stock Item Handler
- public with sharing class StockItemHandler {
- //Default Constructor
- public void StockItemHandler() {
- }
- //Check for duplicate stock items before insert and display an error to user if a duplicate is found
- public void OnBeforeInsert(List<Stock_Item__c> stockItems){
- //Create a set to hold new stock items being inserted
- Set<String> newStockSet = new Set<String>();
- //Create a set to hold stock items in the database (db)
- Set<String> dbStockSet = new Set<String>();
- //Create an error variable and assign value
- String errorMsg = 'This item name is already entered in the system. Please enter a unique item name.';
- for (Stock_Item__c s : stockItems) // Loop through all of the records for insert
- newStockSet.add(s.Item_Name__c); // Add each item name to the newStockSet
- for (Stock_Item__c dbStock : [SELECT Item_Name__c //Loop through stock items in the database
- FROM Stock_Item__c
- WHERE Item_Name__c IN :newStockSet]){
- dbStockSet.add(dbStock.Item_Name__c.toUpperCase()); // Add values to the dbStockSet that match an item being inserted
- }
- for (Stock_Item__c s : stockItems){ // Loop through all of the records for insert
- if(dbStockSet.contains(s.Item_Name__c.toUpperCase())) // If the item name is already in the dbStockSet, we have a duplicate item
- s.addError(errorMsg); // So, add an error to the record
- }
- }
- //Check stock on hand before a stock item can be deleted
- public void OnBeforeDelete(List<Stock_Item__c> stockItems){
- // Create a list to hold new cases for insertion.
- List<Case> casesToCreate = new List<Case>();
- for(Stock_Item__c s : stockItems){ // Loop through all of the records being deleted
- if(s.Stock_on_Hand__c <> 0){ // If the stock on hand is greater than zero, we need to alert someone
- Case newCase = new Case(); // So, create a new case for the deleted item
- newCase.Status = 'New';
- newCase.Subject = 'Item with Stock on Hand DELETED'; // Set the field values for the new case record
- newCase.Description = 'Item Name: ' + s.Item_Name__c + '; Stock Item Id: ' + s.Id + '; Number on Hand: ' + s.Stock_on_Hand__c;
- casesToCreate.add(newCase); // Add new case to the casesToCreate list
- }
- }
- insert casesToCreate; //DML call to insert list of new case records
- }
- }
Add Comment
Please, Sign In to add comment