Saturday, 6 August 2022

Format Dates and Time using Apex in Salesforce

 

Format Dates and Time using Apex in Salesforce


This post explains how to format dates and times using apex.
The below table contains the formatting codes.

LetterDate or Time PieceExamples
GEraG = AD
yYearyy = 09, yyyy = 2009
MMonthMM = 08, MMM = Aug, MMMMM = August
wWeek in yearw = 35
WWeek in monthW = 3
DDay in yearD = 235
dDay in monthdd = 27
FDay of week in monthF = 2
EDay in weekE = Thu, EEEEE = Thursday
aAM/PMa = AM or PM
HHour in day (0-23)HH = 23
kHour in day (1-24)kk = 24
KHour in am/pm (0-11)KK=11
hHour in am/pm (1-12)hh = 12
mMinutes in hourmm = 30
sSecond in minutess = 55
SMillisecond in secondSSS = 888
zTime zonez = EDT, zzzzz = Eastern Daylight Time
ZTime zone offsetZ = -0400

Monday, 12 July 2021

Validate duplicate status on opportunity

 



trigger opportunityTrigger on Opportunity (){

 opportunityTriggerHandler.validateOpportunity(Trigger.New, Trigger.old);

}


public class opportunityTriggerHandler{


  public static void validateOpportunity(List<Opportunity> oppList){

  Set<String> accountIdset = new Set<String>();

  for(Opportunity opp : oppList){

     if(opp.AccountId != null){

         accountIdset.add(opp.AccountId);

    }

  }

 

  Map<String,String> opportunityMap = new Map<String,String>();

  

  for(Opportunity opp : [SELECT Id,StageName FROM Opportunity where stageName != null && accountId !=null And accountId IN :accountIdset LIMIT 49999]){

     opportunityMap.add(opp.AccountId,opp.stageName);

  }

    for(Opportunity opp: oppList)){

      if(opp.containsKey(opp.AccountId) && opp.get(opp.AccountId)== opp.stageName){

         opp.stageName.addError('StageName already exists for this account');

     }

   }

 }

}

Thursday, 17 June 2021

Check value exist in array using Javascript

var preHSValues = userRole.HealthSystem.split(",");  

for (var i in hsOptions) {

                            var checkExistingValue = hsOptions.find(

                                opt => opt.value === preHSValues[i]

                            );

                            if (checkExistingValue) {

                                hsValuesNew.push(preHSValues[i]);

                            }

}

Tuesday, 15 June 2021

Apex OOPs Concepts

 Object means a real-world / run time entity such as marker, car, table, chair, etc. Object-Oriented Programming is a methodology or way to design a program using classes and objects. It eases software development and its maintenance by providing some beautiful concepts as followed.

  • Classes
  • Objects
  • Encapsulation
  • Polymorphism
  • Inheritance
  • Abstraction

Object

Any real world entity that has state and behavior is known as an object. For example: marker, book, table, chair, mouse, car etc.

Technically, we can say object is an instance of a class or in other words you can say it is an implementation of a class.

Class

Class is a concept or prototype or template i.e. it is a logical entity.

Technically, we can say that we create an individual object of a class.

Encapsulation

It is a binding of code and data together into a single unit known as encapsulation. For example, a capsule, it is wrapped with different types medicines into single unit.

An apex class is the example of encapsulation.

Polymorphism

One name many forms known as polymorphism. Real world example of polymorphism: A person at the same time can have different characteristic. Like a woman at the same time is a mother, a wife, an employee and a daughter etc.

In Apex, we use method overloading and method overriding to achieve polymorphism.

Inheritance

When one class acquires all the properties and behaviors of super/parent class it is known as inheritance. It provides code reusability as well as we can used to achieve runtime polymorphism.

Note: Without inheritance we cannot achieve runtime polymorphism.

Abstraction

Hiding internal complexity and showing functionality is known as abstraction. For example: Car Drive, we don’t know the internal processing.

In Apex, we use abstract class and interface to achieve abstraction.


http://salesforcedrillers.com/learn-salesforce/lwc-interview-questions/


Friday, 24 January 2020

Salesforcce Future Methods with Higher Limits (Pilot)


Apex future methods (methods that are annotated with @future) currently have the higher asynchronous limits for heap size, CPU timeout, and number of SOQL queries. This pilot enables you to specify even higher values for these limits and for additional limits in future methods. If you’re exceeding a governor limit in your future method, or if you think a future method requires a higher limit, you can increase this limit for your future method. This pilot also allows you to invoke a future method from another future method.


