Saturday, May 18, 2019

Pass properties value from parent to child component (Parent Child Communication)

Objective of this post is to shown you how to call a child component from a parent component and also how to pass child component's property's value from parent component.

If you have existing project then you can use that or create a new project as describe in my previous post.

1. Create a child component named as "childComponent" and parent component named as "parentComponent".























2. Open "childComponent.js" file and add a string property (childComMessage) as follows,

import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api childComMessage;
}

3. Open "childComponent.html" file and modify it with below code to display childComMessage.


<template>
    {childComMessage}
</template>

4. Now we want to call this childComponent from parentComponent. So, open parentComponent.html and modify it with below code,


<template>
    <lightning-card title="Parent Component">
        <lightning-layout>
            <lightning-layout-item>
                <c-childComponent></c-childComponent>    
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

5. Now we want to pass value of "childComMessage" property of childComponent. So, modify the code base of parentComponent.html again as below,


<template>
    <lightning-card title="Parent Component">
        <lightning-layout>
            <lightning-layout-item>
                <c-child-component child-com-message="Child component property's value passing from parent component."></c-child-component>    
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

Note: 
In child component (childComponent) and it's property name is "childComMessage" and is in "CAMEL" case, but while calling it from another component, child component and it's property should be written in "KEBAB" Case.
So, childComponent (camel case) should be like child-component (kebab case).
and childComMessage (camel case) should be like child-com-message (kebab case).

6. Now to make this parentComponent available in AppBuilder/Record Page/Home Page, please update "parentComponent.js-meta.xml" file as below,

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="parentComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>   
    </targets>
</LightningComponentBundle>

7. Now deploy it to your authenticated ORG. If you are not authenticated any ORG till now then click  [Ctrl + Shift + P] and in command pallet type "Authorize an Org" and select "Authorize an Org" and from browser authenticate your destination ORG where you want to deploy parent and child component.

8. Then open any existing appBuilder / create a new one and drag the <parentComponent> in to respective column and then save and activate it. Now click the tab to show it in browser and it will look as follows,

SFDX + Visual Studio (Software Setup) + Create your first LWC component.

Please check my previous blog post (SFDX Setup Guide.) to setup SFDX,
http://sfdccodepractices.blogspot.com/2019/01/sfdx-setup-guide.html

