Reading list Switch to dark mode

    Write a Basic trigger in apex

    Updated 16 July 2021

    Trigger, to any mind trained in the art of writing SQL or PL-SQL, this word will always ring a bell. As the name suggest it is something which will be fired when an event occurs. In simple words we can say that trigger is just a piece of code which works if anything happens which we have programmed the trigger for, like insert, delete, update, etc. Likewise we have an option to write trigger in APEX too. And that’s what we are going to see today. How to write a basic trigger in APEX on insert and update operation.

    Types Of triggers in APEX

    APEX provides two types of trigger based on the time of execution:

    • Before Trigger: These triggers run before the records are inserted, updated, deleted or undeleted in any object. Simply, the trigger runs before the record is provided an id.
    • After Trigger: These trigger run right after the records are inserted, updated, deleted or undeleted in any object, and before the commit is called.

    Triggers can also be categorized on the basis of the event for which they occur like insert trigger happens before of after the insert operation, or update trigger occur right after or before update. Upsert operation calls both insert and update triggers. For merge operations the winning record will call before update trigger and the other record will call before and after delete trigger.

    APEX Trigger example

    Now that we have enough information about triggers, let’s move on to writing a trigger. For this example we will write a trigger to add a ‘code-‘ at the beginning of every newly created product2 record’s product code, if it’s not empty.

    To write the trigger on product2 object go to Setup | Customize | Products | Triggers: then click on new button

    Searching for an experienced
    Salesforce Company ?
    Find out More
    trigger changecode on Product2 (before insert) {
    
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         **/
    
        list<product2> productlist = trigger.new;
        for(product2 pro:productlist){
            if(pro.productcode != null && pro.productcode != '')
                pro.productcode = 'code-'+pro.productcode;
        }
    }

    In this code the first line defines the trigger, like the prototype of a function. ‘trigger‘ keyword tells that this is a trigger, changecode is the name of the trigger, and we are writing this trigger on product2. The before insert tells that this trigger will run before insert of a record. We can add more events by separating them with comma.

    The trigger.new provides the records that are about to be inserted, or updated. Likewise trigger.old returns the value of records before update or delete. Rest is simple code to update the values of the new records. You’ll see on thing in this code, that an update command or insert command is missing. This is because the trigger is already a part of the DML process and hence we do not need to call another DML command, or else there are chances of having and trigger recursion. So it is always a good habit to avoid DML for the same object in a trigger.

    Next up is after trigger, for which we will write a trigger to add a standard price to every new or updated product which does not already have a standard price.

    trigger addprice on Product2 (after insert, after update) {
    
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         **/
    
        list<product2> prolist = trigger.new;
        pricebook2 pb= [select id from pricebook2 where isstandard = true];
        list<pricebookentry> pbe= new list();
        for(product2 pro: prolist){
            try{
                pricebookentry pbe = [select id from pricebookentry where product2id=:pro.id and pricebook2id=:pb.id];
            }catch(exception e){
                pbe.add(new pricebookentry(product2id=pro.id,pricebook2id=pb.id,unitprice=100));
            }
        }
        insert pbe;
    }

    The only difference in the way of writing this trigger is the after insert in the place of before insert.

    Output

    Once you have created the triggers, you can see the changes by creating a new product normally. Go to the product tab, click on new and add details.

    As you can see that the product code was updated and a standard price was added too by the triggers that we created

    SUPPORT

    That’s all for how to write a basic trigger, for any further queries feel free to add a ticket at:

    https://webkul.uvdesk.com/en/customer/create-ticket/

    Or let us know your views on how to make this code better, in comments section below.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content