Sunday 19 February 2017

jQuery code to convert table data into JSON format


Below code converts table data into JSON format.


        function actionSubmit(){
//.messager.alert('Data Saved');

$(document).ready(function(){

  ResUtilObj = {rows: []};

  $('.datagrid-btable').find('tr').each(function() {

rowObj = {};

$(this).find('td').each(function() {

rowObj[$(this).attr("Field")] = $(this).text();

});

ResUtilObj.rows.push(rowObj);

});

console.log(JSON.stringify(ResUtilObj));
});

        }


Main points on the above code

$('.datagrid-btable').find('tr').each(function() { });  - This will loop through each record in the tr tag

$(this).find('td').each(function() {}); - This will loop through each td element in the td tag

ResUtilObj represents in the main table object, it is initialized with rows array object.

rowObj = {}; represents the each field and value in the row.

ResUtilObj.rows.push(rowObj); pushes each row into rows array object

$(this).attr("Field") -  is used to read each field attribute value in the <td field=""> markup

Finally, JSON.stringify(ResUtilObj) is used to convert the array object into JSON string.



Wednesday 15 February 2017

Debug in Lightning


Enable Debug Mode for Lightning Components

Enable debug mode to make it easier to debug JavaScript code in your Lightning components.

There are two modes: production and debug. By default, the Lightning Component framework
runs in production mode. This mode is optimized for performance. It uses the Google Closure
Compiler to optimize and minimize the size of the JavaScript code. The method names and code
are heavily obfuscated.

When you enable debug mode, the framework doesn't use Google Closure Compiler so the JavaScript
code isn't minimized and is easier to read and debug.

To enable debug mode for your org:
1. From Setup, enter Lightning Components in the Quick Find box, then select
    Lightning Components.
2. Select the Enable Debug Mode checkbox.
3. Click Save.

Salesforce Lightning Inspector Chrome Extension

The Salesforce Lightning Inspector is a Google Chrome DevTools extension that enables you to navigate the component tree, inspect component attributes, and profile component performance. The extension also helps you to understand the sequence of event firing and handling.

The extension helps you to:
• Navigate the component tree in your app, inspect components and their associated DOM elements.
• Identify performance bottlenecks by looking at a graph of component creation time.
• Debug server interactions faster by monitoring and modifying responses.
• Test the fault tolerance of your app by simulating error conditions or dropped action responses.
• Track the sequence of event firing and handling for one or more actions.

Install Salesforce Lightning Inspector

Install the Google Chrome DevTools extension to help you debug and profile component performance.

1. In Google Chrome, navigate to the Salesforce Lightning Inspector extension page on the Chrome Web Store.
2. Click the Add to Chrome button.


Get a Reference to a Component in the Console
Click a component reference anywhere in the Inspector to generate a $auraTemp variable that points at that component. You can explore the component further by referring to $auraTemp in the Console tab.

These commands are useful to explore the component contents using the $auraTemp variable.

$auraTemp+""
Returns the component descriptor.

$auraTemp.get("v.attributeName")
Returns the value for the attributeName attribute.

$auraTemp.getElement()
Returns the corresponding DOM element.

inspect($auraTemp.getElement())
Opens the Elements tab and inspects the DOM element for the component.

Salesforce componentRenderer.js important notes


If you want to modify DOM elements created by the framework for a component, modify the DOM elements in the component's renderer. Otherwise, the framework will override your changes when the component is re-rendered

The lightning framework will automatically render the component so you dont have to know anything about the rendering unless you want to customize the default rendering behavior,

the base component in the framework is aura:component. Every component extends this base component.

the renderer for aura:component has 4 phases of rendering and rerendering cycles

1) render()
2) rerender()
3) afterRender()
4) unrender()

the framework calls these functions as part of rendering and rerendering lifecycles.


Rendering Lifecycle

The rendering lifecycle happens once in the lifetime of a component unless the component gets explicitly unrendered. When you create a component:

1. The framework fires an init event, enabling you to update a component or fire an event after component construction but before rendering.

2. The render() method is called to render the component’s body.

3. The afterRender() method is called to enable you to interact with the DOM tree after the framework’s rendering service has inserted DOM elements.


Rerendering Lifecycle

The rerendering lifecycle automatically handles rerendering of components whenever the underlying data changes. Here is a typical sequence.

