Thursday, May 31, 2018

Lightning Datatable using Fieldset

1. Create a util class (FieldSetExample) which is responsible to return list of fields (label, api and       type) available under field set of an object passed as parameters by a method.

public class FieldSetExample {
    /**
     * This method is responsible to return list of fields (label, api and type) avaliable
     * under field set of an object passed as parameters.
     * */
    public static List<FieldSetProperties> getFieldFromFieldSet(String objApi, String fieldSetName){
        List<FieldSetProperties> lstOfWrapper = new List<FieldSetProperties>();
        
        Schema.SObjectType sObjType = Schema.getGlobalDescribe().get(objApi);
        Schema.DescribeSObjectResult desSObjRslt = sObjType.getDescribe();            
        Schema.FieldSet fieldSetIns = desSObjRslt.FieldSets.getMap().get(fieldSetName);
        
        for( Schema.FieldSetMember fieldSetMember : fieldSetIns.getFields() ){
            FieldSetProperties wrapperIns = new FieldSetProperties();
            
            wrapperIns.label = String.valueOf(fieldSetMember.getLabel()); 
            wrapperIns.fieldName = String.valueOf(fieldSetMember.getFieldPath()); 
            wrapperIns.type = String.valueOf(fieldSetMember.getType()).toLowerCase();
            
            lstOfWrapper.add(wrapperIns);
        }        
        
        return lstOfWrapper;
    }
    
    /**
     * Wrapper class to hold fieds properties like label, field api and field type.
     * */
    public class FieldSetProperties{
        @AuraEnabled
        public String label;
        @AuraEnabled
        public String fieldName;
        @AuraEnabled
        public String type;
    }
}

2. Create a server side controller class (DataTableExampleController) for the lightning component (dataTableExample) used to display records using data table.

public class DataTableExampleController {
    
    @AuraEnabled
    public static DataTableDetails getDataTableDetails(String objApi, String fieldSetName){
        DataTableDetails dataTableDtls = new DataTableDetails();
        List<FieldSetExample.FieldSetProperties> lstOfFieldSetProperties = FieldSetExample.getFieldFromFieldSet(objApi, fieldSetName);
        
        if(lstOfFieldSetProperties != null && lstOfFieldSetProperties.size() > 0){
            String strQuery = 'SELECT ';
            for(FieldSetExample.FieldSetProperties inst : lstOfFieldSetProperties){
                dataTableDtls.lstOfFieldLabels.add(inst);
                
                strQuery = strQuery + inst.fieldName + ',';
            }
            if(!strQuery.equalsIgnoreCase('SELECT '))
                strQuery = strQuery + 'Id FROM ' + objApi;
            
            dataTableDtls.lstOfSObjs = Database.query(strQuery);
        }
        
     return dataTableDtls;
    }
    
    
    public class DataTableDetails{
        @AuraEnabled
        public List<sObject> lstOfSObjs = new List<sObject>();
        @AuraEnabled
        public List<FieldSetExample.FieldSetProperties> lstOfFieldLabels = new List<FieldSetExample.FieldSetProperties>();
    }
}

3. Create the lightning component (dataTableExample.cmp).

<aura:component controller="DataTableExampleController">
    <aura:attribute name="lstOfRecords" type="Object"/>
    <aura:attribute name="columnsHeader" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
        
    <lightning:datatable data="{!v.lstOfRecords}"
                         columns="{!v.columnsHeader}"
                         keyField="Id"
                         hideCheckboxColumn="true"/>
</aura:component>

4. dataTableExampleController.js

({
    doInit : function(component, event, helper) {
         helper.getDataTableRespone(component, event);
    }
})

5. dataTableExampleHelper.js

({
 getDataTableRespone : function(component, event) {
        var action = component.get("c.getDataTableDetails");
        action.setParams({
            objApi : 'YOUR OBJECT API',
            fieldSetName : 'YOUR FIELD SET NAME'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === 'SUCCESS'){
                //console.log('::::::::::::: SUCCESS :::::::::::::'+JSON.stringify(response.getReturnValue().lstOfFieldLabels));
                component.set("v.columnsHeader", response.getReturnValue().lstOfFieldLabels);
                
                component.set("v.lstOfRecords", response.getReturnValue().lstOfSObjs);    
            }else if (state === 'ERROR'){
                console.log('::::::::::::: ERROR :::::::::::::');
            }
        });
        $A.enqueueAction(action);
 }
})

6. Call the above component from an application (dataTableExampleApp.app)


<aura:application extends="force:slds">
 <c:dataTableExample />
</aura:application>

How to fetch Field(s) under Fieldset using Apex.



public class FieldSetExample {
    /**
     * This method is responsible to return list of fields (label, api and type) avaliable
     * under field set of an object passed as parameters.
     * */
    public static List<FieldSetProperties> getFieldFromFieldSet(String objApi, String fieldSetName){
        List<FieldSetProperties> lstOfWrapper = new List<FieldSetProperties>();
        
        Schema.SObjectType sObjType = Schema.getGlobalDescribe().get(objApi);
        Schema.DescribeSObjectResult desSObjRslt = sObjType.getDescribe();            
        Schema.FieldSet fieldSetIns = desSObjRslt.FieldSets.getMap().get(fieldSetName);
        
        for( Schema.FieldSetMember fieldSetMember : fieldSetIns.getFields() ){
            FieldSetProperties wrapperIns = new FieldSetProperties();
            
            wrapperIns.label = String.valueOf(fieldSetMember.getLabel()); 
            wrapperIns.fieldName = String.valueOf(fieldSetMember.getFieldPath()); 
            wrapperIns.fieldType = String.valueOf(fieldSetMember.getType()).toLowerCase();
            
            lstOfWrapper.add(wrapperIns);
        }        
        
        return lstOfWrapper;
    }
    
    /**
     * Wrapper class to hold fieds properties like label, field api and field type.
     * */
    public class FieldSetProperties{
        public String label;
        public String fieldName;
        public String fieldType;
    }
}

Wednesday, May 30, 2018

Open a Modal Window using overlayLibrary


1. Create a lightning component where your modal content will be displayed.

modalContent.cmp
<aura:component access="global">
    <!-- This is the reference of Modal window -->
    <lightning:overlayLibrary aura:id="overlayLibRefId"/>
    <div class="slds-grid slds-wrap">
        <div class="slds-size_8-of-12">
            <div class="slds-text-align_left">
                ::::: Modal window using overlayLibrary :::::
            </div>            
            <div class="slds-align_absolute-center">
                <lightning:button label="Close" 
                                  onclick="{!c.doCloseOperation}" 
                                  variant="brand" 
                                  class="slds-m-top--medium"/>
            </div>
        </div>
    </div>    
</aura:component>

modalContentController.js
({
 doCloseOperation : function(component, event, helper) {
        //Closing the Modal Window
        component.find("overlayLibRefId").notifyClose();
  
 },
})

2. Create second lightning component from where your actual component (as created above) will be called.

modalWindowOverlay.cmp
<aura:component implements="lightning:actionOverride" 
                access="global">
    <!-- overlayLibId is used to show modal window from controller -->
    <lightning:overlayLibrary aura:id="overlayLibId"/>
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
</aura:component>

modalWindowOverlayController.js
({
    doInit : function (component, event, helper) {
        var modalBody;
        $A.createComponent("c:modalContent", {},
                           function(content, status) {
                               if (status === "SUCCESS") {
                                   modalBody = content;
                                   component.find('overlayLibId').showCustomModal({
                                       header: "Modal Header",
                                       body: modalBody,
                                       showCloseButton: true,
                                       //cssClass: "mymodal CSS"
                                       closeCallback: function() {
                                           console.log('Close ......');
                                       }
                                   })
                               }
                           });
    }
})

3. Now, set the modalWindowOverlay.cmp  under any button and then click the button. It will open the modal window.

Thursday, May 24, 2018

How to call Lightning Component from Visualforce page.

Scenario: Suppose we have a lightning component named as "xyz.cmp" with some attributes. Now we want to call this component from a VF page (CallLightingCompFromVF).

Solution:

  • First we have to create a component (xyz.cmp) with attributes let say "var1" and "var2" and these attributes have default value as "Mr." , "Mark" respectively.
<aura:component >
 <aura:attribute name="var1" type="String" default="Mr."/>
    <aura:attribute name="var2" type="String" default="Mark"/>
    Helo! {!v.var1} {!v.var2}
</aura:component>

          Now if we preview this component then, it will display "Hello! Mr.Mark" as an output.

  • Now create a lightning app called as dependency app where component (which need to be called from VF for our case xyz.cmp) dependency will be defined.

<!-- Extending from ltng:outApp adds SLDS resources to the page to allow your 
Lightning components to be styled with the Salesforce Lightning Design System (SLDS). 
If you don’t want SLDS resources added to the page, extend from ltng:outAppUnstyled 
instead. -->
<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="c:xyz"/>
</aura:application>

  • Now our aim is to call the above component from a VF page and pass different attribute's value. Let say after preview the VF (which call the above component) display or output will be "Hello! Ms.Andi
<apex:page >
    <!-- The below tag help to add lighting component to Visualforce page -->
    <apex:includeLightning />
    
    <!-- Declear a div where your lightning component will be displayed -->
    <div id="lightningDivId" />
    
    <!-- Script logic to call Lightning component from VF using a dependiecy app. -->
    <script>
        $Lightning.use("c:LigDependencyAppForVF", function() {
             $Lightning.createComponent("c:xyz",
                                           {var1 : "Ms.",
                                            var2 : "Andi"},
                                           "lightningDivId"
                                       );
            }
        );
    </script>
</apex:page>


LWC to LWC Communication using Lightning Messaging Service (Part - 2)

In my previous post ( previous post link ) we have learn how to create a Lightning Messaging Service with 6 steps and today we will use the ...