Saturday, 17 October 2020

How to retain formula field value on record update?

We have formula function ISNEW() to identify record is created or updated. ISNEW() is available in workflow and Process builder, not in formula field. 

What if we want to execute formula field value only in record creation and value should not be changed on record update. Let me share a business scenario.

Assume we have status icon image formula field on case shows different image based on the Entitlement End date. There was chance case record can refer to different entitlement, at that time business does not want to change status image formula on entitlement change , Instead there should be new status icon field which should be calculated based on different Entitlement.

If you are thinking to implement workflow or process builder, we cant use Image formula field and ISNEW function is not available in formula field.

Here is the workaround for this.

Create a new formula field which will be only executed when record created, there will be other formula field which will be executed all the time. Now business can easily report on both field values.

Workaround for ISNEW function in formula field is 

IF(MINUTE(TIMEVALUE( Craeteddate))== MINUTE(TIMEVALUE( LastModifiedDate))

Formula Field for Record creation 

IF(MINUTE(TIMEVALUE( Created_Date__c))== MINUTE(TIMEVALUE( LastModifiedDate)), IF(ISBLANK(AccountId),'',IMAGE(IF(( Primary_user_Entitlement_End_Date__c> Today()),'/img/msg_icons/confirm24.png','/img/msg_icons/error24.png'),'Entitlement Flag')), IMAGE(IF(( End_user_Entitlement_End_Date__c> Today()),'/img/msg_icons/confirm24.png','/img/msg_icons/error24.png'),'Entitlement Flag'))

Formula field for record update 

IF(ISBLANK(AccountId),'', IMAGE(IF((Entitlement.EndDate > Today()),'/img/msg_icons/confirm24.png','/img/msg_icons/error24.png'),'Entitlement Flag'))

Thursday, 1 November 2018

How to know object name from a record Id in dynamically ?

Hi All,

There are may ways to identify object name from the record id, Below is the simplest one.

String recId = '001hjhtthijhkfj';
String sObjName = recID.getSobjectType().getDescribe().getName();
System.debug('Printing-sObjName -'+sObjName ); --- Account

Here is my earlier post which talks about to get keyprefix of an object

Use Cases 

Lets assume we need to modify few fields of two different object records (Say Account and Contact), user has to modify from the detail page,

What will be our first step ?  We will create two custom detail page button (one for Account and another for Contact) .
Buttons will be linked to visual force page having standard controller Account/Contact.

The page will have a button "Save" , Save button function will be written in an extension class. At that time we should not create two extension class one for Account another for contact. We should be creating one extension class having one method which updates Account and Contact dynamically based on record id.

Public Account acc{get;set;}
Public Contact con {get;set;}
public updateRecords(Apexpages.StandardController con){
    System.debug('Printing con...'+con.getId());
        String sRecordId = con.getId();
        if(sRecordId.subString(0,3) == Account.sObjectType.getDescribe().getKeyPrefix()){
        acc= new Account(Id = sRecordId);
        else if(sRecordId.subString(0,3) == Contact.sObjectType.getDescribe().getKeyPrefix()){
        con = new Queue_View__c(Id = sRecordId);

If(acc !=null){
update acc;
if(con !=null){
update con;

Friday, 17 August 2018

How to get Record Type developer name in Apex ?

Hi All,

Before summer 18, we used to write SOQL query to get developer name of a particular record type, now SOQL query is not required. 

This is my earlier post where recordtypeinfo method has been explained. What can we do using those methods.

1. How can we get Record Type Id of an object ?

    a.  Lets assume we know the record type name. say its "Inquiry".

Id objectRecordTypeId = Schema.SObjectType.CASE.getRecordTypeInfosByName().get('Inquiry').getRecordTypeId();
System.debug('objectRecordTypeId ---'+objectRecordTypeId ); 

    b.  Lets assume we know the record type developer name, say its "DevInquiry".

Id objectRecordTypeId = Schema.SObjectType.CASE.getRecordTypeInfosByDeveloperName().get('DevInquiry').getRecordTypeId();
System.debug('objectRecordTypeId ---'+objectRecordTypeId );

2.  How can we get record type developer name ? 

     a. Lets assume we know the record type name. say its "Inquiry".

String developerName = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Inquiry').getDeveloperName();

Same code can be broken into following.

String recordTypename = 'Inquiry';

Schema.DescribeSObjectResult caseDesribe = Schema.SObjectType.Case;
Map<String,Schema.RecordTypeInfo> rtMapByName = caseDesribe.getRecordTypeInfosByName();
Schema.RecordTypeInfo rtByName =  rtMapByName.get(recordTypename);
String RecordTypeDeveloperName = rtByName.getDeveloperName();
System.debug('RecordTypeDeveloperName --'+RecordTypeDeveloperName ); 

  b.  Lets Assume we know recordType id.

String developerName = Schema.SObjectType.Case.getRecordTypeInfosById().get('012w0000000kc2XAAQ').getDeveloperName();

Please let me know if you have any confusion, I would be happy to help.

Maintain Your Platform Developer I Certification for Summer ’18

How to use ISBLANK function in visuaforce page ?

Hi All,

Just a brief what isblank method does.


Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.
How to render a particular component based on the string value defined in the controller. if that string is null or blank dont rerder component.
In the class say the variable name is
Public String sStringBlankField{get;set;}  
In the visualforce page use it like below
 <apex:outputpanel  rendered = "{!len(sStringBlankField)>0 || sStringBlankField!=null}">

Thursday, 9 August 2018

How to use custom Lebel in javascript file ?

We all know how custom labels are useful, we can use in apex/visual force/workflow formula/validation rule etc. This post is all about hot to use in java script file which is been uploaded in static resource.

In the page just add these two lines of code, which will make js file understand the custom label.

      window.$Label = window.$Label || {};


In the java script file use like below

Tuesday, 7 August 2018

How to use includes operator in query filter ?

Hi All,

It has been a long time, there is no post in salesforce4u, I am apologizing for being so late, now I am assuring you, there will be at least one post in each month.

We will start with the simple one, Last week I faced one query exception "expecting left parentheses, found ':'",  Let me share how did I resolve that issue.

The requirement was just filtering records using multi-select picklist values. What exactly will come to a developer mind ??  Use the following operator to accomplish.

1. LIKE - It will be used for normal string/text field filter and it's a partial match.
2. CONTAINS - It is not being used at all in SOQL
3. INCLUDES - This is the best one to use for this requirement.

How to use INCLUDES operator in the SOQL query.

Below is the code snippet to filter Account based on value  ( 'Agriculture','HR' ).

Static Querry
List<Account> accList = [Select id,name,LOB__c from Account where LOB__c INCLUDES ('Agriculture','HR') ];
System.debug('accList ---'+accList[0]);

Dynamic Query

set<String> lobSet = new Set<String>{'Agriculture','HR'};
System.debug('lobSet ---'+lobSet );

String queryFilter = '';
For(String str :lobSet ){
   queryFilter += queryFilter == '' ? '(\''+str+'\'' : ','+ '\''+str+'\'';
queryFilter += ')';
System.debug('queryFilter ---'+queryFilter );

String sQuery = 'Select id,name,LOB__c from Account where LOB__c INCLUDES  '+queryFilter;
System.debug('sQuery ---'+sQuery );
List<Account> accListDynamicQueryResults = Database.query(sQuery);
System.debug('accListDynamicQueryResults ---'+accListDynamicQueryResults );

For more info related to Includes operator

Please let me know if it is useful or not by adding comments below.

Sunday, 10 December 2017

How to format Date and Date time in Apex class ?

Hi All,

We might need to display date in some other format as per requirement. For example there might be an requirement to display created date as MONTH/DAY or time as 11: 00 PM or 9 :00 AM.  

How will we do it ? 

For Time format
System.debug('hh:mm a'));

For Date format 

 String daysMonth = String.valueOf(Date.Today().month()) + '/' + String.valueof(Date.Today().day());
 System.debug('daysMonth --'+daysMonth );

22:54:03.3 (3392679)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
22:54:03.3 (3811485)|SYSTEM_METHOD_ENTRY|[1]|
22:54:03.3 (3885055)|SYSTEM_METHOD_EXIT|[1]|
22:54:03.3 (3920613)|SYSTEM_METHOD_ENTRY|[1]|String.valueOf(Object)
22:54:03.3 (3939253)|SYSTEM_METHOD_EXIT|[1]|String.valueOf(Object)
22:54:03.3 (4125004)|SYSTEM_METHOD_ENTRY|[1]|System.debug(ANY)
22:54:03.3 (4135074)|USER_DEBUG|[1]|DEBUG|Today--2017-12-10 00:00:00
22:54:03.3 (4141876)|SYSTEM_METHOD_EXIT|[1]|System.debug(ANY)

22:54:03.3 (4268948)|SYSTEM_METHOD_ENTRY|[3]|System.debug(ANY)
22:54:03.3 (4279474)|USER_DEBUG|[3]|DEBUG|daysMonth --12/10

For more info please refer below link

Tuesday, 28 November 2017

How to calculate time spent or no of days between two day time value ?

Hi All,

This post explains how to  calculate time spent and no of days between two date time value and issue faced while doing same and how to resolve those.

First Try 
Account acc = [select id,createddate,lastmodifieddate from Account limit 1];

datetime diff = acc.lastmodifieddate - acc.createddate;
System.debug('diff --'+diff );

Error - ERROR:COMPILE ERROR: Date/time expressions must use Integer or Double or DecimalLINE: 3 COLUMN: 14

 Second Try 

Account acc = [select id,createddate,lastmodifieddate from Account limit 1];

Integer diff = Integer.valueOf(acc.lastmodifieddate) - Integer.valueOf(acc.createddate);
System.debug('diff --'+diff );

ERROR:EXCEPTION: System.TypeException: Invalid integer: java.util.GregorianCalendar[time=1455789326000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=1,WEEK_OF_YEAR=7,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=49,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=9,HOUR_OF_DAY=9,MINUTE=55,SECOND=26,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]STACKTRACE: AnonymousBlock: line 3, column 1LINE: 3 COLUMN: 1

Final Try and It works.

Account acc = [select id,createddate,lastmodifieddate from Account limit 1];
long seconds = acc.lastmodifieddate.getTime() - acc.createddate.getTime();
System.debug('seconds --'+seconds);
long millseconds = seconds/1000;
System.debug('millseconds --'+millseconds );
Integer min = Integer.valueof(millseconds/60);
System.debug('min --'+min );
Integer hour = min/60;
System.debug('hour --'+hour);
Integer day = hour/24;
System.debug('day --'+day );

The key note here is use of getTime() method.

We can also use Day() to get the difference.
Account acc = [select id,createddate,lastmodifieddate from Account where name = 'yyy' limit 1];
System.debug('createddate --'+acc.createddate);
System.debug('lastmodifieddate --'+acc.lastmodifieddate);
long daysDifference = -;
System.debug('seconds --'+seconds);

Tuesday, 25 July 2017

How to Lock/Unlock record thorough Apex code ?

Hi All,

We all have faced many business scenario where we have to lock/unlock records. We had traditional approach to create separate record type and page layout to achieve it, but salesforce has given API to do thorough apex code.

Please make sure below settings is enabled.

Locking Record 

1. Create a standard Approval process which will take care of locking records.

2. Invoke Approval process
  a. Using Process builder (Submit for Approval)
  b. Use Apex code to invok from trigger or custom button.

    * This method will invoke the standard approval process
    public static void submitForApproval(Case caseRecord)
        // Create an approval request for the Opportunity
        System.debug('Printing insyde approval process method');
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval automatically using Button');
        //req1.setNextApproverIds(new Id[] {case.owner});

        // Submit the approval request for the Opportunity
        Approval.ProcessResult result = Approval.process(req1);


If there is no approval process defined still we can lock the record.

// Query the accounts to lock
Case [] cases = [SELECT Id from Case];
// Lock the accounts
Approval.LockResult[] lrList = Approval.lock(cases, false);

// Iterate through each returned result
for(Approval.LockResult lr : lrList) {
    if (lr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully locked account with ID: ' + lr.getId());
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : lr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Case fields that affected this error: ' + err.getFields());

Unlocking record

Below is the code which will unlock the record.

    * This method will unlock case record.
    public static void unlockCaseRecord(Case caseRecord) {
        Approval.UnlockResult unlockedRersult = Approval.unlock(caseRecord);
        // Iterate through each returned result
        if (unlockedRersult.isSuccess()) {
            // Operation was successful, so get the ID of the record that was processed
            System.debug('Successfully unlocked opportunity with ID: ' + unlockedRersult.getId());
        else {
            // Operation failed, so get all errors                
            for(Database.Error err : unlockedRersult.getErrors()) {
                System.debug('The following error has occurred.');                    
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                System.debug('opportunity fields that affected this error: ' + err.getFields());

Monday, 24 July 2017

How to resolve the java script error "Cannot read property execute of undefined"

Hi All,

Debugging java script error is very tedious, if there is some still mistake then whole functionality will not work and it will not even tell line number of code where exactly that error is coming.

Anyways let us say you have custom detail page button (Source code = java script) , you want to call apex class from that button code, you faced this error "Cannot read property execute of undefined"
This is because you have missed to add {!requireScript("/soap/ajax/26.0/apex.js")} in the java script code.