1. A browser event triggers one or more Lightning events.

2. Each Lightning event triggers one or more actions that can update data. The updated data can fire more events.

3. The rendering service tracks the stack of events that are fired.

4. When all the data updates from the events are processed, the framework rerenders all the components that own modified data by calling each component’s rerender() method.

The component rerendering lifecycle repeats whenever the underlying data changes as long as the component is valid and not explicitly unrendered.

Create a Renderer

You don't normally have to write a custom renderer, but it’s useful when you want to interact with the DOM tree after the framework’s rendering service has inserted DOM elements. If you want to customize rendering behavior and you can’t do it in markup or by using the init event, you can create a client-side renderer.

These guidelines are important when you customize rendering.

• Only modify DOM elements that are part of the component. Never break component encapsulation by reaching in to another component and changing its DOM elements, even if you are reaching in from the parent component.

• Never fire an event as it can trigger new rendering cycles. An alternative is to use an init event instead.

• Don’t set attribute values on other components as these changes can trigger new rendering cycles.
• Move as much of the UI concerns, including positioning, to CSS.

Customize Component Rendering

Customize rendering by creating a render() function in your component's renderer to override the base render() function, which updates the DOM.

The render() function returns a DOM node, an array of DOM nodes, or nothing. The base HTML component expects DOM nodes when it renders a component.

You generally want to extend default rendering by calling superRender() from your render() function before you add your custom rendering code. Calling superRender() creates the DOM nodes specified in the markup.


render:function(cmp,helper){

var ret = this.superRender();
//do custom rendering here

return ret;

}

Rerender Components

If you update data in a component, the framework automatically calls rerender().

rerender : function(cmp,helper){

this.superRerender();

}

Access the DOM After Rendering

The afterRender() function enables you to interact with the DOM tree after the framework’s rendering service has inserted DOM elements. It's not necessarily the final call in the rendering lifecycle; it's simply called after render() and it doesn't return a value.

afterRender: function(component,helper){

this.superAfterRender();

}


Unrender Components

The base unrender() function deletes all the DOM nodes rendered by a component's render() function. It is called by the framework when a component is being destroyed. Customize this behavior by overriding unrender() in your component's renderer. This method can be useful when you are working with third-party libraries that are not native to the framework.

unrender: function(){

this.superUnrender();

}






Salesforce Lightning Components Important Points


Component Bundle

A component bundle contains component or an app and all its related resources. All resources in the component bundle  follow the naming convention  and are auto-wired. for example, a controller <componentName>Controller.js is auto-wired to its component, which means that you can use the controller within the scope of that component.


Using Expressions

expression is a placeholder for the expression.

Anything inside the {! } delimiters is evaluated and dynamically replaced when the component is rendered or when the value is used by the component. Whitespace is ignored.

The resulting value can be a primitive, such as an integer, string, or boolean. It can also be a JavaScript object, a component or collection, a controller method such as an action method, and other useful results.


Global Value Providers

globalID : 

The globalId global value provider returns the global ID for a component. Every component has a unique globalId, which is the generated runtime-unique ID of the component instance.

$Browser:

The $Browser global value provider returns information about the hardware and operating system of the browser accessing the application.

$Label:

The $Label global value provider enables you to access labels stored outside your code.

$Locale:

The $Locale global value provider returns information about the current user’s preferred locale.

$Resource:

The $Resource global value provider lets you reference images, style sheets, and JavaScript code you’ve uploaded in static resources.

Lightning Component Considerations


We recommend that you don't depend on the markup of a Lightning component as its internals can change in the future. For example, using cmp.get("v.body") and examining the DOM elements can wreak havoc should the component markup change down the road. With LockerService enforced, you won't be able to traverse the DOM for components you don't own. Instead of accessing the DOM tree, you can rely on the component tree and take advantage of value binding with component attributes. For example, you'll go far with cmp.find("myInput").get("v.name") instead of cmp.find("myInput").getElement().name.


Important Points

Add the force:appHostable interface to a Lightning component to allow it to be used as a custom tab in Lightning Experience or Salesforce1.


Configure Components for Custom Actions

