Browsing "Older Posts"

Browsing Category "Salesforce Development Real-time Interview Questions"
  • Salesforce Apex Map & Map methods with Examples

    salesforcepoint Wednesday, 8 July 2020
    Salesforce Apex Map, Map methods with Examples
    Map is one of the collection type in salesforce apex. In this post we are going to see what are the map methods with some basic examples. First of all Map is a key and value pair i.e each and every value is associates with key. Here key is unique, that means if we put one key,value pair into Map, we should not add same key one more time. If key is already exist in map and once again you are trying to add key with different value then old value override with new value.

    Salesforce Apex Map Syntax:

    Map<dataType, dataType> variabeName ;

    If we don't initialize map and 'trying to put new set of key, value' Or trying to use any map methods on that variable, you will end up with null pointer exception. So we need to initialize map whenever we create map variable.

    Map<dataType, dataType> variabeName = new Map<dataType, dataType>();

    eg: Map<String, String> countryWithCapitalMap =  new Map<String, String>();

    Important Apex Map Methods:

    put( ): By using this method we can new set of key, value pair into map.
    example: countryWithCapitalMap.put('India', 'Delhi'); //here India is key & Delhi is corresponding value for key 'India'.

    containsKey(key): By using this method we can check whether key exist or not in Map. It will return true if key is exist in apex map.
    example: countryWithCapitalMap.containsKey('India') //true

    get(Key): It returns value of corresponding key.
    example:  countryWithCapitalMap.get('India') //reurns 'Delhi'

    isEmpty(): It returns true if Map does not contain any key, value pair.
    example:  countryWithCapitalMap.isEmpty() //false

    size():  It returns number of key, value pairs available in Map.
    example: countryWithCapitalMap.size() // 1

    keySet(): It returns SET of key's available in the map.
    example: countryWithCapitalMap.keySet() //{India}

    values(): It returns LIST of values available in map.
    example: countryWithCapitalMap.values() //{Delhi}

    Task: Create a map to store country as Key and corresponding countries as values.

    Country (Key)
    'United States'
    'India'
    States (Value)
    'California',
    'Colorado',
     'Texas' 
    'Andhra Prdesh',
    'Telangana',
    'Karnataka'

    One country can have multiple states so that we should create Map value as List<string>

    Map<String, List<String>> countryWithStatesMap = new Map<String, List<String>>();

    countryWithStatesMap.put('United States', new List<String>{'California','Colorado','Texas'});
    countryWithStatesMap.put('India', new List<String>{'Andhra Prdesh','Telangana','Karnataka'});

    system.debug('Get countries from countryWithStatesMap ===>'+countryWithStatesMap.keyset());
    // o/p: {India, United States}
    system.debug('Get States of India ===>'+countryWithStatesMap.get('India'));
    // o/p: (Andhra Prdesh, Telangana, Karnataka)
    system.debug('Is Srilanka there in Map ===>'+countryWithStatesMap.containsKey('Srilanka')); 
    // o/p: false
  • How To Compare Old Values And New Values In Salesforce Triggers

    salesforcepoint Monday, 2 December 2019

    How To Compare Old Values And New Values In Salesforce Triggers (How to check whether record values are changed or not in Apex Trigger)


    We know that salesforce Before update and After Update triggers fired/invoked based on Update DML event occurs, irrespective of any field value updated on record. But update triggers should not get invoked every time when record is updated. These trigger's should fire when corresponding field values got changed on record.

    If we want to know whether respective field value changed or not, we need to use trigger.new and trigger.oldMap context variables. As we know that trigger.New contains list of records which will have updated field values and trigger.OldMap contains map of records which will have old values. Lets take basic example: If Phone field value on Account got changed, then update Description field like "Phone number got updated from old Phone Number to New Number. Here the logic should not trigger every time, only gets triggered when only phone field value got updated.



    Trigger Helper Class

     public class Account_Helper {  
      public static void checkPhoneValueUpdated(List<account> newList, Map<Id,Account> oldMap) {  
        for(Account accountRecord: newList){  
        if(accountRecord.phone != oldMap.get(accountRecord.Id).phone){  
          accountRecord.description = 'Phone number got updated from'+oldMap.get(accountRecord.Id).phone+' to '+accountRecord.phone;  
         }  
        }  
      }  
     }  
    
    Trigger:
     Trigger AccountTrigger on Account(Before update){  
       if(trigger.isBefore &amp;&amp; trigger.isUpdate){  
         Account_Helper.checkPhoneValueUpdated(trigger.new, trigger.oldMap);  
       }  
     }  
    

  • When To Use Before Triggers & After Triggers in Salesforce

    salesforcepoint Wednesday, 22 February 2017
    Difference Between Before Trigger and After Trigger & When Should we use Before & After Triggers:

    Before Triggers: Before triggers are used to update or validate record values before they’re saved to the database.

    Uses:

    1. When we need to write validation on same object record.
    2. Insert and update operation same object.

    Sample Example: if opportunity amount is less then 10000 then through error.


    Trigger validateOppRecord on opportunity(Before Insert){
                             For(opportunity o: Trigger.new)
                               If(o.amount<10000){
                                   o.addError(‘please Enter opportunity amount more than 5000’);
                                  }

                            }

    After Triggers: 
    After Trigger:  After trigger is used when we perform DML operation on one object record and action will effect on another object record by accessing system fields such as record id and last mododifieddate field .

    USES: Insert/Update on related object, not the same object.
                 Notification email.


    Note: We cannot use After trigger if we want to update same record because after saving, record will be committed to database and record will be locked. The records, which fired with after trigger are read only. so  it causes read only error(System.FinalException: Record is read-only) if we perform operation on same object.

    Sample Example: Automatically create a Contact record when we create new Account Record.

    Trigger autoaccCon on Accout(After Insert){
        List<Contact> conlist = new List<Contact>();
        For(Account acc:Trigger.New){
           Contact con = New Contact();
           con.accountid=acc.id;
           con.lastname = acc.name;
           conlist.add(con);
        }
        insert conlist;
    }