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
Vaibhav SFDCVaibhav SFDC 

How Do we write Trigger on Custom object?

SandhyaSandhya (Salesforce Developers) 

Please refer below salesforce document which has an example code.

If this helps you, please mark it . as solved so that it will be available for others as a solution.

Best Regards,
Varun SinghVarun Singh

Setup --> Create --> Objects --> Click into the name of the object

Apex triggers are like stored procedures which execute when a particular event occurs. A trigger executes before and after an event occurs on record.

trigger triggerName on ObjectName (trigger_events) { Trigger_code_block }

Executing the Trigger
Following are the events on which we can fir the trigger −


Trigger Example 1
Suppose we received a business requirement that we need to create an Invoice Record when Customer's 'Customer Status' field changes to Active from Inactive. For this, we will create a trigger on APEX_Customer__c object by following these steps −

Step 1 − Go to sObject

Step 2 − Click on Customer

Step 3 − Click on 'New' button in the Trigger related list and add the trigger code as give below.
// Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
   List InvoiceList = new List();
   for (APEX_Customer__c objCustomer: {
      if (objCustomer.APEX_Customer_Status__c == 'Active') {
         APEX_Invoice__c objInvoice = new APEX_Invoice__c();
         objInvoice.APEX_Status__c = 'Pending';
   // DML to insert the Invoice List in SFDC
   insert InvoiceList;

Explanation − This is the context variable which stores the records currently in the trigger context, either being inserted or updated. In this case, this variable has Customer object's records which have been updated.
There are other context variables which are available in the context – trigger.old, trigger.newMap, trigger.OldMap.