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.

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.



Thursday, 13 July 2017

How to display button on apex page message ?

Hi All,

We might need to display button while showing page message to get user feed back. Based on user feedback necessary action need to be taken care.

For example

Below is the code snippet.

 <apex:pageMessages escape="false"/> 
<apex:outputPanel rendered="{!isYesVisible}">
        <apex:pageMessage severity="info" strength="3" summary="{!applicantMessage}">
                <apex:commandButton value="Yes" action="{!cloneOpportunity}"/>
                <apex:commandButton value="No" action="{!stayinSamePage}"/>

Tuesday, 11 July 2017

How to supress standard approval email in salesforce ?

Hi All,

Sometimes we might need to suppress approval email from being sent out without affecting approval process.

There are two way we can achieve it.
1. Creating Queue.

Create empty queue record and use empty queue in approval process as approver.

2. Update user record
Select Migration admin user as approver in the approval process.
Change approver setting for migration admin user.

Saturday, 8 July 2017

How to export detail record in word document ?

Hi All,

We can do this using conga composer , in my earlier post I have explained this .

We will do in simple way/easier way. here we go

1. Create visaulforce page

<apex:page standardController="Case" contentType="application/msWord#msword.doc">
    <apex:detail />

2. Create custom button. Content source might be execute java script or link.


How to use comparatiors operator in java script button code ?

Hi All,

This post is just to help you to use comparatiors operator (Greater than  > and less than <) effectively in Java script code.

I did face some issue while using,

Say the case record is having Absolute_Total_Exception_Amount_USD__c as 50,340.

alert('print-'+{!Case.Absolute_Total_Exception_Amount_USD__c}); -- it will Print50
alert('print-'+"{!Case.Absolute_Total_Exception_Amount_USD__c}"); - It will print 50,340
var amount =  "{!Case.Absolute_Total_Exception_Amount_USD__c}";

if(amount  > "120000"){
alert('webservice method');

Always else block will get executed, Pagemethod alert will come.

The correct approach will be
var amount = {!VALUE(TEXT(Case.Absolute_Total_Exception_Amount_USD__c))};
alert('Pagemethod-4-'+amount );
if(amount  > "120000"){
alert('webservice method');

Saturday, 24 June 2017

How to track Organization’s Custom Object Usage by User License Type ?

Hi All,

We can generate a report to keep track on custom object usages in the ORG.

1. Creating Report Type.
2. Create Report using report type.

  • Set up- Create--Report Type-- New.

Friday, 23 June 2017

Enabling association of multiple accounts to a particular contact

Hi All,

As part of summer 16 release SFDC lunched a cool feature,Allow users to relate a contact to multiple accounts .

Now contacts are not necessarily to be linked to one Account, it can be multiple account based on different different role.

Demo -

Link to refer more info  -

How can we show in visualforce page ?  

<apex:page standardController="Account">
  <apex:detail relatedList="false"/>
  <apex:relatedList list="AccountContactRelations"/>
on the Account page one new related list (Related Contacts) will get introduced.

<apex:page standardController="Contact">
  <apex:detail relatedList="false"/>
  <apex:relatedList list="AccountContactRelations"/>

on the Contact Page one new releated list (Related Accounts) will get introduced. 

Monday, 22 May 2017

How to avoid hard coded record type id from Validation rule ?

Hi All,

It is not best pratice to use hard coded id value in validation rule or in any formula field logic, because ID value will keep on changing form environment to environment.

if we use hard coded id then it will cause lot of maintenance activity. Here is an example where hard code Id value is being used and how to achieve without using hard code value.

AND( ISBLANK(CustomField__c ), 
RecordTypeId ='0124B0000004aZ4', 

OR(ISPICKVAL(Type, 'New'), 
ISPICKVAL(Type, 'Reserved')), 
NOT($Profile.Name ='Integration Admin'))

Instead of recordtypeid it is better to use Recordtype.developername.

AND( ISBLANK(CustomField__c), 
RecordType.DeveloperName ='Marketing_Event', 
OR(ISPICKVAL(Type, 'New'), 
ISPICKVAL(Type, 'Reserved')), 
NOT($Profile.Name ='Integration Admin'))

Thursday, 13 April 2017

How to find total number of records of each object in salesforce ?

Hi All,

Sometimes we are asked to share total number of records of each object and what percentage it is increasing.

Salesforce is so smart,
Login-->Set up-->Data Management-->Storage Usage

Tuesday, 14 February 2017

How to delete all scheduler jobs at a time?

Hi All,

Below is the script to help you to delete all scheduler jobs at a time.

List<CronTrigger> scope = [select id from CronTrigger];
System.debug('Hi---'+scope );
for(CronTrigger cron:scope ){



Tuesday, 7 February 2017

How to tab Order for the fields in visualforce page?

We can use the attribute tabOrderHint of visualforce page to control tab order.

<apex:inputField value="{!Account.AnnualRevenue}" tabOrderHint="1"/>

<apex:inputField value="{! oppyContact.Contact_Street_Address__c}" tabOrderHint="1"/>
<apex:inputField value="{! oppyContact.Contact_Country__c}" tabOrderHint="3"/>
<apex:inputField value="{! oppyContact.Contact_State_Province__c}" tabOrderHint="2"/>
<apex:inputField value="{! oppyContact.Contact_Zip_PostalCode__c}" tabOrderHint="4"/>

How to use Field Set in Page and in Controller

Sometimes we  don't know which fields should be displayed in the page and which field should be added in the query. To solve this issue and make it salable SFDC has given cool features called Field set.

This post will share some code snippet about using field set in the page and in controller.

In the page
<apex:repeat value="{!$ObjectType.Lead.FieldSets.Update_Fields_FieldSET}" var="f">  
      <apex:inputField value="{!leadTemp [f]}"/><br/>
Public Lead leadTemp {get;set;}

In the apex class

String sQuerry = 'Select id,GEO__c,Is_Locked__c,';
       for(Schema.FieldSetMember f : SObjectType.Lead.FieldSets.Update_BDR_Activity_Fields.getFields()) {
                sQuerry = sQuerry+f.getFieldPath()+',';
       sQuerry = sQuerry.substring(0,sQuerry.length()-1);
sQuerry = sQuerry+' From Lead';
ldList = Database.query(sQuerry );


How to assign value entered from page to lead list

for(Schema.FieldSetMember f : SObjectType.Lead.FieldSets.Update_BDR_Activity_Fields.getFields()) {
if(leadTemp.get(f.getFieldPath()) != null){
System.debug('inside iffff');