Salesforce Organizations, Career Paths, Certifications,Creating Salesforce Account

Types of Organizations

Production Organization

Production Organizations is the one where client organization works in real time. It contains original data and actual code deployed. Users can log into the production Org at https://login.salesforce.com. All usernames must be unique across all production Orgs.

Sandbox Organization

You can create multiple copies of your production org for development, configuration, testing or training without affecting your production configuration and data.

Users can log into sandbox Organizations at https://test.salesforce.com.

Developer Organization

A developer Organization is a free, non-expiring copy of an Enterprise Edition environment that you can use to instantly start developing, testing and deploying your applications.

To sign up for Developer Organization user can log on to http://developer.force.com to get free developer edition link.

Partner Developer Organization

Partner Developer organization is a free Developer Org with more storage, features and licenses for companies who are enrolled in the partner program.

Types of Sandboxes

Developer Sandbox

A Developer sandbox is intended for development and testing in an isolated environment. A Developer Sandbox includes a copy of your production org’s configuration (metadata).

Developer Pro Sandbox

A Developer Pro sandbox is intended for development and testing in an isolated environment and can host larger data sets than a Developer sandbox. A Developer Pro sandbox includes a copy of your production org’s configuration (metadata).

Partial Copy Sandbox

A Partial Copy sandbox is intended to be used as a testing environment. This environment includes a copy of your production org’s configuration (metadata) and a sample of your production org’s data as defined by a sandbox template.

Full Sandbox

A Full sandbox is intended to be used as a testing environment. Only Full sandboxes support performance testing, load testing, and staging. Full sandboxes are a replica of your production org, including all data, such as object records and attachments, and metadata.

Creating Salesforce Account

Creating a developer edition salesforce account.

Go to  http://developer.force.com

Salesforce Career Path and Certifications

Administrators:

Salesforce Administrator

Salesforce Advanced Administrator

Salesforce Certified CPQ Specialist

Salesforce Certified Platform Application Builder

Developers:

Salesforce Certified Platform Developer I

Salesforce Certified Platform Developer II

Salesforce Certified B2C Commerce Developer

Salesforce Certified Marketing Cloud Developer

Salesforce Architect Certifications:

Certified Data Architecture and Management Designer

Certified Sharing and Visibility Designer

Certified Development Lifecycle and Deployment Designer

Certified Identity and Access Management Designer

Certified Integration Architecture Designer

Certified Mobile Solutions Architecture Designer

Salesforce consultant certifications:

Salesforce Certified Community Cloud Consultant

Salesforce Certified Sales Cloud Consultant

Salesforce Certified Service Cloud Consultant

Please check below video for more detailed explaination:

Advertisement

10 Most Important Interview Questions for Salesforce – Aura Components

1. What is difference between the way we implement VF Page and Lightning.

Visualforce Page:
VF page framework follows page-centric model as it sends that request to the Salesforce servers and then reloads the entire page with the new state of the UI(using view state) In VF page most of the processing takes place on the server-side. VF page was developed keeping in mind the desktop websites.

Lightning Component :
Aura Component framework follows App-Centric Model as most of the work is done at client side and call to server is made only when its essentially required like updating records etc. Aura Component framework was built keeping the mobile first approach.

2. What are different files in Aura Component ?

  • Component: It contains HTML like markup which is responsible for displaying UI components.
  • Controller: It handles the client side events and behaviour for UI components.
  • Helper: Helper file is used to write common logic which can be used by different controller methods.
  • Style: We can add CSS for UI components in this file.
  • Documentation: We can add comments, components description here.
  • Renderer: This file contains the default rendering behaviour of a component.
  • SVG: We can plae SVG icons here such as the icon which gets displayed before the component name in the Lightning App Builder.
  • Design: This component controls which attribute we can expose to tools like the Lightning App Builder. It helps with component re-usability.

3. What are events in Aura components ?

Events are used to provide communication between various components in Aura applications, for example passing arguments etc.

There are diffrent types of events in Aura Components :

System events like init events which are automatically triggered during component life cycles.

Component Events, Application events.

4. What are difference between Component events and Application events in Aura Components?

Component Events :

A component event can either be handled by the component itself or it can be handled by any other component which is present in the hierarchy above the component.For Example, if we have two components say parent and child, and we want to pass paramters from child to parent than, we can use component events for this.

Application Events :

Application events can be fired from any component and they can be handled by any component. No relation is required between the components, but these components must be a part of a single application. These events are essentially a traditional publish-subscribe model.

5. How to include Aura Component inside VF page?

  1. Add <apex:includeLightning/> at the beginning of your page
  2. Create an aura:application and add dependencies by extending lightning out.
