Set Default Assignment Rule To Case and Lead Object

This is very easy using trigger to set default assignment rule to case and lead object. First you need to create an assignment rule on Case and Lead object.
Let’s create an assignment rule
Go-to Case Assignment Rules–> click on New button–> Enter Rule Name “Assignment Rule 2” –> make Active by checkbox and click Save button.
Set Default Assignment Rule To Case and Lead Object

There will be only one assignment rule active for an object. In simple way you can said that other assignment rule become inactive if your new created assignment rule become active.

Now let’s create an apex trigger to set assignment rule

trigger setAssignmentRuleTrigger on Case (after insert)
{   
    if(trigger.isInsert){
        List arRuleList = new List();
        List caseList = new List();
        
        arRuleList = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
        
        if(!arRuleList.isEmpty())
        {
            for(Case caseObj : [Select Id from Case where Id in :Trigger.newMap.keySet()])
            {
                Database.DMLOptions dmoObj = new Database.DMLOptions();
                dmoObj.assignmentRuleHeader.assignmentRuleId= arRuleList[0].id;                    
                caseObj.setOptions(dmoObj);
                caseList.add(caseObj);
            }
            
            Update caseList;   
        }
    }
}

In same way you can create a trigger on Lead object to set default assignment rule to new created Lead.

What is apex trigger in salesforce?

Apex trigger is block of code wrapped by {} and fire whenever object(table) records are (insert,update and delete) all DML Operation like.

Suppose you want to set Title field of Contact object on the basis of “Gender__c” and “Marital_Status__c” custom field. There are no standard Gender and Marital Status fields for Contact Object in Salesforce. So please add both custom fields Gender and Marital Status in Contact Object if you want to run following apex trigger.

If you want to create custom fields in contact object

Step-1: goto to top-right of screen and click setup link and type Contact in search box after that click highlighted fields link.

Step-2:  Goto Contact Custom Fields & Relationships section and click on new button to add custom field. in next screen select a data type Picklist not multi select and click next button.

Step-3: Filled all required fieldsFor option value check “Enter values, with each value separated by a new line” add two option Male and Female separated by new line.

Step-4: Click Next button.

Step-5: Click Save button.

Marital Status custom field you can create in same way.

Now Let’s create trigger on Contact Object to set Title fields of contact.
Apex TriggerApex Trigger

trigger SetTitleTrigger on Contact (before insert,After Update) {
    List conatctList = new List();    
    if(Trigger.isInsert){
        for(Contact cont : Trigger.New){
            if(String.isNotBlank(cont.Title)){
                if(String.isNotBlank(cont.Gender__c) && (cont.Gender__c.toLowerCase()=='female'))
                {
                    if(String.isNotBlank(cont.Marital_Status__c) && (cont.Marital_Status__c.toLowerCase()=='single'))
                    {
                        cont.Title = 'Ms.';
                    }
                    else
                    {
                        cont.Title = 'Mrs.';
                    }
                }
                else
                {
                     cont.Title = 'Mr.';   
                }
            }
        }
    }
}

Apex Trigger Context Variables

List of context variables are available in apex trigger. Some of variables are very useful i.e., isInsert, isUpdate, isDelete, isBefore and isAfter. I suggest that you should create only one trigger for each object if required. Example

trigger SetTitleTrigger on Contact(before insert,before update,before delete,after update, after delete) {
    List conatctList = new List();    
    if(Trigger.isInsert){
	// execute (in both case before and after) if insert a contact
     }
     if(Trigger.isInsert && Trigger.isBefore){
	// execute before insert a contact
	// you can set some field value before inserting record
     }
     if(Trigger.isInsert && Trigger.isAfter){
	// execute after insert a contact
	//Here you can get 
     }
     ...
     ..
     .
}

In same way you can check isUpdate and isDelete along with isBefore and isAfter context variables.

Difference Trigger.new and Trigger.newMap

Trigger.new is a apex context variable that return list of sObject while Trigger.newMap return Map of Id and sObject.

List objList = Trigger.new;
Map<Id,sObject> objList = Trigger.newMap;

There are also two variables Trigger.old and Trigger.OldMap. These two variable return list and map of sObject if record is update or delete only.

Prevent Recursive Trigger in Salesforce Apex

What is recursive trigger?

You have learned about recursion process of loop. Same logic here means a trigger fire by itself. In detail you say that recursive trigger fire by some code of block which is written in same apex trigger or INSERT or UPDATE.

public Class AvoidRecursive
{
    private static boolean isRun = true;
    public static boolean runOnce()
    {
        if(isRun)
        {
            isRun=false;
            return true;
        }
        else
        {
           return isRun;
        }
    }
}

Use above runOnce() static method in trigger before insert/update statement like

if(AvoidRecursive.runOnce())
{
     // Database insert/update/delete statement
}