Thursday, 31 August 2017

Salesforce - Find Object name from Record Prefix



public class SchemaGlobalDescribe{
    public static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix){
        String objectName = '';
        try{
            //Get prefix from record ID
            //This assumes that you have passed at least 3 characters
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);
           
            //Get schema information
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe();
           
            //Loop through all the sObject types returned by Schema
            for(Schema.SObjectType stype : gd.values()){
                Schema.DescribeSObjectResult r = stype.getDescribe();
                String prefix = r.getKeyPrefix();
                System.debug('Prefix is ' + prefix);
               
                //Check if the prefix matches with requested prefix
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    objectName = r.getName();
                    System.debug('Object Name! ' + objectName);
                    break;
                }
            }
        }catch(Exception e){
            System.debug(e);
        }
        return objectName;
    }
}

Tuesday, 29 August 2017

SLDS - Add Lightning component to Visualforce Page

Create a Visualforce page like this,


<apex:page sidebar="false" showHeader="false">
     <apex:includeScript value="/lightning/lightning.out.js" />
 
    <script>
        $Lightning.use("c:AssociationsApp", function() {
            $Lightning.createComponent(
                "c:customLookup",
                {
              objectAPIName:"CASE_Professional_Association__c",
              IconName:"standard:account",
              label:"Professional Association"
              },
                "profassc",
                function(cmp) {
                    console.log("Component created!");
                    console.log(cmp);
                });
             $Lightning.createComponent(
                "c:customLookup",
                {
              objectAPIName:"Lead",
              IconName:"standard:lead",
              label:"Consumer"
              },
                "Consumer",
                function(cmp) {
                    console.log("Component created!");
                    console.log(cmp);
                });
         
             $Lightning.createComponent(
                "c:customLookup",
                {
              objectAPIName:"Account",
              IconName:"standard:account",
              label:"Relation"
              },
                "relation",
                function(cmp) {
                    console.log("Component created!");
                    console.log(cmp);
                });
             $Lightning.createComponent(
                "c:customLookup",
                {
              objectAPIName:"CASE_Candidate__c",
              IconName:"standard:account",
              label:"Relation"
              },
                "candidate",
                function(cmp) {
                    console.log("Component created!");
                    console.log(cmp);
                });
            });
    </script>
    <div id="profassc"></div>
    <div id="Consumer"></div>
    <div id="relation"></div>
    <div id="candidate"></div>
</apex:page>


before that create c:AssociationsApp as follows,

<aura:application access="GLOBAL" extends="ltng:outApp" implements="ltng:allowGuestAccess">
    <aura:dependency resource="c:customLookup"/>
</aura:application>


create c:customLookup like this,

customLookup.cmp:

<aura:component controller="customLookUpController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
    <!--declare attributes-->
    <aura:attribute name="selectedRecord" type="sObject" default="{}" description="Use,for store SELECTED sObject Record"/>
    <aura:attribute name="listOfSearchRecords" type="List" description="Use,for store the list of search records which returns from apex class"/>
    <aura:attribute name="SearchKeyWord" type="string"/>
    <aura:attribute name="objectAPIName" type="string" default=""/>
    <aura:attribute name="IconName" type="string" default=""/>
    <aura:attribute name="label" type="string" default=""/>
 
    <!--declare events hendlers-->
    <aura:handler name="oSelectedRecordEvent" event="c:selectedsObjectRecordEvent" action="{!c.handleComponentEvent}"/>
    <aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
    <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
    <aura:attribute name="Message" type="String" default=""/>
 
    <!-- https://www.lightningdesignsystem.com/components/lookups/ -->
 
    <div aura:id="searchRes" class="slds-form-element slds-lookup slds-is-close" data-select="single">
        <label class="slds-form-element__label" for="lookup-348">{!v.label}</label>
        <!--This part is for display search bar for lookup-->
        <div class="slds-form-element__control">
         
            <div class="slds-input-has-icon slds-input-has-icon--right">
                <lightning:icon class="slds-input__icon slds-show" iconName="utility:search" size="x-small" alternativeText="search"/>
                <!-- This markup is for when an record is selected -->
                <div aura:id="lookup-pill" class="slds-pill-container slds-hide">
                    <span class="slds-pill" style="width:100%">
                        <span class="slds-icon_container  slds-combobox__input-entity-icon" title="record">
                            <lightning:icon class="slds-icon slds-icon slds-icon_small slds-icon-text-default" iconName="{!v.IconName}" size="x-small" alternativeText="icon"/>
                            <span class="slds-assistive-text"></span>
                        </span>
                        <span class="slds-pill__label slds-p-left_x-large">
                            {!v.selectedRecord.Name}
                        </span>
                        <button class="slds-button slds-button--icon slds-pill__remove" onclick="{!c.clear}">
                            <lightning:icon class="slds-button__icon" iconName="utility:close" size="x-small" alternativeText="search"/>
                            <span class="slds-assistive-text">Remove</span>
                        </button>
                    </span>
                </div>
                <div aura:id="lookupField" class="slds-show">
                    <span class="slds-icon_container  slds-combobox__input-entity-icon" title="record">
                        <lightning:icon class="slds-icon slds-icon slds-icon_small slds-icon-text-default" iconName="{!v.IconName}" size="x-small" alternativeText="icon"/>
                        <span class="slds-assistive-text"></span>
                    </span>
                    <ui:inputText click="{!c.onfocus}" updateOn="keyup" keyup="{!c.keyPressController}" class="slds-lookup__search-input slds-input leftPaddingClass" value="{!v.SearchKeyWord}" placeholder="search.."/>
                </div>
            </div>
        </div>
        <!--This part is for Display typehead lookup result List-->
        <ul class="slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid slds-lookup__menu slds" role="listbox">
            <center> <ui:spinner aura:id="spinner"/> </center>
            <center> {!v.Message}</center>
            <aura:iteration items="{!v.listOfSearchRecords}" var="singleRec">
                <c:customLookupResult oRecord="{!singleRec}" IconName="{!v.IconName}"/>
            </aura:iteration>
             <li role="presentation" class="slds-listbox__item" onclick="{!c.selectRecord}">
     <span id="listbox-option-unique-id-01" class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta" role="option">
              <span class="slds-media__figure">
                  <span class="slds-icon_container" title="Description of icon when needed">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="icon"/>                  
                      <span class="slds-assistive-text">Description of icon</span>
                  </span>
              </span>  
              <span class="slds-media__body">
                  <span class="slds-listbox__option-text slds-listbox__option-text_entity">New {!v.objectAPIName}</span>
              </span>
        </span>
    </li>
        </ul>
    </div>
 
</aura:component>


customLookupController.js

({
   onfocus : function(component,event,helper){
        var forOpen = component.find("searchRes");
            $A.util.addClass(forOpen, 'slds-is-open');
            $A.util.removeClass(forOpen, 'slds-is-close');
        // Get Default 5 Records order by createdDate DESC
         var getInputkeyWord = '';
         helper.searchHelper(component,event,getInputkeyWord);
    },
    keyPressController : function(component, event, helper) {
       // get the search Input keyword
var getInputkeyWord = component.get("v.SearchKeyWord");
       // check if getInputKeyWord size id more then 0 then open the lookup result List and
       // call the helper
       // else close the lookup result List part.
        if( getInputkeyWord.length > 0 ){
             var forOpen = component.find("searchRes");
               $A.util.addClass(forOpen, 'slds-is-open');
               $A.util.removeClass(forOpen, 'slds-is-close');
            helper.searchHelper(component,event,getInputkeyWord);
        }
        else{
             component.set("v.listOfSearchRecords", null );
             var forclose = component.find("searchRes");
               $A.util.addClass(forclose, 'slds-is-close');
               $A.util.removeClass(forclose, 'slds-is-open');
          }
       
},
 
  // function for clear the Record Selaction
    clear :function(component,event,heplper){
   
         var pillTarget = component.find("lookup-pill");
         var lookUpTarget = component.find("lookupField");
     
         $A.util.addClass(pillTarget, 'slds-hide');
         $A.util.removeClass(pillTarget, 'slds-show');
     
         $A.util.addClass(lookUpTarget, 'slds-show');
         $A.util.removeClass(lookUpTarget, 'slds-hide');
   
         component.set("v.SearchKeyWord",null);
         component.set("v.listOfSearchRecords", null );
         component.set("v.selectedRecord", {} );
       
    },
 
  // This function call when the end User Select any record from the result list.
    handleComponentEvent : function(component, event, helper) {
    // get the selected Account record from the COMPONETN event
       var selectedAccountGetFromEvent = event.getParam("recordByEvent");

  component.set("v.selectedRecord" , selectedAccountGetFromEvent);
     
        var forclose = component.find("lookup-pill");
           $A.util.addClass(forclose, 'slds-show');
           $A.util.removeClass(forclose, 'slds-hide');
   
     
        var forclose = component.find("searchRes");
           $A.util.addClass(forclose, 'slds-is-close');
           $A.util.removeClass(forclose, 'slds-is-open');
     
        var lookUpTarget = component.find("lookupField");
            $A.util.addClass(lookUpTarget, 'slds-hide');
            $A.util.removeClass(lookUpTarget, 'slds-show');
   
},
  // automatically call when the component is done waiting for a response to a server request.
    hideSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : false });
        evt.fire();  
    },
 // automatically call when the component is waiting for a response to a server request.
    showSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : true });
        evt.fire();  
    },
 

})


customLookupHelper.js

({
searchHelper : function(component,event,getInputkeyWord) {
 // call the apex class method
     var action = component.get("c.fetchLookUpValues");
      // set param to method
        action.setParams({
            'searchKeyWord': getInputkeyWord,
            'ObjectName' : component.get("v.objectAPIName")
          });
      // set a callBack  
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
              // if storeResponse size is equal 0 ,display No Result Found... message on screen.                }
                if (storeResponse.length == 0) {
                    component.set("v.Message", 'No Result Found...');
                } else {
                    component.set("v.Message", '');
                }
                // set searchResult list with return value from server.
                component.set("v.listOfSearchRecords", storeResponse);
            }

        });
      // enqueue the Action
        $A.enqueueAction(action);
 
},

})


customLookup.css

.THIS .leftPaddingClass {
    padding-left: 2rem;
}


selectedsObjectRecordEvent.evt

<aura:event type="COMPONENT" description="by this event we are pass the selected sObject(lookup list record) in the parent component">
    <aura:attribute name="recordByEvent" type="sObject"/>

</aura:event>


customLookupResult.cmp

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
<aura:attribute name="oRecord" type="sObject" />
        <aura:attribute name="IconName" type="string"/>
   

  <!--Register the component level event-->
    <aura:registerEvent name="oSelectedRecordEvent" type="c:selectedsObjectRecordEvent"/>

    <li role="presentation" class="slds-listbox__item" onclick="{!c.selectRecord}">
        <span id="listbox-option-unique-id-01" class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta" role="option">
              <span class="slds-media__figure">
                  <span class="slds-icon_container" title="Description of icon when needed">
                    <lightning:icon iconName="{!v.IconName}" class="slds-icon slds-icon_small" size="small" alternativeText="icon"/>
                    <span class="slds-assistive-text">Description of icon</span>
                  </span>
              </span>  
              <span class="slds-media__body">
                  <span class="slds-listbox__option-text slds-listbox__option-text_entity">{!v.oRecord.Name}</span>
              </span>
        </span>
    </li>

</aura:component>


customLookupResultController.js

({
   selectRecord : function(component, event, helper){    
    // get the selected record from list
      var getSelectRecord = component.get("v.oRecord");
    // call the event
      var compEvent = component.getEvent("oSelectedRecordEvent");
    // set the Selected sObject Record to the event attribute.
         compEvent.setParams({"recordByEvent" : getSelectRecord });
    // fire the event
         compEvent.fire();
    },

})


SvgIcon.cmp

<aura:component >
    <aura:attribute name="class" type="String" description="CSS classname for the SVG element" />
    <aura:attribute name="xlinkHref" type="String" description="SLDS icon path. Ex: /assets/icons/utility-sprite/svg/symbols.svg#download" />
    <aura:attribute name="aria-hidden" type="String" default="true" description="aria-hidden true or false. defaults to true" />
</aura:component>


SvgIconRenderer.js

({
render: function(component, helper) {
//grab attributes from the component markup
var classname = component.get("v.class");
var xlinkhref = component.get("v.xlinkHref");
var ariaHidden = component.get("v.aria-hidden");
//return an svg element w/ the attributes
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('class', classname);
svg.setAttribute('aria-hidden', ariaHidden);
svg.innerHTML = '<use xlink:href="'+xlinkhref+'"></use>';
return svg;
}
})


to display an svgicon try like,

<c:svgIcon class="slds-input__icon slds-show" xlinkHref="{!$Resource.SLDS221 + '/assets/icons/utility-sprite/svg/symbols.svg#search'}" />


customLookUpController.apxc



public class customLookUpController {
    @AuraEnabled
    public static List < sObject > fetchLookUpValues(String searchKeyWord, String ObjectName) {
        system.debug('ObjectName-->' + ObjectName);
        String searchKey = searchKeyWord + '%';
        
        List < sObject > returnList = new List < sObject > ();
      
        // Create a Dynamic SOQL Query For Fetch Record List with LIMIT 5  
        String sQuery =  'select id, Name from ' +ObjectName + ' where Name LIKE: searchKey order by createdDate DESC limit 5';
        List < sObject > lstOfRecords = Database.query(sQuery);
        
        for (sObject obj: lstOfRecords) {
            returnList.add(obj);
        }
        return returnList;
    }
}