Skip to content

Instantly share code, notes, and snippets.

@niavesper
Created March 30, 2021 00:32
Show Gist options
  • Save niavesper/512182d04aa734d03d71ede260aac62c to your computer and use it in GitHub Desktop.
Save niavesper/512182d04aa734d03d71ede260aac62c to your computer and use it in GitHub Desktop.
Recipe Trigger and Handler
public with sharing class RecipeHandler {
public static void checkDraft(List<Recipe__c> draftRecipes) {
for (Recipe__c r : draftRecipes){
if (r.Name == null || r.Active_Time__c == null || r.Description__c == null || r.Active_Time_Units__c == null || r.Servings__c == null){
r.Draft__c = true;
}
}
}
public static void rateComplexity(List<Recipe__c> ratedRecipes) {
List <Recipe__c> updatedComplexityRecipes = new List <Recipe__c>();
for (Recipe__c r : ratedRecipes){
switch on HelperFunctions.rateRecipeComplexity (r){
when 1 {
r.Complexity__c = 'Simple';
}
when 2 {
r.Complexity__c = 'Moderate';
}
when 3 {
r.Complexity__c = 'Difficult';
}
}
updatedComplexityRecipes.add(r);
}
}
public static void createTasks(List<Recipe__c> taskRecipes) {
List <Task> newTasks = new List<Task>();
for (Cookbook__c c : [SELECT Id, OwnerId FROM Cookbook__c
WHERE ID IN (SELECT Cookbook__c FROM Recipe_Usage__c
WHERE Recipe__r.Draft__c = false AND Recipe__r.Id IN : taskRecipes)]){
Task t = new Task();
t.WhatId = c.Id;
t.OwnerId = c.OwnerId;
t.ActivityDate = Date.Today().addDays(7);
t.Subject = 'Review recipe';
t.Status = 'Not Started';
newTasks.add(t);
}
insert newTasks;
}
}
trigger RecipeTrigger on Recipe__c (before insert, after insert, before update, after update) {
if (trigger.isBefore && ( trigger.isInsert || trigger.isUpdate )){
RecipeHandler.checkDraft(trigger.new);
RecipeHandler.rateComplexity(trigger.new);
}
if(trigger.isAfter && ( trigger.isInsert ||trigger.isUpdate )){
RecipeHandler.createTasks(trigger.new);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment