Use Standard Controller In Visualforce Page

How to use standard controller in Visualforce Page?

Using Standard Controller we easily insert update and delete record from custom Visualforce Page.

To associating Standard Controller with Visualforce Page use standardController attribute of <apex:page> tag.

To associate custom Object controller use custom object:-

<apex:page standardController=”Custom_Object_Name__c”>

To associate standard Object controller use standard object, suppose you want to bind with Lead object this your code will:-

<apex:page standardController=”Lead”>

Let’s try to save a lead using standard controller. There are some point need to focus during using standard controller:-

  1. Use <apex:pageMessages/> tag insde <apex:form> tag. This tag handle messages like error or warning.
  2. You must include all required fields in your form.
  3. Use any one action from (save,quicksave,delete,edit,cancel and list)
  4. In case of save action if record created successfully then controller redirect to record detail page.
  5. Use command button, action support or action function  to bind with a action(save,quicksave,delete,edit,cancel and list)
<apex:page standardController="Lead" showHeader="true" sidebar="true">
		<apex:outputLabel>Last Name</apex:outputLabel>
		<apex:inputField id="lastName" value="{!lead.LastName}"/>
		<apex:outputLabel>Company Name</apex:outputLabel>
		<apex:inputField id="company" value="{!lead.Company}"/>
		<apex:commandButton action="{!save}" value="Save" />

Output of above code will be

Standard Controller In Visualforce Page

In Lead and Contact  object Last name is mandatory(required) field. Also in Lead Object Company name is required. Click save button without enter field data. You will get error message  like following

Standard Controller In Visualforce Page

Encrypt and Decrypt String in Apex Salesforce

In apex class you can use EncodingUtil and Crypto classes to encrypt and decrypt string in apex class.

Useful methods of EncodingUtil to encode and decode string in apex class.

  1. String base64Decode(String inputString)
  2. String base64Encode(Blob inputBlob)
  3. Blob convertFromHex(String inputString)
  4. String convertToHex(Blog inputBlob)
  5. String urlDecode(String inputString, String encodingScheme)
  6. String urlEncode(String inputString, String encodingScheme)

Note: for URL encode and decode second parameter will be encoding scheme i.e., UTF-8. All methods are static so you can call by class name.

Example of all above methods to encode and decode string

base64Encode() and base64Decode

Blob blobData=Blob.valueOf('salesforce xyz');

// Encode 'salesforce xyz' String using base64
String encodedString = EncodingUtil.base64Encode(blobData);
//output: c2FsZXNmb3JjZSB4eXo=

//Just use decode method to decode above encoded string
Blob decodeString = EncodingUtil.base64Decode(encodedString);
//output: salesforce xyz

convertToHex and convertFromHex() methods

Blob blobData=Blob.valueOf('salesforce xyz');

// Encode 'salesforce xyz' String using base64
String encodedString = EncodingUtil.convertToHex(blobData);
//output: 73616c6573666f7263652078797a

//Just use decode method to decode above encoded string
Blob decodeString = EncodingUtil.convertFromHex(encodedString);
//output: salesforce xyz

if you want to test above code go to developer console press Ctr + E. A anonymous window will be open. Paste code in anonymous box and click execute button.

Encrypt and Decrypt String in Apex

In same way you can encode and decode url using urlEncode() and urlDecode() methods of EncodingUtil class.

Encrypt and Decrypt String in Apex Using ManagedIV

Encrypt and Decrypt String in Apex using ManagedIV. ManagedIV encryption and deryption required an security key of 16 bits. Use 16 bits security key for both encoding and decoding. If you want to get decoded data as string you can use toString() method of Blob class. Want to learn more about encode and decode string in Salesforce click next two linkencodingutil and Crypto classes.

public class MyEncodingUtil
	// Security key must be 16 characters string
	public static key='[email protected]%sAfk';

	public static String encodeString(String encodingString)
		Blob blobData = Crypto.encryptWithManagedIV('AES128', key, Blob.valueOf(encodingString));
		return EncodingUtil.base64Encode(blobData);
	public static String decodeString(String str)
		Blob blobData = EncodingUtil.base64Decode(str);		
		Blob decryptedBlob = Crypto.decryptWithManagedIV('AES128', key, encodedEncryptedBlob);		
		return decryptedBlob.toString();   

All Salesforce DX Commands List

Salesforce  provide Command Line Interface to increase productivity with integrated tools. Using this tool(Salesforce DX) you can create SF Org, apex class, lightning component, visualforce page and so on. You have to download and install tool  on you local machine. Please use following table to download Salesforce DX tool. Reference from

OS Download URL
Windows 32-bit
Windows 64-bit
Debian/Ubuntu 64
Debian/Ubuntu x86

Whenever finish installation open you command window to test sfdx command

