Skip to content

Instantly share code, notes, and snippets.

@pritaunk
Last active October 22, 2017 19:12
Show Gist options
  • Save pritaunk/c02aebeedef05e6d451c55e59779cd8a to your computer and use it in GitHub Desktop.
Save pritaunk/c02aebeedef05e6d451c55e59779cd8a to your computer and use it in GitHub Desktop.
Requirement 2 final project (draft) line 41 onwards
trigger StockItemTrigger on Stock_Item__c (before insert, after delete) {
//*DATA SET UP*created sample records using DML via the execute annonymous window
//stock_item__c stock = new stock_item__c ();
//stock.Item_Name__c = 'chocolate';
//stock.description__c = 'i love chocolate';
//stock.minimum_stock_level__c = 10;
//stock.stock_on_hand__c = 10;
//stock.list_price__c = 50;
//insert stock;
//*REQUIREMENT 1* Before a Stock Item can be created, check that there is not already
// a stock item record with a matching name.
//the below creates the new stockitems in a set that
//doesn't allow for duplicates. Trigger.new to ensure all new records created
//for this object get added to this Set
set <string> stockitems = new set <string> ();
for (stock_item__c stock : trigger.new) {
stockitems.add(stock.Item_Name__c);
}
//here we are checking for duplicates in the existing records to ensure
//we don't enter new stock items with the same name
//SOQL query to get a list of existing stock items from the org calling for the stock name
list <stock_item__c> stocklist = new list <stock_item__c> (
[select id, Item_Name__c from stock_item__c where Item_Name__c in : stockitems]);
for(stock_item__c newstock : trigger.new) {
//checking if the list has a duplicate item then add the below words to the new stock item name
if(stocklist.size() > 0)
newstock.adderror('duplicate item' + newstock.Item_Name__c);
}
//*REQUIREMENT 2*Before a Stock Item is deleted, make sure that the stock on
//hand is at 0. If it is not, Create a case so that someone is alerted.
//checking if the record is deleted
if(trigger.isdelete) {
for (stock_item__c stockdelete : trigger.old)
{
if (stockdelete.Stock_on_Hand__c <> 0) //check if stock on hand is not 0 then create a case to alert
{
case c = new case ();
c.subject = 'stock item being deleted';
c.OwnerId = '0050Y000001lnHx';
c.Description= 'Item_Name__c , stock_on_hand__c';
c.Status = 'new';
c.Origin = 'email';
//not sure how to get the record id for the
//record that's being deleted
insert c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment