Monday, June 5, 2017

Lightning Component Rendering LifeCycle

Rendering LifeCycle

1. The init event is fired by the component service that constructs the components to signal that initialization has completed.

2. For each component in the tree, the base implementation of render() or your custom renderer is called to start component rendering.

3. Once your components are rendered to the DOM, afterRender() is called to signal that rendering is completed for each of these component definitions.

4. To indicate that the client is done waiting for a response to the server request XHR, the aura:doneWaiting event is fired.

5. The framework fires a render event, enabling you to interact with the DOM tree after the framework’s rendering service has inserted DOM elements. Handling the render event is preferred to creating a custom renderer and overriding afterRender().

6. Finally, the aura:doneRendering event is fired at the end of the rendering lifecycle.

Salesforce doesn't recommend using the legacy aura:waiting, aura:doneWaiting, and aura:doneRendering application events except as a last resort. The aura:waiting and aura:doneWaiting application events are fired for every batched server request, even for requests from other components in your app.

References:
https://developer.salesforce.com/blogs/developer-relations/2015/06/understanding-system-events-lightning-components-part-1.html
https://developer.salesforce.com/blogs/developer-relations/2015/06/understanding-system-events-lightning-components-part-2.html

Share This:    Facebook Twitter

Sunday, June 4, 2017

Access SOQL data in Lightning component

public class AccountContactController {
    @AuraEnabled
    public static List<Account> fetchAccount() {
        List<Account> listOfAccounts = [SELECT Name, AnnualRevenue, BillingState, (SELECT LastName FROM contacts) FROM Account LIMIT 10];
        return listOfAccounts;
    }
}

<aura:component controller="AccountContactController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="Accounts" type="Account[]"/>
    <ul>
        <aura:iteration items="{!v.Accounts}" var="account">
            <li>AccountName: {!account.Name}</li>
            <ul>
                <aura:iteration items="{!account.Contacts}" var="contact" indexVar="index">
                    <li>Contact {!index + 1} : {!contact.LastName}</li>
                </aura:iteration>
            </ul>
            <hr/>
        </aura:iteration>
    </ul>
</aura:component>

