Skip to content

Instantly share code, notes, and snippets.

@mailtoharshit
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mailtoharshit/e2ece54080e6ce12d195 to your computer and use it in GitHub Desktop.
Save mailtoharshit/e2ece54080e6ce12d195 to your computer and use it in GitHub Desktop.
Here goes my code
//Bug fix : Thanks mohit, I missed the serious bug, this should be after insert trigger, as we need caseId here and which is only available once a required is inserted or committed
trigger LazyEmployee on Case(after insert)
{
//In a standard Salesforce Scenario Case Owner is actually ownerID which ID field
// As per the requirement, I am assuming Owner as Text Field, basically a custom field
//Clearly Trigger needs to bulkified, I would have created bunch of Utilitiy Class to check for null values
//To handle Map values and set value , I mean repeted check, very easy to use and maintain (Good engineering)
//Make set of id to hold unique id, avoiding duplicates of case owners
Set<id> ownerIds = new Set<Id>();
//populate set with unique values,
for(Case c : Trigger.New)
ownerIds.add(c.Id);
//Make a map that hold cases matching Id in the set we just populated
//This map will hold all data we need, we can query map and avoid querying salesforce
Map<id, Case> userToIdMap = new Map<id, Case>([Select Id, Owner, Status From Case Where Id in : ownerIds])
//Make a list of cases needs to updaed
List<Case> caseList = new List<Case>();
//Now we have map, we can avoid SOQL from here and we are getting awesomer now
//Loop through each case coming in
for(Case c : Trigger.New)
{
//close only if status is not closed, get status from Map , yay we avoid SOQL here
//but check to see if Map is not empty
if(userToIdMap.isNotEmpty())
{
//Close only if status is anything but closed
if(userToIdMap(c.Id).status != 'Closed')
{
c.Status='Closed';
//Check if ownerID is David Liu Id since in sample this is text field so it's easy
// since requirement says close all cases and set owner as David regardless
if(userToIdMap(c.Id).Owner !='David Liu')
//set the Owner (if custom textfield, remember Id is not writeable Field)
c.Owner='David Liu';
//add only qualified values to list, this will keep list limited in size
caseList.add(c);
}
//User Try-Catch log the update, in case if exception occurs
try
{
//check if list is not empty or null
if(caseList.isNotEmpty() || caseList.Size()!=0 || caseList!=null)
update caseList;
}Catch(DMLException e)
{
System.Debug('Error Updating Records in LazyEmployee Trigger '+e.getMessage());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment