function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Carol MatsumuraCarol Matsumura 

Trigger to update one field on a case coming from web-to-case

I would like to create a Trigger for new cases being created by web-to-case

My goal is to update the County__c custom field on cases
Only when case RecordTypeName = 'BLNC' and CaseOrigin = 'Web'
 
Should I use a before or after insert for this?
Nayana KNayana K
Before insert
Carol MatsumuraCarol Matsumura
Thanks Nayana!  Could you explain the reason for using before insert? Also, could you outline how to structure the logic. I have developer experience but this the first trigger that I am writing on my own.
Nayana KNayana K

    When an object's record is being inserted, if we have to populate some field-values based on some logic on record ITSELF, then we usually prefer before insert. 
    Let's say, you have chosen after insert instead of before insert, then it is equal to ==> Data is already committed to Database + you are trying to populate values on the same record by updating the record based on the logic (You can only populate its values after insert by updating the record)
    ==> this causes unnecessary DML i.e, insert + unnessary update.
    IF you chose before insert in this scenario => Data is about to be commited + populate necessary values on fields based on desired logic(here you can directly populate values) => Only once DML will happen i.e, insert
Nayana KNayana K
public class CaseTriggerHandler
{
	public void onBeforeInsert(List<Case> lstNewCase)
	{
		Id idRecType =  Schema.SObjectType.Case.getRecordTypeInfosByName().get('BLNC').getRecordTypeId();
		for(Case objCase : lstNewCase)
		{
			if(idRecType == objCase.RecordypeId && objCase.CaseOrigin == 'Web')
			{
				/* Here your logic goes and at the end you will populate objCase.County__c = SOMEVALUE  */
			}
		}
	}
}
 
trigger CaseTrigger on Case(before insert) 
{
	CaseTriggerHandler objHandler = new CaseTriggerHandler();
	/* below condition check is unnecessary but if you add after insert, aftre update, after delete, before update or 
	any other event on Case at later point of time, then it is going to differentiate the context that it should fire on before insert only.
	*/
	if(Trigger.isBefore && Trigger.isInsert)
	{
		objHandler.onBeforeInsert(Trigger.New);
	}
}

Please let me know the requirement, I will try my best to make you understand by code comments