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 https://trailhead.salesforce.com

OSDownload URL
Windows 32-bithttps://sfdc.co/sfdx_cli_win
Windows 64-bithttps://sfdc.co/sfdx_cli_win64
macOShttps://sfdc.co/sfdx_cli_osx
Debian/Ubuntu 64https://sfdc.co/sfdx_cli_linux
Debian/Ubuntu x86https://sfdc.co/sfdx_cli_linux_x86

Whenever finish installation open you command window to test sfdx command

Note: All command example from Window OS
C:\Users\ADMIN>sfdx
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 NameDescriptionExample
force:apexWork 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:authAuthorize an org for use with the Salesforce CLI force:auth:web:login
force:configConfigure 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:dataManipulate records in your org
force:docDisplay help for force commands
force:lightningCreate and test Lightning component bundles
force:limitsView your org’s limits
force:mdapiRetrieve and deploy metadata using Metadata API
force:orgManage your Salesforce DX orgs
force:packageInstall and uninstall first- and second-generation packages
force:package1Develop first-generation managed and unmanaged packages
force:package2Develop second-generation packages
force:projectSet up a Salesforce DX project.force:project:create -n your-proect-name
force:schemaView standard and custom objects
force:sourceSync 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:source:pull 

force:source:push

force:userPerform 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
org)
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:visualforceCreate and edit Visualforce page force:visualforce:component:create (create a Visualforce component)
force:visualforce:page:create (create a Visualforce page)
force:aliasManage 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 LabelApi NameField TypeSize
Class Nameclass_name__cText255
Method Namemethod_name__cText255
Userusername__cLookup(User)
Log Timelog_time__cDateTime255
Error Descriptiondescription__cTextArea(Long)32000
Line NumberLine__cText6
HTTP Status CodeHTTP_Status_code__cText7

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.log_time__c=System.now();
	log.user__c = UserInfo.getUserId();
	
	// You can get HTTP Status Code and Response Body
	if(response!=null)
	{
		log.description__c=response.getBody();
		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.log_time__c=System.now();
	            log.user__c = UserInfo.getUserId();
                    if(upsertResult.getId() != null){
                        log.Object_Name__c = upsertResult.getId().getSobjectType().toString();
                    }
                    logList.add(log);                    
                }
          }
          if(!logList.isEmpty())
          {
               Database.insert(logList);
          }	
    }
}

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);
ExceptionHandler.logInsertORUpdateError('clsname',methodname,'212',upsertResObjList);

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)
{   
    if(trigger.isInsert){
        List arRuleList = new List();
        List caseList = new List();
        
        arRuleList = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
        
        if(!arRuleList.isEmpty())
        {
            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;                    
                caseObj.setOptions(dmoObj);
                caseList.add(caseObj);
            }
            
            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:component>

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

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

</aura:component>

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 {!v.email}.

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

<aura:component>

<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”/>

</aura:component>

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

Lightning Component Controller

HelloWorldController.js

({
      //Action alertName 
      alertName : function(component, event, helper) {
	  alert(component.get("v.fullName"));
          //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
          com.get("v.attributename");
      }
})

<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”>
<c:HelloWorld/>
</aura:application>

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:component>
<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>
</span>
</div>
<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>
<span class=”slds-media__body”>
<span class=”slds-truncate” title=”{!item.label}”> {!item.label}</span>
</span>
</div>
</li>
</aura:iteration>
</ul>
</div>
</div>
</div>
</div>
</div>
</aura:component>

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

({
    doInit:function(component,event,helper){
        var opt =[];
        for(var i=1;i<=5;i++){
            if(i==1){
             	opt.push({label:'Items '+i,isChecked:true});
            }
            else{
             	opt.push({label:'Items '+i,isChecked:false});   
            }
        }
        component.set("v.options",opt);
        helper.selectOptionHelper(component,'Item 1','true');       
    },
    openDropdown:function(component,event,helper){
        $A.util.addClass(component.find('dropdown'),'slds-is-open');
        $A.util.removeClass(component.find('dropdown'),'slds-is-close');
    },
    closeDropDown:function(component,event,helper){
        $A.util.addClass(component.find('dropdown'),'slds-is-close');
        $A.util.removeClass(component.find('dropdown'),'slds-is-open');
    },
    selectOption:function(component,event,helper){        
        var label = event.currentTarget.id.split("#BP#")[0];
        var isCheck = event.currentTarget.id.split("#BP#")[1];
        helper.selectOptionHelper(component,label,isCheck);
    }
})

Step-3
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';
        }
        component.set("v.selectedOptions",selectedOption);
        component.set('v.options',allOptions);
    }
})