Add the force:lightningQuickAction or force:lightningQuickActionWithoutHeader interface to a Lightning component to enable it to be used as a custom action in Lightning Experience or Salesforce1. You can use components that implement one of these interfaces as object-specific actions in both Lightning Experience and Salesforce1. You can use them as global actions only in Salesforce1.

Configure Components for Record-Specific Actions

Add the force:addRecordId to a lightning component to enable the component to be assigned with the Id of the currently displaying record.

force:addRecordId interface when used it adds the recordId attribute to the component. this attribute is set to the currently visible record Id.

recordId is only visible when used directly in the component. But when used inside another component this attribute will get nullified.


Add a new interface to your component

To appear in the Lightning App Builder or a Lightning Page, a component must implement the flexipage:availableForAllPageTypes interface.

Mark your resources, such as a component, with access="global" to make the resource usable outside of your own org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a Community Builder user in another org.


Add SLDS to Lightning Components

In order to add SLDS styling to lightning components which are run from developer console. add below line of code to your lightning component

<ltng:require styles="/resource/SLDS105/assets/styles/salesforce-lightning-design-system.css" />


Salesforce lightning exception handling


Below are the steps for doing exception handling in Salesforce lightning


1) Add exception message in apex controller to AuraHandledException class so that these message can be accessed in lightning component. If we use normal exception class to throw error messages from apex controller to lightning component, it is not possible. We have to use AuraHandledException class.

This AuraHandledException class can be used in controller or service layer of the apex enterprise patterns.

For Example

Apex Controller

       try{

         }
        catch(Exception e){
            AuraHandledException auraExceptionObj = new AuraHandledException(e.getMessage());
            throw auraExceptionObj;  
        }


Lightning Component


       var myAction = component.get("c.myMethod");
               
        myAction.setParams({          
            "rec": component.get("v.Account")
        });
               
       
        myAction.setCallback(this,function(response){
                       
            if(component.isValid() && response.getState() === "SUCCESS"){
             
             
               }else{
                 
                    var errors = response.getError();
                    console.log(errors[0].message);
                    component.set("v.stdExceptionMsg",errors[0].message);
             
               }          
           
        });      

            $A.enqueueAction(myAction);

In the above code errors[0].message  will fetch the error message from the AuraHandledException class.



Salesforce Apex : How to get object name from record id


Below got will get the object name based on the record id in apex.

String sObjName = myId.getSObjectType().getDescribe().getName();

In above code assign record id to myId.

Salesforce Lightning How to display error message just below the UI markup component


Below code displays error message just below the UI markup component such as text box, select list etc.


            var Error = $A.get("$Label.c.Comments_Required_Error");

            component.find("comments").set("v.errors",[{message:Error}]);


Below code snippet can be used in controller.js or helper.js to display the error message just below the component.

In the above component.find("comments") will help identify the markup component. set("v.errors",[{message:cmtError}]) is used to set the error message.



Tuesday 14 February 2017

Salesforce Lightning Show Toast Message


Below code is used to show toast message after success or failure actions. Toast can be shown as even warning messages.


                    var resultsToast = $A.get("e.force:showToast");
                    var SuccessMsg = $A.get("$Label.c.Approved_Success_Msg");
                 
                    resultsToast.setParams({
                     
                        "message": SuccessMsg,
                        "type": "success"
                     
                    });

                    resultsToast.fire();



Above code can be used in either controller.js or helper.js files. The color of the toast message will change based on the type parameter value passed to toast.

Salesforce Lightning Modal Container


Below is the code for creating custom modal in salesforce lightning.

<!-- Below lines of code in the component.cmp file -->

<div aria-hidden="true" role="dialog" class="slds-modal slds-modal--prompt slds-fade-in-hide" aura:id="accountModalDialog">  
      
        <div class="slds-modal__container">   
         
            <div class="slds-modal__header slds-theme--info">
                <h2 class="slds-text-heading--medium">Approve Transaction</h2>                
            </div>

<div class="slds-modal__content slds-p-around--medium">
                              
                         
                 <div aura:id="nameLblId" class="slds-form-element__label slds-m-top--medium slds-text-body--regular ">
                     <label class="slds-align-middle" >FullName<abbr class="slds-required" title="required">*</abbr></label>
                 </div>
                 <ui:inputTextArea class="slds-m-top--medium" aura:id="name" Label="Name" rows="3" value="{!v.Name__c}" />
                              
                              
             </div>
             <div aura:id="btnpanelId" class="slds-modal__footer">
                <ui:button class="slds-button slds-button--brand" press="{!c.SaveName}" label="Submit" />
                <ui:button class="slds-button slds-button--neutral" press="{!c.CloseWindow}" label="Cancel" />
             </div>