One of the following limits can be doubled or tripled for each future method.


Heap size

CPU timeout

Number of SOQL queries

Number of DML statements issued

Number of records that were processed as a result of DML operations, Approval.process, or Database.emptyRecycleBin

@future(limits='2x|3x***limitName***')


@future(limits='2xHeap')

public static void myFutureMethod() {

    // Your code here

}

@future(limits=’2xHeap’) = Heap size limit is doubled (24 MB)

@future(limits=’3xHeap’) = Heap size limit is tripled (36 MB).

@future(limits=’2xCPU’) = CPU timeout is doubled (120,000 milliseconds).

@future(limits=’3xCPU’) = CPU timeout is tripled (180,000 milliseconds).

@future(limits=’2xSOQL’) = Number of SOQL queries limit is doubled (400).

@future(limits=’3xSOQL’) = Number of SOQL queries limit is tripled (600).

@future(limits=’2xDML’) = Number of DML statements limit is doubled (300).

@future(limits=’3xDML’) = Number of DML statements limit is tripled (450).

@future(limits=’2xDMLRows’) = Number of records that were processed as a result of DML operations is doubled (20,000)

@future(limits=’3xDMLRows’) = Number of records that were processed as a result of DML operations is tripled (30,000).

Sunday, 4 August 2019

How to add Map of id list of object in apex

     Map<Id,list<Lead>> affliateToLeadsMap = new Map<Id,list<Lead>>();
        for(Lead ld: [SELECT Id, CreatedDate, FirstName, LastName, Email, Status, Affiliate__c FROM Lead WHERE Affiliate__r.Type =: ACC_TYPE_AFF_BROKET_PARTNER AND  Status =: Constant.LEAD_STATUS_PRE_APPROVED AND createdDate > YESTERDAY ]){
            if(affliateToLeadsMap.containsKey(ld.Affiliate__c)){
                affliateToLeadsMap.get(ld.Affiliate__c).add(ld);
            }else{
                affliateToLeadsMap.put(ld.Affiliate__c, new list<Lead>{ld});
            }
        }

Wednesday, 24 July 2019

escape single quotes to the query

Before escape single quotes to field

            
String detailQuery = 'select ' + fieldName + ' from ' + objectName + ' where id = \'' + auditParentId + '\'';

After escape single quotes to the field :


String detailQuery = String.format('select {0} from {1} where {2}', new List<String>{String.escapeSingleQuotes(fieldName), objectName, 'id =:auditParentID'});




Test class : 

 @IsTest
    private static void formatRecordDetailValueShouldThrowExceptionIfSOQLInjectionIsAttemptedOnFieldNameParameter() {
        TestUtil util = new TestUtil();
        User adminUser = util.generateSystemAdminForTest();
        CMPL123__Device__c testDevice = new CMPL123__Device__c (name = 'TestDevice');
        SObjectType sObjectType = CMPL123__Device__c.getSObjectType();
        Insert testDevice;

        String result;
        Boolean exceptionThrown;

        System.runAs(adminUser){
            Test.startTest();
            try {
                result = MDC_Utility.formatRecordDetailValue(testDevice.Id, 'CMPL123__Device__c', 'Name WHERE Name = \'TestDevice\' --');
            } catch (AccessViolationException ave) {
                exceptionThrown = true;
                System.assertEquals(sObjectType, ave.getSObjectType(), 'Exception not caused by ' + String.valueOf(sObjectType));
            }
            Test.stopTest();
        }

        System.assert(exceptionThrown);
        System.assertEquals(null, result, 'result is not null.  value: ' + result);
    
    }

    @IsTest
    private static void formatRecordDetailValueShouldThrowExceptionIfSOQLInjectionIsAttemptedOnObjectNameParameter() {
        TestUtil util = new TestUtil();
        User adminUser = util.generateSystemAdminForTest();
        CMPL123__Device__c testDevice = new CMPL123__Device__c (name = 'TestDevice');
        SObjectType sObjectType = CMPL123__Device__c.getSObjectType();
        Insert testDevice;

        String result;
        Boolean exceptionThrown;

        System.runAs(adminUser){
            Test.startTest();
            try {
                result = MDC_Utility.formatRecordDetailValue(testDevice.Id, 'CMPL123__Device__c WHERE Name = \'TestDevice\' --', 'Name');
            } catch (NullPointerException npe) {
                exceptionThrown = true;
            }
            Test.stopTest();
        }

        System.assert(exceptionThrown);
        System.assertEquals(null, result, 'result is not null.  value: ' + result);
    
    }
}