<aura:application access="GLOBAL" extends="ltng:outApp">     <c:demoComp/>
</aura:application>

3. Use Lightning Application inside VF page and create the component inside it.

<apex:page standardController=”Account”>        
    <apex:includeLightning />
    <script>
        $Lightning.use(“c:demoApp”, function() {
            $Lightning.createComponent(
                “c:demoComp”,
                {},
                “test”,
                function(cmp) {
                    console.log(“Component is created!”);
              
                });
            });        
      </script>
</apex:page>

6. What are bound and unbound expression in Aura Components?

There are two ways in which we can use expression in aura components and also pass value to child component attriutes from parent components.

Below is the bound expression. If you pass the value this way, then any change to value in child component is also reflected in the parent ccomponent.

<c:child childAttr="{!v.parentAttr}" />

Below is the unbound expression. If you pass the value this way, then any change to value in child component is not reflected in the parent ccomponent.

<c:child childAttr="{#v.parentAttr}" />

7. What are Aura Methods in Aura Components?

For passing the values from child to parent or executing parent component’s logic based on certain event in child we can use component events.

But lets say, we want to pass paramters to child component from parent or want to execute certain logic of child compoent based on certain events in parent component, we can use Aura Methods for this.

ChildComponent.cmp

<aura:component>
    <aura:method name="childMethod" action="{!c.handleMethod}" access="public">
        <aura:attribute name="firstName" type="String" default="Salesforce"/> 
    </aura:method>
</aura:component>

ChildComponentController.js

({
    handleMethod : function(component, event) {
        var params = event.getParam('firstName');
        if (params) {
			console.log('First Name from parent is #' + params);
        }
    }
})

parentCmp.cmp

<aura:component>  
        <c:ChildComponent aura:id="childCmp"/>
        <lightning:button variant="brand" label="Call Child Method" onclick="{!c.callAuraMethod}" />
</aura:component>

parentCmpController.js

({
    callAuraMethod : function(component, event, helper) {
        var childComponent = component.find("childCmp");
        var message = childComponent.childMethod();
    }
})

8. If we have two components say parent and child in Aura, whose init event is fired first?

Always child init gets fired first. However, if you want to fire parent’s init first you can achieve it.

Check below link for more detailed answer on this:

https://knowledgepredator.com/2020/05/30/aura-init-execution-order/

9. Can We have two methods with same name in Controller.js and helper.js files in Aura Components?

Surprisingly, yes we can have two methods with same name in either controller or helper files. Check below link for more detailed answer on this.

https://knowledgepredator.com/2020/06/08/aura-components-interesting-scenarios/

10. What are different interfaces in Aura Components ?

Lightning Interfaces uses to allow components to be used in different contexts or enable the lightning component to receive extra context data. A Lightning component can use multiple interfaces.

Examples:

flexipage:availableForAllPageTypes component to be available for all pages.

flexipage:availableForRecordHome component to be available only on the record home page.

force:lightningQuickAction component to be used as quick action.

Lightning Web Components:@Wire and Imperative Apex Server Calls in LWC

In this post we are going to discuss about how we can make server call to the apex:method from our lightning web component. There are two ways for doing so :

First is using @wire to wire a property or a function in JavaScript to apex method and second is calling an apex method imperatively.

Using @wire to wire a property or function

  1. Make the apex method @AuraEnabled(cacheable =true)

2. Import the apex method into javascript file of your component using:

  import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod’; 

3. Wire the imported method to a property or function which will receive stream of data from the wire service.


@wire(apexMethod, {apexMethodParams})
propertyOrFunction;

Lets understand this better with implementation.

We will create a component name “getcontactComp”. In these component we will fetch the list of contacts from salesforce and display using for:each iteration and lightning card.

For fetchning the records from contact , we will write an auraenabled method similar to way in which we write for aura components.

Using @wire to wire a property.

ContactController.cls

public class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacList(){
        List<Contact> conList = [select id,lastname from contact limit 6];
        return conList;
    }
}

getcontactComp.cmp

<template>
 
        <template for:each={conList} for:item="contact">
            <lightning-card key = {contact.LastName} icon-name="standard:contact">
                <p>{contact.LastName}</p>
            </lightning-card>
        </template>
</template>

getcontactComp.js

import { LightningElement,track,wire,api} from 'lwc';
import getContacList from '@salesforce/apex/ContactController.getContacList';
export default class GetcontactComp extends LightningElement {

    @track conList ;
    @wire (getContacList) conList;
   
}

Using @wire to wire a function.

getcontactComp.js

 
import { LightningElement,track,wire,api} from 'lwc';
import getContacList from '@salesforce/apex/ContactController.getContacList';
export default class GetcontactComp extends LightningElement {