Step-4
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 “demoMultipicklistApp.app“. app code will be

<aura:application extends=”force:slds”>
<c:demoMultipicklistCmp/>
</aura:application>

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{
    @AuraEnabled
    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++){            
			opt.push({label:result[i].label,isChecked:result[i].isChecked});
        }
        component.set("v.options",opt);
	});
	
	// $A.enqueueAction adds the server-side action to the queue.
	$A.enqueueAction(action);

} 

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

What is apex trigger in salesforce?

Apex trigger is block of code wrapped by {} and fire whenever object(table) records are (insert,update and delete) all DML Operation like.

Suppose you want to set Title field of Contact object on the basis of “Gender__c” and “Marital_Status__c” custom field. There are no standard Gender and Marital Status fields for Contact Object in Salesforce. So please add both custom fields Gender and Marital Status in Contact Object if you want to run following apex trigger.

If you want to create custom fields in contact object

Step-1: goto to top-right of screen and click setup link and type Contact in search box after that click highlighted fields link.

Step-2:  Goto Contact Custom Fields & Relationships section and click on new button to add custom field. in next screen select a data type Picklist not multi select and click next button.

Step-3: Filled all required fieldsFor option value check “Enter values, with each value separated by a new line” add two option Male and Female separated by new line.

Step-4: Click Next button.

Step-5: Click Save button.

Marital Status custom field you can create in same way.

Now Let’s create trigger on Contact Object to set Title fields of contact.
Apex TriggerApex Trigger

trigger SetTitleTrigger on Contact (before insert,After Update) {
    List conatctList = new List();    
    if(Trigger.isInsert){
        for(Contact cont : Trigger.New){
            if(String.isNotBlank(cont.Title)){
                if(String.isNotBlank(cont.Gender__c) && (cont.Gender__c.toLowerCase()=='female'))
                {
                    if(String.isNotBlank(cont.Marital_Status__c) && (cont.Marital_Status__c.toLowerCase()=='single'))
                    {
                        cont.Title = 'Ms.';
                    }
                    else
                    {
                        cont.Title = 'Mrs.';
                    }
                }
                else
                {
                     cont.Title = 'Mr.';   
                }
            }
        }
    }
}

Apex Trigger Context Variables

List of context variables are available in apex trigger. Some of variables are very useful i.e., isInsert, isUpdate, isDelete, isBefore and isAfter. I suggest that you should create only one trigger for each object if required. Example

trigger SetTitleTrigger on Contact(before insert,before update,before delete,after update, after delete) {
    List conatctList = new List();    
    if(Trigger.isInsert){
	// execute (in both case before and after) if insert a contact
     }
     if(Trigger.isInsert && Trigger.isBefore){
	// execute before insert a contact
	// you can set some field value before inserting record
     }
     if(Trigger.isInsert && Trigger.isAfter){
	// execute after insert a contact
	//Here you can get 
     }
     ...
     ..
     .
}

In same way you can check isUpdate and isDelete along with isBefore and isAfter context variables.

Difference Trigger.new and Trigger.newMap

Trigger.new is a apex context variable that return list of sObject while Trigger.newMap return Map of Id and sObject.

List objList = Trigger.new;
Map<Id,sObject> objList = Trigger.newMap;

There are also two variables Trigger.old and Trigger.OldMap. These two variable return list and map of sObject if record is update or delete only.

Prevent Recursive Trigger in Salesforce Apex

What is recursive trigger?

You have learned about recursion process of loop. Same logic here means a trigger fire by itself. In detail you say that recursive trigger fire by some code of block which is written in same apex trigger or INSERT or UPDATE.

public Class AvoidRecursive
{
    private static boolean isRun = true;
    public static boolean runOnce()
    {
        if(isRun)
        {
            isRun=false;
            return true;
        }
        else
        {
           return isRun;
        }
    }
}

Use above runOnce() static method in trigger before insert/update statement like

if(AvoidRecursive.runOnce())
{
     // Database insert/update/delete statement
}