({
    doInit: function(component, event, helper) {
        var action = component.get('c.fetchAccount');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.Accounts', response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})

Share This:    Facebook Twitter

Access apex class properties in Lightning component

public class PersonController {
    @AuraEnabled public String Name {get;set;}
    @AuraEnabled public integer Age {get;set;}
    @auraEnabled public List<Account> ListOfAccounts {get;set;}
    
    @AuraEnabled
    public static PersonController initMethod(){
        PersonController person = new PersonController();
        person.Name = 'John Doe';
        person.Age = 30 ;
        person.ListOfAccounts = [SELECT Id, Name FROM Account LIMIT 10];
        return person ;
    }
}

Note the attribute personController of type PersonController.
<aura:component controller="PersonController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="personController" type="PersonController"/>
    
    <div>
        Name: {!v.personController.Name}<br />
        Age: {!v.personController.Age}<br />
    </div>
    <div>
        List of Accounts:
        <aura:iteration items="{!v.personController.ListOfAccounts}" var="account">
            <li>{!account.Name}</li>
        </aura:iteration>
    </div>
</aura:component>

({
    doInit : function(component, event, helper) {
        var action = component.get('c.initMethod');
        action.setCallback(this,function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.personController', response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
})

Share This:    Facebook Twitter

Sunday, April 2, 2017

Javascript: Functions


There are actually two literal forms of functions. The first is a function declaration, which begins with the function keyword and includes the name of the function immediately following it.
function add(num1, num2) {
   return num1 + num2;
}

The second form is a function expression, which doesn’t require a name after function. These functions are considered anonymous because the function object itself has no name. Instead, function expressions are typically referenced via a variable or property, as in this expression:
var add = function(num1, num2) {
   return num1 + num2;
};

Function hoisting

Function declarations are hoisted to the top of the context when the code is executed. That means you can actually define a function after it is used in code without generating an error.
var result = add(5, 5);

function add(num1, num2) {
   return num1 + num2;
}

Function hoisting happens only for function declarations because the function name is known ahead of time. Function expressions, on the other hand, cannot be hoisted because the functions can be referenced only through a variable. So this code causes an error:
// error!
var result = add(5, 5);

var add = function(num1, num2) {
   return num1 + num2;
};

Functions as Values

function sayHi() {
   console.log("Hi!");
}

sayHi(); // outputs "Hi!"

var sayHi2 = sayHi;

sayHi2(); // outputs "Hi!"

Parameters

You can pass any number of parameters to any function without causing an error. That’s because function parameters are actually stored as an array-like structure called arguments. The values are referenced via numeric indices, and there is a length property to determine how many values are present.
function sum() {

   var result = 0,
   i = 0,
   len = arguments.length;

   while (i < len) {
      result += arguments[i];
      i++;
   }
 
   return result;
}

console.log(sum(1, 2));       // 3
console.log(sum(3, 4, 5, 6)); // 18
console.log(sum(50));         // 50
console.log(sum());           // 0

Overloading

The fact that functions don’t have signatures in JavaScript doesn’t mean you can’t mimic function overloading. You can retrieve the number of parameters that were passed in by using the arguments object, and you can use that information to determine what to do.
function sayMessage(message) {

   if (arguments.length === 0) {
      message = "Default message";
   }

   console.log(message);
}

sayMessage("Hello!");    // outputs "Hello!"

Share This:    Facebook Twitter

Thursday, August 13, 2015

Dynamic Apex

Describe information provides metadata information about sObject and field properties. For example, the describe information for an sObject includes whether that type of sObject supports operations like create or undelete, the sObject's name and label, the sObject's fields and child objects, and so on. The describe information for a field includes whether the field has a default value, whether it is a calculated field, the type of the field, and so on.

You can describe sObjects either by using tokens or the describeSObjects Schema method.

Apex Describe Information
• Token
   • sObject
      • sObject Token
   • Field
      • Field Token

• Describe Result
   • sObject
      • sObject Describe Result
   • Field
      • Field Describe Result

Using sObject Tokens

Schema.SObjectType is the data type for an sObject token. To access the token for an sObject, use one of the following methods:

1. Access the sObjectType member variable on an sObject type, such as Account.
Schema.sObjectType t = Account.sObjectType;

2. Call the getSObjectType method on an sObject describe result, an sObject variable, a list, or a map.
Account a = new Account();
Schema.sObjectType t = a.getSObjectType();

Details on getSObjectType(): https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm#apex_System_SObject_getSObjectType

Using field Tokens

Schema.SObjectField is the data type for a field token. To access the token for a field, use one of the following methods:

1. Access the static member variable name of an sObject static type, for example, Account.Description.
Schema.SObjectField fieldToken = Account.Description;

2. Call the getSObjectField method on a field describe result.
// Get the describe result for the Name field on the Account object
Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.Name;

// Verify that the field token is the token for the Name field on an Account object
System.assert(dfr.getSObjectField() == Account.Name);

// Get the describe result from the token
dfr = dfr.getSObjectField().getDescribe();


Using sObject Describe Results

Schema.DescribeSObjectResult is the data type for an sObject describe result. To access the describe result for an sObject, use one of the following methods:

1. Call the getDescribe method on an sObject token.
Schema.DescribeSObjectResult dsr = Account.sObjectType.getDescribe();

2. Use the Schema sObjectType static variable with the name of the sObject.
Schema.DescribeSObjectResult dsr = Schema.SObjectType.Account;

Using Field Describe Results

Schema.DescribeFieldResult is the data type for a field describe result. To access the describe result for a field, use one of the following methods:

1. Call the getDescribe method on a field token.
Schema.DescribeFieldResult dfr = Account.Description.getDescribe();


2. Access the fields member variable of an sObject token with a field member variable
Schema.DescribeFieldResult dfr = Schema.SObjectType.Account.fields.Name;






Accessing All Field Describe Results for an sObject

Map representing the relationship between all the field names (keys) and the field tokens (values) for an sObject.
Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Account.fields.getMap();

Accessing All sObjects

Map representing the relationship between all sObject names (keys) to sObject tokens (values).
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();



The following algorithm shows how you can work with describe information in Apex:
  1. Generate a list or map of tokens for the sObjects in your organization.
  2. Determine the sObject you need to access.
  3. Generate the describe result for the sObject.
  4. If necessary, generate a map of field tokens for the sObject.
  5. Generate the describe result for the field the code needs to access.
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Schema.SObjectType t = gd.get('Broker__c');
Schema.DescribeSObjectResult dsr = t.getDescribe();
Map<String, Schema.SObjectField> fieldMap = dsr.fields.getMap();
Schema.DescribeFieldResult dfr = fieldMap.get('Name').getDescribe();



References:
  1. DescribeSObjectResult Class
  2. DescribeFieldResult Class
  3. http://www.swdcworld.com/2017/06/salesforce-dynamic-apex-useful-code.html
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top