    @track conList ;
   @wire (getContacList)
    contactList({error,data}){
        if(error){
            console.log('error is#'+error);

        }
        else if(data){
            console.log('contact data#'+data);
            this.conList = data;
        }

    }
 
   
}

We will include component insde aura application and load the app. You will notice that contact details are displayed in inside lightning cards.

@wire with dynamic paramters

Call to apex method using @wire is executed at the time component loads. But suppose we want to make server call when a particular parameter changes.

So for that we can @wire an apex method with a dynamic parameter. We need to pass a parameter with “$” appended to it while making call to apex method. So, once the value of this property changes, call to apex is made at that time.

We will update the above components, and include a boolean property “showContacts”.

getcontactComp.html

<template>
    <template if:true = {showContacts}>
  
        <template for:each={conList} for:item="contact">
            <lightning-card key = {contact.LastName} icon-name="standard:contact">
                <p>{contact.LastName}</p>
            </lightning-card>
        </template>
  
    </template>
    <br>
    <lightning-input type="checkbox" label="Show Contacts" checked={showContacts} onchange={handleFlag}></lightning-input>

</template>

getcontactComp.js

import { LightningElement,track,wire,api} from 'lwc';
import getContacList from '@salesforce/apex/ContactController.getContacList';
export default class GetcontactComp extends LightningElement {

    @track conList ;
    @track showContacts = false;

    handleFlag(event){
        this.showContacts = event.target.checked;

    }
@wire (getContacList,{flag : '$showContacts'})
    contactList({error,data}){
        if(error){
            console.log('error is#'+error);

        }
        else if(data){
            console.log('contact data#'+data);
            this.conList = data;
        }

    } 
}

ContactController.cls

public class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacList(Boolean flag){
        List<Contact> conList = [select id,lastname from contact limit 6];
        return conList;
    }
}

Initially its value is kept false, so no contact list is displayed.

Once we click on “Show Contacts” button, this paramter is made true and since its value changes and it is used with @wire apex call, the @wire call is made which fetches the contact list and displays inside our component.

Imperative Apex Server Calls in LWC

Suppose you don’t want to call to an apex method when component gets loaded. You want to make call to the an apex method on click of a button or on certain logic, so for that we can make call to apex method in imperative way.

We will update our “GetcontactComp”. We will add a button “Get Contacts” to HTML file and bind it to getcontacts method in javascript file.

We will make call to apex method. Using then and catch you can get the result into your local variables as imperative call returns the promises so you have to resolve your promises into a result or error objects.

getcontactComp.html

<template> 
        <template for:each={conList} for:item="contact">
            <lightning-card key = {contact.LastName} icon-name="standard:contact">
                <p>{contact.LastName}</p>
            </lightning-card>
        </template>

   <lightning-button label="Get Contacts" onclick={getContacts}></lightning-button>
    <br>
</template>

getcontactComp.js

/* eslint-disable no-console */
import { LightningElement,track,wire,api} from 'lwc';
import getContacList from '@salesforce/apex/ContactController.getContacList';
export default class GetcontactComp extends LightningElement {

    @track conList ;
  // Using imperative call to server 
  getContacts(){
    getContacList().then(result => {
        console.log('result#'+result);
        this.conList = result;
        
    })
    .catch(error => {
        console.log('error#'+error);
       
    })
}
  
}

We will deploy the changes to salesforce org and reload the application. You can see “Get Contacts” button on screen.

Now if you click on button list of contacts will be displayed.

Thus, we can make call to apex class using @wire or imperatively based on our requirement.

So , we will wrap up this post here . Stay tuned for next posts !

Life Cycle Hooks In Lightning Web Components

A lifecycle hook is a callback method triggered at a specific phase of a component instance’s lifecycle. There are a number of life cycle hook methods available, we are going to discuss them one by one.

constructor()

  • Constructor is invoked when the component is created. It is similar to init method in aura component. Only difference here is that flow is from parent to child as opposite to that of init where the child component’s init is called first and then the parent component’s init gets called.
  • Since flow is from parent to child, do not access child elements in the component body because they don’t exist yet.
  • Also, do not access the element’s public properties , because they’re set after the component is created.
  • The constructor method’s first statement has to be super. It has to be a call to a super method with no parameters. Why it is required ? so that it can assign the proper prototype and value to “this” attribute.

connectedCallback()

  • Connectedcallback is Invoked when the component is inserted into DOM. That means whenever a component is created constructor is in invoked and whenever that component is inserted into Dom connected callback is invoked.
  • Since  flow is from parent to child, do not access child elements in the component body because they don’t exist yet.
  • We can access the Parent elements and modify them in this hook.

