Learn Salesforce Trigger in a Simple way-Part III

As we have discussed in our previous post about the basics of the trigger then write a trigger to update the list of contact in an Account based on the value given in a field.But that trigger is not written in the best way.

Previous question

Today we learn about the best ways to write a trigger.



Learn Salesforce Trigger in a Simple way-Part III

What do you think what was the problem in the previous post or in the previous code.??!!

The Problem is that the account which created the contact is the last account of the loop.Because the whole loop will run and when it reaches the last account it will go out and add the contacts.Let’s see it with the help of code:


trigger createContact on Account (after insert, after update){
    List<contact> contlist=new List<contact>();
    for(Account a:Trigger.new){
        integer i=0;
            if((trigger.isUpdate && a.No_of_Contact__c != Trigger.oldMap.get(a.id).No_of_Contact__c) || trigger.isInsert)
                    contact c=new contact();
                    c.LastName='Cont Of '+a.Name+'-'+i;
        insert contlist;


In this code, we create a list of Contact then inside the for loop we added the contact by fetching the number of contact from “Trigger.oldMap.get(a.id).No_of_Contact__c”. The contact will be added to the account until the while loop breaks the value of i.

Then in the last, we check if there is something on the Contact list “contlist”, if the number is greater than 0  then it will be inserted into the account.

You can understand the concept of trigger through our youtube video in which each detail is explained verbally as well as practically. To go to our Youtube page or video click below:




Note: For any query or question please do comment and write me.We’ll try our best to solve your queries.


A Salesforce Developer at AlmaMate Info Tech PVT LTD. An Aligarian and also your query solver in database field.This site mark the difference as Black or White to make you choose the best for you. Don't feel pressurized, feel confident..!!

Leave a reply:

Your email address will not be published.