Once you install SFDXCLI, then download Visual Studio (link: https://code.visualstudio.com/) and install Visual Studio.
Once VS is installed, open the IDE and click on "Extensions" link.
Then search for "Salesforce Extension Pack" and install the plugin.








Once "Salesforce Extension Pack" is installed successfully, then your software' configuration for your first LWC program is ready and it's time to implement your first Lightning Web Component.

1. Click => Ctrl + Shift + P  and it will open a Command Palette.







2. Type "Create Project" in Command Palette search box and select "Create Project" option and then enter.







3. Then it will ask for your project name. Enter your project name like "MyFirstLWCProject" and then click and it will redirect to your local directory, where you want to create your project.




4. Now you will see a project structure has been created and it is displayed in your EXPLORER panel. Number of files and folders will be created here, so don't panic. We will discussed these later. Just focus on your first LWC component.



















5. Now select your project "MyFirstLWCProject" and again click [Ctrl + Shift + P] and then type "Create Lightning Web Component" in Command Palette and select the "Create Lightning Web Component".





6. Then system will ask for "enter desire file name" and then type your file name like "myFirstLightningWebComponent" and enter.

7. Then system will ask for "enter desire directory". Select the default one (force-app/main/default/lwc) or just press enter.

8. So, under force-app/main/default/lwc --> a new folder will be created named as "myFirstLightningWebComponent" and also under this folder 3 files will be created as,
  • myFirstLightningWebComponent.html ==> Here you write your markup.
  • myFirstLightningWebComponent.js ==> Here you implement your client side business logic.
  • myFirstLightningWebComponent.js-meta.xml ==> Here you configure your component setup, like where you want to expose your component like under record page or under app page etc. 
You can check the files in your local directory or in explorer. If it is not reflected in explorer, then just refresh the explorer.







9. Click on myFirstLightningWebComponent.js-meta.xml and update the content as below,


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="MyFirstLightningWebComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>   
    </targets>
</LightningComponentBundle>

10. Now click on myFirstLightningWebComponent.html file and update it as below,


<template>
    <lightning-card title="Welcome To LWC World">
        <lightning-layout>
            <lightning-layout-item>
                This is my first Lightning Web Component.
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
    
</template>

11. Currently for simplicity we are not touching myFirstLightningWebComponent.js file.

12. Now its time to deploy your LWC component in your ORG. So, first select your project and then click  [Ctrl + Shift + P] and finally in command pallet type "Authorize an Org" and select "Authorize an Org" and then just enter twice (keep the section default as it is.).
It will redirect to login.salefoce.com. Enter your Org credentials. Now your component is ready to deploy in this login Org.







13. Now right click on your "myFirstLightningWebComponent" folder from explorers and then click on "SFDX:Deploy Source to Org" and if every thing is OK then your component will be deployed to your authorise Org.





















14. Once deployed successfully, then you can check your lightning component in your ORG.





















15. Go to Lighting App Builder and then create a new App Page (MyFirstLwc). Drag your "myFirstLightningWebComponent" in to "MyFirstLwc". Than save and activate it.




13. Open App Launcher and click "MyFirstLwc" and it will show your LWC component.

14. Now make this example little complex. Display some message coming from myFirstLightningWebComponent.js file. So, add a variable under myFirstLightningWebComponent.js and then access it from myFirstLightningWebComponent.html.

myFirstLightningWebComponent.js

import { LightningElement } from 'lwc';

export default class MyFirstLightningWebComponent extends LightningElement {
    message = "Enjoy Your Learning.";
}

myFirstLightningWebComponent.html

<template>
    <lightning-card title="Welcome To LWC World">
        <lightning-layout>
            <lightning-layout-item>
                This is my first Lightning Web Component.
                {message}
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
    
</template>

15. Deploy it again.

16. Run the program in browser and it will show as below output screen,


Thursday, May 9, 2019

Lightning Web Component (LWC).

What is Lightning web component?

Lightning web component is a new framework to create Lightning Component and is a custom HTML elements built using  HTML and modern JavaScript.


Advantage :
  • Low custom code is required as LWC is built on web standards for almost all of the code involved.
  • No more static resource is required. You can write reusable component (comp-1) that has no UI and then export it (comp-1) to use it (comp-1) by another component (comp-2) and to use the export component (comp-1),  just import it from another component ((comp-2) . 
  • In LWC less apex needs to write and hence calling apex is less painful experience.


Difference between Lightning Component and Lightning Web Component?
  1. The main difference is that Lightning Component is built on open source aura framework, where LWC is built on standard web technologies like HTML, modern JavaScript, CSS, XML etc.
  2. There is no import/export functionality in Lightning Component, but in LWC support import/export feature which reduce use of static resource and increase use of reusable component.

What you need to know before start LWC?
  1. SFDX.
  2. Visual Studio.
  3. Web Component.

UI part of LWC is implemented by HTML, but Salesforce Org don't support HTML, then how its work?

We can't create LWC component using Salesforce Developer Console. To create it we generally use Visual Studio IDE and use SFDX for deployment. So, when we create LWC component using Visual Studio it will create a bundle which contains HTML, JS, XML and CSS (by default).
Next step is to deploy that component in a Salesforce Org. While deploying that bundle in any Salesforce Org, Salesforce internally handle all the source code and expose only that component's name to use by user.


Web Component:
Web Components is used to create REUSABLE CUSTOM ELEMENTS. Web Component is basically consists of 3 main technologies,
  1. HTML Templates,
  2. Custom Elements,
  3. Shadow DOM

1. HTML Templates:
HTML Templates is allow us to write markup under <template> tag.

Ex. Create a html file say <index.html> and use <template> tag as below,

<template>
 <p>I am under HTML template tag.</p>
</template>

Now, execute/run this <index.html> in browser.

What is display in browser?

Expected Result: As per above html context browser should show "I am under HTML template tag." as a paragraph format.
Actual Result : Blank page. No content :(

Why browser is not showing anything?

Contents/Markup implemented under <template> tag will not rendered automatically. Actually the contents under template tag are not rendered in the DOM.
This <template> tag is part of HTML5 and is very powerful tag. This can be reused number of times (reusable) as the basis of a custom element's structure.

So, how to display the content in browser?

This template should be initiated by a JavaScript.

Example: Used the above <index.html> under a folder and modify it with a template Id as shown below,
<template id="myTemplate">
 <p>I am under HTML template tag.</p>
</template>

Now under same folder create a JavaScript file say named as "myJs.js" and fetch the template reference by template id and append it to the DOM.
Below are the sample JS code.
Example.
// newer feature
function loadTemplate1(){
 var template = document.querySelector("#myTemplate");
 var cloneTemplate = template.content.cloneNode(true);
 document.body.appendChild(cloneTemplate);
}

//older feature
function loadTemplate2(){
 let template = document.getElementById('myTemplate');
 let templateContent = template.content;
 document.body.appendChild(templateContent);
}

Now again modify the <index.html> to load the JavaScript.
<script src="myJs.js"></script>
<body onload="loadTemplate1();">
   <template id="myTemplate">
     <p>I am under HTML template tag...</p>
   </template>
</body>

Finally execute/run this index.html and it will display "I am under HTML template tag." as a paragraph format.


2. Custom Elements

This is the second part of Web Component. Here we can create our own tag and then we can use it in HTML. To build custom element, here we will use the above index.html and myJs.js file.
Suppose we want to create a custom tag named as "my-custom-tag" and want to use it under index.html. Now for simplicity let say this tag only display some string message.

So, the html is look as below,
<script src="myJs.js"></script>
<body onload="loadTemplate1();">
 <template id="myTemplate">
  <p>I am under HTML template tag...</p>
  
  <my-custom-tag></my-custom-tag>
 </template>
</body>

Now we have to create custom tag named as "my-custom-tag" under myJs.js file and the js will be as follows,

// newer feature
function loadTemplate1(){
 var template = document.querySelector("#myTemplate");
 var cloneTemplate = template.content.cloneNode(true);
 document.body.appendChild(cloneTemplate);
}

//Create a class that extends out of the box HTMLElement class.
class MyCustomTag extends HTMLElement{
 constructor(){
  super();
  
  this.innerHTML = '<p>This Message is coming from my custom tag.<p>';
 }
}

//Now define your custom tag logic under a user friendly tag.
customElements.define('my-custom-tag', MyCustomTag);

After execute/run the index.html, it will display below contents in browser.

I am under HTML template tag...

This Message is coming from my custom tag.


3. Shadow DOM

Encapsulation is an important aspect of web components. Shadow DOM can encapsulate the behavior (markup, style etc.) from main DOM.
Let take an example, take the previous example describe under Custom Element section. So, here we have 2 files index.html and myJs.js.
Under html we are using a paragraph (<p>) tag and in js file we are also using a paragraph (<p>) while creation of custom elements (my-custom-tag).

Now we want to show all paragraph contents with RED color. So, what we have to do? We have to create a CSS file (myCss.css) where we mentioned paragraph color as RED and the total code base will look like below,

index.html
<script src="myJs.js"></script>
<link rel="stylesheet" href="myCss.css">
<body onload="loadTemplate1();">
 <template id="myTemplate">
  <p>I am under HTML template tag...</p>
  
  <my-custom-tag/></my-custom-tag>
 </template>
</body>

myJs.js
// newer feature
function loadTemplate1(){
 var template = document.querySelector("#myTemplate");
 var cloneTemplate = template.content.cloneNode(true);
 document.body.appendChild(cloneTemplate);
}

//Create a class that extends out of the box HTMLElement class.
class MyCustomTag extends HTMLElement{
 constructor(){
  super();
  
  this.innerHTML = '<p>This Message is coming from my custom tag.<p>';
 }
}

//Now define your custom tag logic under a user friendly tag.
customElements.define('my-custom-tag', MyCustomTag);

myCss.css
p {
  color: red;
}

Output (red color):

I am under HTML template tag...

This Message is coming from my custom tag.

Here we have to note that we have a common CSS (myCss.css) file, which will made all paragraph's content as RED color.
Now, if we use style (paragraph color as BLUE) under custom elements, then as per Shadow DOM feature it will encapsulate main DOM RED color for paragraph.
So, result will RED color for "I am under HTML template tag..." and BLUE color for "This Message is coming from my custom tag.".

myJs.js

// newer feature
function loadTemplate1(){
 var template = document.querySelector("#myTemplate");
 var cloneTemplate = template.content.cloneNode(true);
 document.body.appendChild(cloneTemplate);
}

//Create a class that extends out of the box HTMLElement class.
class MyCustomTag extends HTMLElement{
 constructor(){
  super();
  
  this.innerHTML = "<p style='color:blue'>This Message is coming from my custom tag.<p>";
 }
}

//Now define your custom tag logic under a user friendly tag.
customElements.define('my-custom-tag', MyCustomTag);

Output:

I am under HTML template tag...

This Message is coming from my custom tag.

Monday, February 4, 2019

How to convert my existing source code retrieve by Ant migration tool to SFDX supported metadata.

1. First crate a sfdx project/workspace from CLI (Check http://sfdccodepractices.blogspot.com/2019/01/sfdx-setup-guide.html for command help. Say folder name is “SFDX_Supported_Metadata” under "D" drive. Hence project path is "D:\SFDX_Supported_Metadata".

2. After project creation system will automatically create SFDX folder and file structure. Say our project is created under "D:\SFDX_Supported_Metadata\SfdxDemo".

3. Change directory to that folder (D:\SFDX_Supported_Metadata\SfdxDemo) in CLI.

4. Now retrieve the source code using ANT migration tool. Say source code is retrieve under "D:\ANT_Supported_Metadata" folder.

5. Now run the below sfdx command for conversion (From Ant supported meta data to SFDX supported meta data).

sfdx force:mdapi:convert -r D:\ANT_Supported_Metadata

6. Once the above command will run successfully, it will put all meta-data under project root directory with suitable sfdx structure. Root directory is “D:\SFDX_Supported_Metadata\SfdxDemo\force-app\main\default”.

7. So, our structure is finally ready for SFDX use.

Thursday, January 31, 2019

How to ignore any source components to be pulled or push from or to Scratch Org?



If you check your local SFDX Project Directory, then you can see that there is a file named as ".forceignore". This file is basically used for ignore source component(s) tracking.

  • IGNORE SOURCE COMPONENT(S) FOR PULL OPERATION.
  1. If you want to ignore any file(s) to be pull from Scratch Org to your local project, then just copy paste your file name (with extension) in your ".forceignore" file. For example say you have create a class "TestIgnoreClass.cls" in your Org for any R&D purpose and you don't want to pull it in your local project, so just write the name "TestIgnoreClass.cls" under your ".forceignore" file.

  • IGNORE SOURCE COMPONENT(S) FOR PUSH OPERATION.
  1. If you want to ignore any file(s) to push from local project to Scratch Org, then you have to give absolute path of that file/folder [Path will be started from your root directory]. For example say you have a class "TestIgnoreClass.cls" in your local project and you don't want to push it to your scratch Org, then just write the path of that class "force-app\main\default\classes\TestIgnoreClass.cls" under your ".forceignore" file.

Note: If you have multiple classes to be ignore then just write down the file names (pull operation) / file or folder path (push operation) with extension and separate the file/folder by placing them in new line.

Tuesday, January 29, 2019

SFDX Setup Guide.

Goal of this post is to setup your SFDX environment and perform below activities,
  • DevHub setup,
  • Local workspace/project creation,
  • Scratch Org creation,
  • Pereform PUSH/PULL operation (deploy/retrieve) etc.

Step by step perform the below action items.


1. First you have to install sfdxcli. Download it from https://developer.salesforce.com/tools/sfdxcli (I have download here). Then install it in your machine and set your environment variable for your install sfdxcli.

2. Now open command prompt and run below command to check is it working properly.

sfdx -v

3. Now create a folder where you want to setup your local repository for sfdx operation. For my case say it under"D:\Assignments\Salesforce DX".

4. Now open CLI and change the directory location to above location using below command,

cd D:\Assignments\Salesforce DX

5. Now setup your DevHub org from where you want to create scratch Orgs. To setup an Org as DevHub run the below command in your CLI.

sfdx force:auth:web:login --setdefaultdevhubusername --setalias my-devhub-org

6. It takes few seconds and browser window will open. Put your user name and password and after successful login in browser it will show below successful message in CLI.




7. If you already login in your DevHub org, then go to setup and search for "Dev Hub" and then       enabled Dev Hub. Otherwise you will get error while try to create scratch org (explain below).



8. Now your dev hub is ready and you are ready to create your scratch org. But before create a    scratch org first create local workspace/project. And it is the location where you push or pull            your source code to your scratch org or from your scratch org respectively.
Now run the below command to create a wrokspace/project in your local directory,

sfdx force:project:create --projectname MyFirstSFDXProject


     So, a new project will be create named as "MyFirstSFDXProject" under "D:\Assignments\Salesforce DX" directory.


9. Now open the folder "D:\Assignments\Salesforce DX\MyFirstSFDXProject\config” there is a file named as "project-scratch-def.json". This json file contains scratch org information. So, you can edit this file to setup your scratch org name, edition etc.

{

    "orgName": "ArunSFDX Demo",

    "edition": "Developer",

    "orgPreferences" : {

        "enabled": ["S1DesktopEnabled"]

    }

}

10. Run the command in CLI to change the directory to your project directory which is created in point 8.

cd MyFirstSFDXProject


11. Now check your Dev Hub connection and list of scratch orgs related to this dev hub. Currently we don't have any scratch org. Run the below command for checking,
sfdx force:org:list



12. Create Scratch Org (Use the above JSON as mention in point 9) and run the below command. Here I have given my scratch org alias name as "MyScratchOrg1".
sfdx force:org:create --setdefaultusername -f config/project-scratch-def.json --setalias MyScratchOrg1

Note: If you miss to enable Dev Hub as mentioned in point 7, then you will get the below error.  So, enable your dev hub as mentioned point 7 and run the command again.




13. If the above command run successfully then CLI will show your scratch org name.


Response message:
Successfully created scratch org: 00DN0000000REujMAG, username: test-f2bwflahpmax@example.com

14. Now like point 11, you can check the dev hub connection and it's scratch org list. Currently we have one scratch org. Run the same command as mentioned in point 11.
sfdx force:org:list



15. Open your scratch org by below command (No password is here).
sfdx force:org:open
or
sfdx force:org:open -u org_alias

 (for my case it is sfdx force:org:open -u ArunSFDX Demo)



System will automatically open the scratch Org in your default browser or you can open the ORG by copy paste the displaying URL in CLI.


16. You can generate password for your scratch org.
sfdx force:user:password:generate




17. You can see the password / org details again by running below command.
sfdx force:user:display -u scratch_org_user_name
For me it like,

sfdx force:user:display -u test-f2bwflahpmax@example.com



18. Check Company Information and it is same as you mentioned in your JSON


19. As this scratch org is developer org so the storage limit is low and you can check it from “System Overview”.


20. Now try to deploy some source code in the scratch org.
  • Open your project folder (D:\Assignments\Salesforce DX\MyFirstSFDXProject) and here you get a json file named as “sfdx-project.json”.
  • Open the json file and there you get the source directory folder path, where you put your source code to deploy.

{
  "packageDirectories": [

    {

      "path": "force-app",

      "default": true

    }

  ],

   "namespace": "",

"sfdcLoginUrl": "https://login.salesforce.com",

  "sourceApiVersion": "44.0"

}
  • Suppose I want to deploy some class. So create “Classes” folder and here put your classes and their metadata. Folder and file structure is same as used on the time of ant deployment and only difference is here being no package.xml is required.
  • For our case say, I want to deploy “ToolBean.cls”.


  • Currently there is no class under scratch Org.

  • Now use below push command for deployment.
sfdx force:source:push


  • Check Org for this deployment,


  • Now suppose I have created another class (ArunSFDXDemoClass.cls) and a lightning component (ArunSFDXDemoComponent.cmp) and also modify existing class (ToolBean.cls) in scratch org and finally I want to pull it from scratch Org.



  • Now run the below command to pull the above new and modified source code.
  • sfdx force:source:pull
  • Before pull

  • After pull

  • Under classes folder


  • Under aura folder



21. Once you complete your work then logout from org. Below are the logout command,

sfdx force:auth:logout -u test-f2bwflahpmax@example.com

Data Cloud Part 6: Practical (Ingest Physical Store's Customer details and Sales details)

Hope you have already created your Data Cloud Org and also downloaded the Customer's details and Sales details from previous posts.  Now...