disconnectedCallback()

  • disconnectedCallback is invoked when component is removed from DOM.
  • This hook flows from parent to child.

render()

  • This hook is used to override the standard rendering functionality.
  • It gets called after connectedCallback() and it returns a valid HTML temaplate.
  • This hook flows from parent to child.

renderedCallback()

  • This hook is Called after component is rendered.
  • This hook flows from child to parent.

errorCallback(error, stack)

• This hook is called when the component throws an error in one of its hooks.

• The Error argument is a JavaScript native error object and the stack argument is a string.

• This method works like a JavaScript catch{} block for catching errors.

We will created two components lifecyclehooks and lifecycleChild and add above methods one by one.

lifecyclehooks.html

<template>
    <div>Inside Template 1</div>
    <c-lifecycle-child></c-lifecycle-child>
</template>

lifecyclehooks.js

import { LightningElement, api } from 'lwc';
import firsttemplate from './lifecyclehooks.html';
import secondtemplate from './lifecyclehooks2.html';
export default class Lifecyclehooks extends LightningElement {
@api templateno = 'temp1';
    constructor(){
        super();
        console.log('Inside constructor');
    }
    connectedCallback()
    {
        console.log('Inside connected callback');
    }
    disconnectedCallback(){
        console.log('Inside disconnected callback');
    }
    render()
    {
        console.log('Inside render');
        if(this.templateno==='temp1')
        return firsttemplate;
        else return secondtemplate;
    }
    renderedCallback(){
        console.log('insiderender callback');
    }
    errorCallback(error, stack)
    {
        console.log('error callback'+error);

    }
}

lifecycleChild.html

<template> 
</template>

lifecycleChild.html

import { LightningElement } from 'lwc';

export default class LifecycleChild extends LightningElement {
    connectedCallback() {
        throw new Error('Whoops!');
   }
}

We will add lifecyclehooks inside aura application and load the application. Notice the console log statements and observe the order in which each life cycle hooks gets executed.

Also, we have added the child component “lifecycleChild” to throw error from it, which is getting caught by lifecyclehooks component using errorCallback.

So , we will wrap up this post here . Stay tuned for next posts !

Communication Between Unrelated Components Using Publisher -Subscriber pattern(LWC)

In this post we are going to discuss about communication between components which are not within the same Dom tree using publisher subscriber pattern in Lightning web components.

Lets say we have two components firstly the “pubComp” component and second is a “subComp” component. “pubComp” component is a component from where we want to fire an event on certain button click or some UI event and “subComp”component is a component where we want to handle this event fired by the pub component.

  • Step 1 : Import pubsub.js into LWC project.

So for this the first thing we need to do is to include a JavaScript file name “pubsub” in your lwc directory. It is nothing but the shared JavaScript file which your two components will be using to communicate between themselvesSo for this the first thing we need to do is to include a JavaScript file name “pubsub” in your lwc directory. It is nothing but the shared JavaScript file which your two components will be using to communicate between themselves

pubsub.js

/**
 * A basic pub-sub mechanism for sibling component communication
 *
 * TODO - adopt standard flexipage sibling communication mechanism when it's available.
 */

const events = {};

/**
 * Confirm that two page references have the same attributes
 * @param {object} pageRef1 - The first page reference
 * @param {object} pageRef2 - The second page reference
 */
const samePageRef = (pageRef1, pageRef2) => {
    const obj1 = pageRef1.attributes;
    const obj2 = pageRef2.attributes;
    return Object.keys(obj1)
        .concat(Object.keys(obj2))
        .every(key => {
            return obj1[key] === obj2[key];
        });
};

/**
 * Registers a callback for an event
 * @param {string} eventName - Name of the event to listen for.
 * @param {function} callback - Function to invoke when said event is fired.
 * @param {object} thisArg - The value to be passed as the this parameter to the callback function is bound.
 */
const registerListener = (eventName, callback, thisArg) => {
    // Checking that the listener has a pageRef property. We rely on that property for filtering purpose in fireEvent()
    if (!thisArg.pageRef) {
        throw new Error(
            'pubsub listeners need a "@wire(CurrentPageReference) pageRef" property'
        );
    }

    if (!events[eventName]) {
        events[eventName] = [];
    }
    const duplicate = events[eventName].find(listener => {
        return listener.callback === callback && listener.thisArg === thisArg;
    });
    if (!duplicate) {
        events[eventName].push({ callback, thisArg });
    }
};