Note: All command example from Window OS
If Salesforce DX installed on your system above command will produce following output
Salesforce DX
C:\Users\ADMIN>sfdx help force when you run this command this command return all command list that support by Salesforce DX.

All command suffix by sfdx command

Command Name Description Example
force:apex Work with Apex code

Syntax will be like –> sfdx force:apex:class:create n class_name d forceapp/main/default/classes

-n means required component name

-d means required directory path where component created in local machine

force:apex:class:create (create an Apex class)
force:apex:execute (execute anonymous Apex code)
force:apex:log:get (fetch a debug log)
force:apex:log:list (list debug logs)
force:apex:log:tail (start debug logging and display logs)
force:apex:test:report (display test results)
force:apex:test:run (invoke Apex tests)
force:apex:trigger:create (create an Apex trigger)
force:auth Authorize an org for use with the Salesforce CLI  force:auth:web:login
force:config Configure the Salesforce CLI  force:config:get (get config var values for given names)
force:config:list (list config vars for the Salesforce CLI)
force:config:set (set config vars for the Salesforce CLI)
force:data Manipulate records in your org
force:doc Display help for force commands
force:lightning Create and test Lightning component bundles
force:limits View your org’s limits
force:mdapi Retrieve and deploy metadata using Metadata API
force:org Manage your Salesforce DX orgs
force:package Install and uninstall first- and second-generation packages
force:package1 Develop first-generation managed and unmanaged packages
force:package2 Develop second-generation packages
force:project Set up a Salesforce DX project. force:project:create -n your-proect-name
force:schema View standard and custom objects
force:source Sync your project with your orgs.

pull only source code into your local machine from your configured ORG which are not sync.

push only unsync source code form local machine to configured ORG