</div>

</div>

<!-- below button will show the modal when clicked -->

<ui:button press="{!c.showModal}" label="Show Modal>


<!-- Add below lines of code in the controller.js file -->

ShowModal : function(component, event, helper) {

        helper.showPopupHelper(component, 'accountModalDialog', 'slds-fade-in-');
helper.showPopupHelper(component,'accountModalDialog','slds-backdrop--');
       
},
   
hideModal : function(component,event,helper){
       
        helper.hidePopupHelper(component, 'accountModalDialog', 'slds-fade-in-');
helper.hidePopupHelper(component, 'accountModalDialog', 'slds-backdrop--');
     
    }

<!-- Add below lines of code in the helper.js file, this method will hide and unhide the modal on the UI -->


    showPopupHelper : function(component, componentId, className){
        var modal = component.find(componentId);
        $A.util.removeClass(modal, className+'hide');
        $A.util.addClass(modal, className+'open');
    },  
    hidePopupHelper: function(component, componentId, className){
        var modal = component.find(componentId);
        $A.util.addClass(modal, className+'hide');
        $A.util.removeClass(modal, className+'open');
       

    }


Salesforce Lightning Use of aura:if


Use of <aura:if> is very critical in salesforce lightning when displaying UI components conditionally.

 Please note the markup in the <aura:if> will not be initiated until the condition is met.

for example:

<aura:component>

<aura:if isTrue="{!v.pass}">

<ui:inputText aura:id="comments" value="{!v.passComments}" />

<aura:set attribute="else">

<ui:inputText aura:id="comments" value="{!v.failComments}" />

</aura:set>

</aura:if>

</aura:component>


In the above markup please note both the inpuText markup in if and else sections has same aura:id for comments. it is possible to use same id for inputText markup in if and else condition only because the salesforce DOM structure will not recognize the aura:id until the condition is satisfied.

This will allow us to use the same aura:id reference in controller js file. By doing this we can eliminate some extra code.


Retrieve All Picklist Values for specifid fields through APEX


Below code will retrieve all picklist values for specified fields based on specific object



    public static Map<String,List<String>> getPickListValues(){
       
        Map<String,List<String>> mapOptions = new Map<String,List<String>>();      
       
        Schema.sObjectType sobject_type = Account.getSObjectType(); 
       
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
       
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); 
       
        list<String> fieldList = new list<String> 
 {'Field1__c','Field2__c','Field3__c','Field4__c','Field5__c'};
       
        for(String s:fieldList){
           
            List<Schema.PicklistEntry> pick_list_values = field_map.get(s).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
            List<String> sOptions = new List<String>();
            for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
               
                sOptions.add(a.getValue()); //add the value and label to our final list
               
            }
           
            mapOptions.put(s,sOptions);
       
        }    
       
        return mapOptions;

}

APEX Get Record Type Details for specific object based on record type name



Below code will fetch the record type details for specific object based on record type name using APEX code

Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();

Map<String,Schema.RecordTypeInfo> rtMapByName = R.getRecordTypeInfosByName();

Schema.RecordTypeInfo rtInfo = rtMapByName.get('MyAccounts');

System.debug(rtInfo.getRecordTypeId());



Convert Salesforce object returned from Apex controller in lighting component js file into Key,Value pair

          
             
Below code details How to Convert Salesforce object returned from Apex controller into lighting component js file into Key,Value pair


       var clVar = response.getReturnValue();
                         
             var out = Object.keys(clVar).map(function(data){
                 console.log('Value of Data : ' + data);
                 if(data == "ComfortLevel"){                    
                    
                     component.set("v.comfortLevel",response.getReturnValue().ComfortLevel);
                    
                 }else if(data == "CallInter"){
                    
                                component.set("v.callInter",clVar(data));                    
                 }
                
                
                 return [data,clVar[data]];
             });
            
            
             console.log('Complete Output' + out);

             

In the above code Data is the Key/Field value returned from apex controller.
clVar(data)  - Will return the value of the field