/**
 * Unregisters a callback for an event
 * @param {string} eventName - Name of the event to unregister from.
 * @param {function} callback - Function to unregister.
 * @param {object} thisArg - The value to be passed as the this parameter to the callback function is bound.
 */
const unregisterListener = (eventName, callback, thisArg) => {
    if (events[eventName]) {
        events[eventName] = events[eventName].filter(
            listener =>
                listener.callback !== callback || listener.thisArg !== thisArg
        );
    }
};

/**
 * Unregisters all event listeners bound to an object.
 * @param {object} thisArg - All the callbacks bound to this object will be removed.
 */
const unregisterAllListeners = thisArg => {
    Object.keys(events).forEach(eventName => {
        events[eventName] = events[eventName].filter(
            listener => listener.thisArg !== thisArg
        );
    });
};

/**
 * Fires an event to listeners.
 * @param {object} pageRef - Reference of the page that represents the event scope.
 * @param {string} eventName - Name of the event to fire.
 * @param {*} payload - Payload of the event to fire.
 */
const fireEvent = (pageRef, eventName, payload) => {
    if (events[eventName]) {
        const listeners = events[eventName];
        listeners.forEach(listener => {
            if (samePageRef(pageRef, listener.thisArg.pageRef)) {
                try {
                    listener.callback.call(listener.thisArg, payload);
                } catch (error) {
                    // fail silently
                }
            }
        });
    }
};

export {
    registerListener,
    unregisterListener,
    unregisterAllListeners,
    fireEvent
};

Lets explore the four important methods present inside this pubsub.js:


fireEvent :

The “fireEvent” method is used by the component which is supposed to fire the event and the parameter would be the page reference of a component which is
firing the event(pageRef) , the name given to the event(eventName) and whatever data the component needs to pass along with the event(payload).

registerListener :

register listener method would be used by the component which is handling the event. The parameter would be the “eventName” which will be same as
the name given earlier to the event . Next paramter is the callback method. This callback method would be any method inside the handling component which will handle the event and perform certain operations.

unregisterListener:

unregisterListener method is called by the handling component only when the component needs to unregister to the listener which it has already subscribed earlier.

unregisterAllListeners:

unregisterAllListeners removes all the listeners from the current component.

Other components will be using this library to communicate between them and other components can access this method because if you can see at the end we have exported these methods.

  • Step 2 : Publishing Event from “pubComp”
<template>
    <lightning-button label="call Event" onclick = {calEvent}></lightning-button>
</template>
import { LightningElement,wire,track } from 'lwc';
import {CurrentPageReference} from 'lightning/navigation';
import {fireEvent} from 'c/pubsub';


export default class PubComp extends LightningElement {
@wire (CurrentPageReference) pageRef;

    calEvent(event){
        var eventParam = {'firstname': 'KnowledgePredator'};
        fireEvent(this.pageRef,'pubsubevent',eventParam);

    }
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

We need to import the CurrentPageReference from lightning navigation library. CurrentPageReference will be contain the URL of our current page.

Import fireEvent from pubsub why because in the pub/sub library we have this fire event method and we have exported this method so our component can import this.

Use the fireEvent method which we have imported from our pub/sub library and pass the corresponding paramters to it.

Step 3 : Subscribe Event in “subComp”.

<template>
    <lightning-card  title = "Contact Details" icon-name="standard:contact">
        <p>{myName}</p>
    </lightning-card>
</template>
/* eslint-disable no-alert */
import { LightningElement,wire,track} from 'lwc';
import {registerListener,unregisterAllListeners} from 'c/pubsub';
import {CurrentPageReference} from 'lightning/navigation';
export default class SubComp extends LightningElement {
    @track myName = "Salesforce Predator";
    @wire (CurrentPageReference) pageRef;
    connectedCallback(){
        registerListener('pubsubevent',this.handleCallback,this);
    }

    disconnectedCallback(){
        unregisterAllListeners(this);
    }
 