force:user Perform user-related admin tasks  force:user:create (create a user for a scratch org)
force:user:display (displays information about a user of a scratch
force:user:list (lists all users of a scratch org)
force:user:password:generate (generate a password for scratch org users)
force:user:permset:assign (assign a permission set to one or more users of
an org)
force:visualforce Create and edit Visualforce page  force:visualforce:component:create (create a Visualforce component)
force:visualforce:page:create (create a Visualforce page)
force:alias Manage username aliases  force:alias:list (list username aliases for the Salesforce CLI)
force:alias:set (set username aliases for the Salesforce CLI)


Set default dev hub username

Note: Here you can get error if you running above some commands. For Example let’s try to create org from scratch use command: sfdx force:org:create -s -f config/project-scratch-def.json -a your-org-name
ERROR: No defaultdevhubusername org found.

Above error will be fixed by sfdx force:config:set [email protected] –global

After setting default username of your development hub org now you are able to run command to create dev org from scratch. Now you can use a command to open new created org by C:\Users\ADMIN\your-project-dir>sfdx force:org:open (this command return an url to open your created org without login)

Use Salesforce DX command to create Apex Class AND Lighting Component

1. Let’s create lightning Component by CLI using sfdx command
C:\Users\ADMIN\your-project-dir>sfdx force:lightning:component:create -n cmp_name -d force-app/main/default/aura (-n means required component name and -d means required directory path where component created in local machine)

2. Let’s create Apex class by CLI using sfdx command

C:\Users\ADMIN\your-project-dir> sfdx force:apex:class:create n class_name d forceapp/main/default/classes

Comment please if you like this post.

Exception Handling And Save Log In Salesforce Object

Exception Handling is the best practice of robust app development and maintenance. In your project if you want to handle exception in proper way and save log in custom object. Then you can create a helper class(“ExceptionHandler“) and an custom object (“Error_Log__c“). What info you can log? You can log class name, method name, username, log time and error description.

So you custom object fields are::

Field Label Api Name Field Type Size
Class Name class_name__c Text 255
Method Name method_name__c Text 255
User username__c Lookup(User)
Log Time log_time__c DateTime 255
Error Description description__c TextArea(Long) 32000
Line Number Line__c Text 6
HTTP Status Code HTTP_Status_code__c Text 7

1. Log Apex Call-Out Error:

public class ExceptionHandler
    public static void logApexCalloutError(String className,String methodName,String lineno,HttpResponse response)
	Error_Log__c log = new Error_Log__c();
	log.className__c = className;
	log.methodName__c = methodName;
	log.lineno__c = lineno;;
	log.user__c = UserInfo.getUserId();
	// You can get HTTP Status Code and Response Body
		log.HTTP_Status_code__c =response.getStatusCode();			
	Insert log;		

2. Exception Handling of Insert and Update Statements

If you insert or update record in bulk using Database.Insert() or Database.upsert() statement then use following method to save log. I think Salesforce Data Loader also use this technique to show insert and update result. But using following code you can log only failed record detail.

public class ExceptionHandler
    public static void logInsertORUpdateError(String className,String methodName,String lineno,List<Database.UpsertResult> saveResultList)
        // In Error Log Custom object you can add an extra column Object name to save also object name
	List<Error_Log__c> logList = new List<Error_Log__c>();
        Transient Database.UpsertResult upsertResult;
        for (Integer index = 0; index < saveResultList.size(); index++) {        
                upsertResult = saveResultList[index];                                    
                //Use isSuccess() method of Database.UpsertResult class to is record inserted/updated or not
                if (!upsertResult.isSuccess()) {                    
                    Error_Log__c log= new Error_Log__c();                    
                    log.description__c = String.valueOf(upsertResult.getErrors()[0].getMessage());
                    log.className__c = className;
	            log.methodName__c = methodName;
	            log.lineno__c = lineno;
	            log.user__c = UserInfo.getUserId();
                    if(upsertResult.getId() != null){
                        log.Object_Name__c = upsertResult.getId().getSobjectType().toString();

Log insert error:

Above method only work for Database.upsert() statement. If you want to log Database.insert() statement errors too. Then you can write same code and change parameter List<Database.UpsertResult> by List<Database.InsertResult>.

You can call logInsertORUpdateError() method like –>

List upsertResObjList = upsert(recordToUpsert, externalIdField, allOrNone);

To learn more about Database statements please click here

Set Default Assignment Rule To Case and Lead Object

This is very easy using trigger to set default assignment rule to case and lead object. First you need to create an assignment rule on Case and Lead object.
Let’s create an assignment rule
Go-to Case Assignment Rules–> click on New button–> Enter Rule Name “Assignment Rule 2” –> make Active by checkbox and click Save button.
Set Default Assignment Rule To Case and Lead Object

There will be only one assignment rule active for an object. In simple way you can said that other assignment rule become inactive if your new created assignment rule become active.

Now let’s create an apex trigger to set assignment rule

trigger setAssignmentRuleTrigger on Case (after insert)
        List arRuleList = new List();
        List caseList = new List();
        arRuleList = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
            for(Case caseObj : [Select Id from Case where Id in :Trigger.newMap.keySet()])
                Database.DMLOptions dmoObj = new Database.DMLOptions();
                dmoObj.assignmentRuleHeader.assignmentRuleId= arRuleList[0].id;                    
            Update caseList;   

In same way you can create a trigger on Lead object to set default assignment rule to new created Lead.

How To Create Lightning Component?

Before start learning about Lightning Component you have to know about Apex Class, Javascript & HML also OOPs Concept.  After reading this article you will be able to create, extends and implements Lightning Components. Here you also learn about lightning method  in lightning component.
Note: You must registered a domain under My Domain. To register your domain Click Here

Let’s create a component named HelloWorld.

Step 1: Go-to Developer Console–> Files–> New–>Lightning Component

Create New Lightning Component

Enter Component Name HelloWorld and click on Submit Button. Lightning component root tag is <aura:component ></aura:component>.

Step 2 Let’s create attribute


<aura:attribute name=”fullname” type=”String” default=”Your Name” description=”User full name”/>

<aura:attribute name=”email” type=”String” default=”” description=”User email address”/>


We have created two attribute fullname and email while defined attribute name follow variable naming rule.

Do not use space in attribute name like name=”full name” this is Wrong, it should be like above attribute name.

Step 3 How to get attribute value in component?

This is very simple {!v.attributename}, if you want to get fullname and email attributes value then you should write {!v.fullname} and {!}.

Step 4 Let’s create a lightning button and bind with component controller


<aura:attribute name=”fullname” type=”String” default=”Your Name” description=”User full name”/>

<aura:attribute name=”email” type=”String” default=”” description=”User email address”/>

<lightning:button onclick=”{!c.alertName}” label=”Alert Name”/>


To bind controller action with lightning button we use {!c.actionName}

Lightning Component Controller


      //Action alertName 
      alertName : function(component, event, helper) {
          //Using component getting attribute value here same as in component.
      // you can write another action here
      //parameter name can be change
      action2: function(com,ev,help){
          //getting attibute value here

<h2> Test your created component</h2>

Now Create a lightning App in same way as you follow previous steps. Go to developer console -> file -> new -> Lightning Application. Enter DemoApp in App name and click submit button.

<aura:application exends=”force:slds”>

Note: Use Ctr+S to save component or any file in developer console. click on preview button to see result of your create component. Here we used exends=”force:slds” in app that means by default salesforce lightning design system apply in your app.



How to create multi-picklist in salesforce lightning component

Multi picklist in salesforce lightning component.
There are only four steps to create mullti picklist in salesforce ligthning component.

multi picklist in salesforce lightning component

Step – 1

let’s create a lightning component named “demoMultipicklistCmp.cmp

<aura:attribute name=”options” type=”list” default=”[]”/>
<aura:attribute name=”selectedOptions” type=”String” default=””/>
<aura:handler name=”init” value=”{!this}” action=”{!c.doInit}”/>
<div class=”slds-form-element”>
<label class=”slds-form-element__label” for=”combobox-unique-id-3″>Search</label>
<div class=”slds-form-element__control”>
<div class=”slds-combobox_container slds-size_small”><!–slds-is-open–>
<div aura:id=”dropdown” onmouseenter=”{!c.openDropdown}” onmouseleave=”{!c.closeDropDown}”    class=”slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-is-close” aria-expanded=”true” aria-haspopup=”listbox” role=”combobox”>
<div class=”slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right” role=”none”>
<input type=”text” class=”slds-input slds-combobox__input slds-combobox__input-value”
placeholder=”Select an Option” readonly=”true” onfocus=”{!c.openDropdown}” value=”{!v.selectedOptions}”/>
<span class=”slds-icon_container slds-icon-utility-down slds-input__icon slds-input__icon_right” title=”Down icon”>
<lightning:icon iconName=”utility:down” size=”xx-small” class=”slds-icon-text-default”/>
<span class=”slds-assistive-text”>Down icon</span>
<div id=”listbox-unique-id” role=”listbox”>
<ul class=”slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid” role=”presentation”>
<aura:iteration items=”{!v.options}” var=”item” indexVar=”ind”>
<li onclick=”{!c.selectOption}” id=”{!item.label+’#BP#’+item.isChecked}” role=”presentation” class=”slds-listbox__item”><!–slds-is-selected–>
<div id=”{!’listbox-option-unique-id-‘+(ind+1)}”
class=”{!item.isChecked==true?’slds-media slds-listbox__option slds-listbox__option_plain slds-media_small slds-media_center slds-is-selected’:’slds-media slds-listbox__option slds-listbox__option_plain slds-media_small slds-media_center ‘}” role=”option”>
<span class=”slds-media__figure”>
<lightning:icon iconName=”utility:check” size=”xx-small” class=”slds-listbox__icon-selected”/>
<span class=”slds-media__body”>
<span class=”slds-truncate” title=”{!item.label}”> {!item.label}</span>

Javascript Controller Named “demoMultipicklistCmpController.cmp
Use following code to handle open, close and handle dropdown option selection.

        var opt =[];
        for(var i=1;i<=5;i++){
             	opt.push({label:'Items '+i,isChecked:true});
             	opt.push({label:'Items '+i,isChecked:false});   
        helper.selectOptionHelper(component,'Item 1','true');       
        var label ="#BP#")[0];
        var isCheck ="#BP#")[1];

Require a helper named “demoMultipicklistCmpHelper.cmp” to handle dropdown selection

    selectOptionHelper : function(component,label,isCheck) {
        var selectedOption='';
		var allOptions = component.get('v.options');
        var count=0;
        for(var i=0;i<allOptions.length;i++){ if(allOptions[i].label==label) { if(isCheck=='true'){ allOptions[i].isChecked = false; }else{ allOptions[i].isChecked = true; } } if(allOptions[i].isChecked){ selectedOption=allOptions[i].label; count++; } } if(count>1){
            selectedOption = count+' items selected';

Your component is created now you are able to use component in lightning app to test your component. Let’s create a lightning app named ““. app code will be

<aura:application extends=”force:slds”>

In app we are using Salesforce Lightning Design System by extending force:slds

HOw to set options of multi picklist in salesforce lightning component using apex controller

You can set options attribute from apex controller. Create a apex class “Demo_Controller”

public class Demo_Controller{
    public static List getOptions()
        List optList = new List();
	optList.add(new PickListOptions('Option 1',false));
	optList.add(new PickListOptions('Option 2',true));
	optList.add(new PickListOptions('Option 3',false));
	return optList;

	// wrapper class 
	public class PickListOptions
		@AuraEnabled public String label;
		@AuraEnabled public boolean isChecked;
		public PickListOptions(String label,boolean isChecked){
			this.label = label;
			this.isChecked = isChecked;

Here using @AuraEnabled annotation that means method become available in lightning. Now update your helper and create a new helper method

getOpetionsHelper: function(component)
      	var action = component.get("c.getOptions");
	// set if using parameter in your apex controller action 
	//action.setParams({ paramName : 'paramvalue' });

	// Create a callback that is executed after        
	action.setCallback(this, function(response) {
		var state  = response.getState(); // return SUCCESS,INCOMPLETE or ERROR string
		var result = response.getReturnValue(); // list return by @AuraEnabled getOptions action 
		for(var i=0;i<=result.length;i++){            
	// $A.enqueueAction adds the server-side action to the queue.


Note: your helper and JS controller method name must not equal to @AuraEnabled apex controller action name.