Monday, August 13, 2018

Component Events: Way to Communicate Between Components in Containment Hierarchy

Components events can be used to pass information between lightning components which are in containment hierarchy. Component events can be handled by component which is firing it or by component container.

Through this blog, I am going to explain how to utilize component events with sample code.


I have created a sample lightning app which contains "c:SK_MasterCmp".  "c:SK_MasterCmp" contains another component "c:SK_ChildCmp"

Below are steps which you need to follow while utilizing component events:

  • Create Lightning event of type "COMPONENT".
        <aura:event type="COMPONENT" description="Event template" >
              <aura:attribute name="passedValue" type="string"/>
        </aura:event>

  • Register the component event which is going to fire component event.
        <aura:registerEvent name="changeValueEvent" type="c:SK_LightningEventChannel"/>
  • Use below syntax to fire event and pass information from "c:ChildCmp".
        var newEvent = component.getEvent("changeValueEvent"); 
        newEvent.setParams({"passedValue":"twitter handle-@sunil02kumar"});                               
        newEvent.fire();
  • Create handler in component which needs to handle the events means want to consume that information. Note the name of handler should be same as that while registering event:
       <!--name should be equal to name while register event-->
       <aura:handler name="changeValueEvent" event="c:SK_LightningEventChannel" 
                  action="{!c.handleNotification}"/>
  • Create function in controller.js which will be called when "c:MasterCmp" will handle the the event.
       handleNotification : function(component, event, helper){
           console.log('****handling event');
           var sentMessage= event.getParam("passedValue");
           component.set("v.mastervalue", sentMessage);
      }


Below is complete code for reference:



Hope this help!!

Thursday, August 9, 2018

How to get User Session Id in Future Method or Batch Class

Sometime it is required to perform Callout in future method and Batch apex class. If we use UserInfo.getsessionId() method inside the future method or batch apex, then it will return null.

Below are different option to get sessionId:

Option 1:

We can either pass sessionId as parameter to future method or to batch apex class.

Option 2:

Create a VF page and use {!$Api.Session_ID} in body.  In apex, get VF page content which will contain session Id.

Below is code snippet explaining the Option 2 by using future method. Same can be used in Batch Apex.

Run below code snippet in execute anonymous to check the output in debug logs:

SessionIdUtility.checkIfUserSessionIdExistInFutureCall();



Hope this help!!!

Remote Site Settings : Way to Create/Update Using Apex (Metadata API)

We can create or update Remote Site Settings in Apex using Metadata API.

You can either download Metadata API WSDL from Salesforce and generate apex class by clicking on Generate from WSDL button.


Or you can download the MetadataService class from below link:

MetadataService.cls

Below is sample to code to create remote site settings.


Execute this static method from execute anonymous and check if records created or not.

 MetadataAPIUtility.createRemoteSiteSettings();

Below is snapshot of remote site settings created


Note:
  • I have used upsertMetadata method. If you want to only insert new remote site setting, then use insertMetadata method
  • fullname property is considered in order to decide whether remote site setting needs to be created or updated.
Hope this will help!!!


Create Custom Metadata Types Using Metadata API
Create Update Custom Label by Using Metadata API


Thursday, July 26, 2018

How to Schedule Apex class to Run Instantly or Run After Some Duration from Developer Console

We create apex scheduler job which can be scheduled to run at specific time. If we want to run job instantly to either check the functionality or want to force start scheduled job then below code sample will help you.

Suppose you have scheduled apex class:

global class SK_JobsSchedulerHelper implements Schedulable {
global SK_JobsSchedulerHelper(){

}
       global void execute(SchedulableContext sc) {
//your business logic
}
}

Now if you want to run it instantly from developer console, then use below script:

SR_JobsSchedulerHelper sch = new SR_JobsSchedulerHelper();
sch.execute(null);

Now if you want to run this job after 5 minutes, then you can use below script:

SR_JobsSchedulerHelper sch = new SR_JobsSchedulerHelper();
Datetime dt = Datetime.now().addMinutes(5);  
String schCronExp = dt.format('s m H d M \'?\' yyyy');
Id schedId = System.Schedule(' scheduling this job at'+System.now().format(),schCronExp,sch);

Hope this help!!


Thursday, July 12, 2018

Adding Lightning Components in VF Page and Passing Values from URL

Can we create custom lightning components and use them in Salesforce Classic?

This question always comes in mind whenever we do development in Org which has not enabled lightning. We call these kind of Org as classic Salesforce Org.

We mainly create lightning components and use them in Lightning experience but it doesn't means that we can not utilize lightning components in Classic Salesforce (in VF)

If we have to create VF page, then create lightning components as per requirement and then add them in VF pages. So if in future, you migrate to Lightning from Salesforce Classic then you do not have to re-work on implementing VF functionality in Lightning.

Through this blog, I am going share sample code which explains how we can create lightning components and add it to VF pages. As lightning components works mainly based on attributes defined in component, how we can pass values to these attributes from VF page so that they behave as per requirement.

In below code, I am passing the Account Id and string message in VF page using URL parameters and then sending Account name and message to lightning component.

You can open VF page and specify parameters in URL. Below is sample URL:

/apex/SK_LtngCmpContainerVF?id=0019000001rHOgA&infoString=AccountId is passed from URL in VF and captured by component

or

/apex/SK_LtngCmpContainerVF?id=0019000001rHOgA&infoString=AccountId%20is%20passed%20from%20URL%20in%20VF%20and%20captured%20by%20component

Below is screenshot of VF page

Hope this will help!!!

Sunday, July 8, 2018

Create Custom Metadata Types Using Metadata API

As we know, custom metadata is also considered as metadata due to which it helps to migrate predefined settings between different Organizations. If we use custom setting, then we need to upload custom records separately after migrating custom settings.

By using, Metadata API we can create apex script to create custom metadata.

You can either download Metadata API WSDL from Salesforce and generate apex class by clicking on Generate from WSDL button.


Or you can download the MetadataService class from below link:

MetadataService.cls

Below is custom metadata created for explaining the apex code:



Below is code snippet to create custom metadata record.


Execute this static method from execute anonymous and check if records created or not.

 MetadataAPICMUtility.createCustomMetadata();

Below is snapshot of record created


You can use above code sample to create records in custom metadata. You can maintain .csv file with all custom metadata records and parse it with apex and then create record in custom metadata.

In order to understand when to use custom setting or custom metadata type and their implementation tricks, please refer below URL:

Custom Metadata Types and Custom Settings Implementation Tricks


Hope this will Help!!!

Wednesday, July 4, 2018

Create Update Custom Label by Using Metadata API

We usually update custom labels from UI. After sandbox refresh, we update all custom labels so that these don't point to production URLs or values.

By using Metadata API, we can write automated apex script through which we can update all custom labels.

You can either download Metadata API WSDL from Salesforce and generate apex class by clicking on Generate from WSDL button.


Or you can download the MetadataService class from below link:

MetadataService.cls

I have created 2 separate static methods, one for creating new custom label and another for updating existing custom label. Below is class code:


Now by running below code in execute anonymous in developer console, you can create custom label:

MetadataAPIUtility.createCustomLabel('SFDC_Blog_URL','My test label from metadata api','en_US','http://www.sfdcstuff.com/',false);



You have to specify custom label values as a parameters in static method.

In order to update custom label, execute below code:

MetadataAPIUtility.updateCustomLabel('SFDC_Blog_URL','My test label from metadata api','en_US','https://www.sfdcstuff.com/search/label/Lightning',false);



Hope this will help!!