    handleCallback(detail){
        alert('paramter from publisher'+ detail.firstname);
        this.myName = detail.firstname;
        
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

In the subscriber component we need to import registerListener, unregisterAllListeners methods to register and unregister to the events.

In the connected callback we need to register to the same event which we published in “pubComp”. Also we need to pass the callback method while doing this, so there we will be handling paramters recieved from publisher component.

In the disconnected callback I need to unregister this particular event using unregisterAllListeners or unregisterListener methods.

In th handleCallback we are changing the value of paramter displayed with the new value recieved from publisher component as event paramter.

Lets deploy the changed to salesforce org and include the component inside a record page.

Initially you will notice that the value insde contact details is “Salesforce Predator”. Now If you will click on that “call Event” button , Event will be fired and value will be changed to “KnowledgePredator”.

So , we will wrap up this post here . Stay tuned for next posts !

Lightning Web Components:Communication Between Components From Child to Parent using Custom Events

In this post, we are going to discuss about communication between components from child to parent using custom events. Lightning web component uses Dom event to create and dispatch events.

Suppose, I have two components parent and child. First, we need to create event in child component using custom event and then we need to give name to that particular event. While naming the event we need to adhere to Dom event standards.

  1. There should not be any uppercase letter in the event name.
  2. No spaces allowed in the name of event.
  3. Suppose there are more than two words or over more than one word then we need to separate them using underscore.

Then we need to dispatch event using dispatch event method. Further, we need to define the handler of event in parent component. Remember when
defining the handler of event in parent component we need to use on before the event name.So in our case the name of event is button click so in the handler the the name of event would be onbuttonclick and then it can be binded to a JavaScript function which will do the further operations.

Lets implement this. We will create two components : testParent and testChild and follow the above given steps.

testParent.html

<template>
   
<c-test-child my-name = {chilparam} onbuttonclick = {handleClick}> </c-test-child>

</template>

testParent.js

import { LightningElement,track } from 'lwc';

export default class TestParent extends LightningElement {

    @track chilparam = 'second';
    handleClick(event){
        alert('inside handler of parent');
        this.chilparam = 'third';
    }
}

testChild.html

<template>
    <lightning-card>
        <lightning-button label="click me" onclick = {handleMe}></lightning-button>
    </lightning-card>

<lightning-card  title = "Contact Details" icon-name="standard:contact">
    <p>{myName}</p>
</lightning-card>

    </template>

testChild.js

import { LightningElement ,api} from 'lwc';

export default class TestChild extends LightningElement {
    @api myName = 'first';


    handleMe(event){
        const childEvent = new CustomEvent('buttonclick');//Created Event
        this.dispatchEvent(childEvent); // Dispatched the Event

    }
}

If you include the testParent component inside an aura application and load the application you will see “second” inside contact details.

Now if you will click the “click me” button , alert will popup and once alert is closed the value will be changed to value set in the event handler ie “third”.

Custom Events with Parameters

Now suppose along with the event I want to pass parameters also in the child component. For that, We need to use the detail property of a custom event.

We will update the above components. In the child component , We will create two buttons: “Send Parameters” for sending single paramter to parent component and “Send Multple Parameter” for sending multiple paramaters to parent component.

Sending Single Parameter

While sending the single parameter, we need to assing the value to detail property of event and add it alng with the event name at the time of event creation.Further in the parent component handler we can access it using dot notation say using “event.detail”

Sending Multiple Paramters

Suppose We want to pass multiple parameters then how to achieve that? We have to create a json object with key as paramter name and value as value of parameter.And then we need to add that json object along with the event name while creation of event. In the parent component handler , we need to access the paramters similar to the way in which we access json paramters.(ie using dot notation)

Lets see this with implemenation.

childTest.html

<template>
    <lightning-card>
        <lightning-button label="click me" onclick = {handleMe}></lightning-button>
    </lightning-card>
    <lightning-card>
        <lightning-button label = "Send Parameters" onclick= {handleParameterEvent}></lightning-button>
    </lightning-card>
    <lightning-card>
        <lightning-button label = "Send Multple Parameter" onclick= {handlemultiparameterEvent} ></lightning-button> 
     </lightning-card>

<lightning-card  title = "Contact Details" icon-name="standard:contact">
    <p>{myName}</p>
</lightning-card>

    </template>

childTest.js

/* eslint-disable no-alert */
import { LightningElement ,api} from 'lwc';

export default class TestChild extends LightningElement {
    @api myName = 'first';


    handleMe(event){
        const childEvent = new CustomEvent('buttonclick');//Created Event
        this.dispatchEvent(childEvent); // Dispatched the Event

    }
    handleParameterEvent(event){
        const paramEvent = new CustomEvent('sendparam',
            {
                detail : 'fourth'
            });
        this.dispatchEvent(paramEvent);
    }

    handlemultiparameterEvent(event){
        const multiparam = new CustomEvent('multievent',{
            detail:{
                firstparam : 'fifth',
                secondparam: 'sixth'
            }
        });
        this.dispatchEvent(multiparam);
        
    }
}

parentTest.html

<template>
   
    <c-test-child my-name = {chilparam} onbuttonclick = {handleClick} onsendparam = {handleParam} onmultievent = {handlemultiParam}> </c-test-child>
</template>

parentTest.js

import { LightningElement,track } from 'lwc';

export default class TestParent extends LightningElement {

    @track chilparam = 'second';
    handleClick(event){
        alert('inside handler of parent');
        this.chilparam = 'third';
    }

   handleParam(event){
        var eventparameter = event.detail;
        this.chilparam = event.detail;
    }
    handlemultiParam(event){
         this.chilparam = event.detail.firstparam + ' ' + event.detail.secondparam

    } 
}

Now if you will preview the application. Initial value inside contact details would be “second”. There will be two more buttons “Send Parameters” and “Send Multiple Parameters”.

If you will click on Send Parameters , the value inside contact details will be changed to “fourth”.

If you will click on Send Multiple Parameters , the value inside contact details will be changed to “fifth sixth”.

So , we will wrap up this post here . Stay tuned for next posts !

Lightning Web Components: Communicating from Parent to Child Component in LWC

In this post we will discuss about communication between components from parent to child. For example,if on certain events in parent component, I want to pass parameter
to child component or I want to execute certain logic in child component then how will I achieve it.

Passing the property values from parent to child component

Suppose I have two components, a parent component say “testParent” and a child component say “testChild” .

In the child component, We will declare a property with @API decorator say “myName”. This means, the property can be accessed outside of this component now in the parent component. We will set default value of this property say “Salesfore Predator”.

We will pass the value to this child components property from parent ,while declaring the child component inside the parent component.

testChild.html

<template>
    <lightning-card  title = "Contact Details" icon-  name="standard:contact">
        <p>{myName}</p>
    </lightning-card>
</template>

testChild.js

import { LightningElement ,api} from 'lwc';

export default class TestChild extends LightningElement {
    @api myName = 'Salesfore Predator';
}

testParent.html

<template>
   
    <c-test-child my-name = {chilparam} </c-test-child>


</template>

Notice the case while writing the child components name inside parent component. It has to be in a kebab case, also the property’s name is to be in a kebab case only.

testParent.js

import { LightningElement,track } from 'lwc';

export default class TestParent extends LightningElement {

    @track chilparam = 'Knowledge Predator';
        }

Now if you include the testParent inside an Aura App and preview the application, you will see that value passed from parent is displayed instead as it has overridden the child components value.

Calling Child component’s method from Parent

Suppose on click of certain event, say on click of button, We want to change the value passed to the child component in above example.

So, We will make changes to above components.

In child component we will add a method say “testChildMethod” which will recieve paramter also from parent component. Remember this method has to be public ie annoted by @api so that it can be accessed by other components. This method will display alert message and change the value of our “myName” property to “Salesfore Predator” again.

testChild.html

<template>
<lightning-card>
        <lightning-button label="click me" onclick = {handleMe}></lightning-button>
</lightning-card>
</template>

testChild.js

import { LightningElement ,api} from 'lwc';

export default class TestChild extends LightningElement {
    @api myName = 'Salesfore Predator';
    @api testChildMethod(parentParam){
        alert('this is child method'+parentParam.firstname);
        this.myName = 'Salesfore Predator';
    }
}

In parent component , We will add a button , which we will bind to a javascript function and from javascript function we will make call to child components method.

testParent.html

<template>
   
    <c-test-child my-name = {chilparam}> </c-test-child>

    <lightning-button label = 'Call Child Method' onclick={handleCall}></lightning-button>
</template>

testParent.js

import { LightningElement,track } from 'lwc';

export default class TestParent extends LightningElement { handleCall(event){
      var childCompVar  = this.template.querySelector('c-test-child');
      var sendParam = {'firstname': 'Salesforce'};
      childCompVar.testChildMethod(sendParam);
          

    }
}

Notice the syntax while accessing the child component and its method in parent component javascript file.

 this.template.querySelector('div')    - >  This returns the first  div element.
 this.template.querySelectorAll()      - >   This returns array of all div elements in the component

Reload the application. Once you click on ‘Call Child Method’ , alert will pop up which displays the paramter passed from parent component.

Once you close the alert , you wil see the property value will be changed to ‘Salesforce Predator’ again.

So , we will wrap up this post here . Stay tuned for next posts !

Aura Component : Infinte Loop and Other Scenarios

If you have worked with aura components,you know we have component file, controller.js,helper.js etc. Also we have apex class with aura enabled methods where server side logic is present.

We are going to discuss some interesting stuffs here.

Calling one Controller method from another

Have you ever tried calling one method of controller file from another method in controller file itself ?
You may get into a situation where you may have to do . Definitely it is not the good practice to do it. But who cares, we are going to discuss it anyway.

We will create an aura component, lets name it as DemoBlog. We will add following code to Component and controller files:

DemoBlog.cmp

<aura:component controller="parentApex">
	
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <lightning:button variant="brand" label="Scenario 2" title="Brand action" onclick="{! c.sourceControllerMethod}" /> 

</aura:component>

DemoBlogController.js

DemoBlogController.js
({
    doInit : function(component, event, helper) {
        console.log('Inside init method');
        
    },
    sourceControllerMethod : function (component, event, helper){
        var targetMethod = component.get('c.targetControllerMethod')
        $A.enqueueAction(targetMethod);
    },
    targetControllerMethod : function (component, event, helper){
        console.log('target method called');  
    }    
})

We have created a button on click of which we have called a sourceControllerMethod method. Now our aim was to call targetControllerMethod from sourceControllerMethod.
We are accessing the targetControllerMethod using component.get(‘c.targetControllerMethod’).
And then using $A.enqueueAction(targetMethod) we are calling targetControllerMethod.
Now we will add our component into aura application and preview App.

If you click on “Scenario 2” button it will make call to targetControllerMethod evantually and display the console log in it.

So we will move on to our next point.

Infinite Loop Scenario

Have you ever got stuck in infinite loop unintentionally while developing aura components? lets see a situation where you can:

We will create an aura component, lets name it as DemoBlog. We will add following code to Component, Controller, Helper fields and Apex Classes:

DemoBlog.cmp

<aura:component controller="parentApex">
	
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <lightning:button variant="brand" label="Infinite Loop" title="Brand action" onclick="{! c.infiniteLoop}" />

</aura:component>

DemoBlogController.js

({
    doInit : function(component, event, helper) {
        console.log('Inside init method');
        
    },
    infiniteLoop : function (component, event, helper){
        alert('infiniteLoop controller method called');  
        helper.handleinfiniteLoop(component,event,helper);
        
    }  
})

DemoBlogHelper.js

({
	  handleinfiniteLoop : function (component, event, helper) {
         alert('into helper method before server call');
         var action = component.get('c.infiniteLoop');
         action.setCallback(this, function(response) {
             var state = response.getState();
             if (state === "SUCCESS") {
                 alert('return from server');
             }
         });
         $A.enqueueAction(action);
    }
})

parentApex

public class parentApex {
    @AuraEnabled
    public static string infiniteLoop(){
        return null;
    }   
}

Now we will add our component into aura application and preview the Application.If you click on “Infinite Loop” button , surprisingly you will notice never stoping alerts of controller and helper methods popping up one after another.

Why ? If you have observed carefully, the name of both controller file method and apex class method is same. (infiniteLoop in above example).
So instead of calling the server side method from helper, it ends up calling controller side method. (Notice the syntax for calling one controller method from another. Quite Similar? ).

So be careful while naming the methods from next time !

Aura Components: Two methods with same name in controller or helper files.

If you have worked with aura components,you know we have component file, controller.js, helper.js etc. Also we have apex class with aura enabled methods where server side logic is present.

We are going to discuss some interesting stuff here !

Have you ever tried having two methods with same name in controller.js file or helper.js file in your aura components?

Do you think salesforce will allow me to save the file in such scenarios ?

Or if it allows, will it give some error on load of component or if that method is called from some where?

Lets check this.

We will create an aura component, lets name it as DemoBlog. We will add following code to Component and controller files:

DemoBlog.cmp

<aura:component controller="parentApex">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
<lightning:button variant="brand" label="Scenario 1" title="Brand action" onclick="{! c.handleClickCtrl}" />
    
</aura:component>

DemoBlogController.js

({
    doInit : function(component, event, helper) {
        console.log('Inside init method');
        
    },
    handleClickCtrl : function (component, event, helper) {
        console.log('Inside handle Click controller first');
    },
    
    handleClickCtrl : function (component, event, helper) {
        console.log('Inside handle Click controller second');
    },
    
})

You will notice we are able to save two functions with same name in controller file.

We have created a button on click of which we have called a handleClickCtrl mtethod. But wait, we have two methods of name handleClickCtrl in controller file. Now we will add our component into aura application and preview the Application. You will notice no error on application loadding !

If you click on Scneario 1 button and observe the console log.You will see the console log statement of second method will be displayed. Again no error !

What do you think is happenig over here. If you will closely observe the format of controller file or helper file in aura component, you will definitely get some idea.

Yes, it is nothing but a json format.
And What happens if you have two keys with same name in JSON string. If you try to access it, it doesn’t give error, moreover, the second key always overrides the first one and if you try to access the key, it will always return value corresponding to second key.

{name: “Demo”, age: 31, city: “New York”,name :”Demo2″} – This is valid JSON.

Similarly, we can have two methods with same name and same paramters in helper.js file also.

Stay tuned for more such interesting scenarios !