How to read Page Layout in LWC?

In this section, we will learn how to use getRecordUi in our Lightning Web Component(LWC).
We will build one LWC by which we can show Account Information by using the same Account record id for learning purposes. We will do this by “getRecordUi” function.

Basically, getRecordUi is used to get metadata information of the records in Salesforce. By this function, we will read the Account Page Layout and read the value of some fields present in that Page Layout.

So, we have created one LWC named “showAccountInfobyRecordUi”.

Step 1: Update showAccountInfobyRecordUi.xml file to enable the LWC for Lightning Pages.

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

Step 2: Need to update showAccountInfobyRecordUi.js file as per following code snippet

import { LightningElement, api, wire } from "lwc";
import { getRecordUi } from "lightning/uiRecordApi";

export default class ShowAccountInfobyRecordUI extends LightningElement {
  @api recordId;
  accountName;
  accountNumber;

  @wire(getRecordUi, {
    recordIds: "$recordId",
    layoutTypes: "Full",
    modes: "View",
  })
  wiredRecord({ error, data }) {
    if (data) {
      this.accountName = data.records[this.recordId].fields["Name"].value;
      this.accountNumber =
        data.records[this.recordId].fields["AccountNumber"].value;
    } else{
      // TODO: Data handling
    }
  }
}

We need to maintain the following steps to use “getRecordUi” function.

  • First, we need to import “getRecordUi” from “lightning/uiRecordApi”.
  • Next, we need to invoke “getRecordUi” method using the wire adapter and we need to pass the layout type and mode as described in the code snippet. This will return the value of all the fields resides in the Page Layout.
    • layout types can be ‘Compact’ or ‘Full’ and modes can be ‘Create, ‘Edit’ or ‘View’
  • Here, we want to fetch Account Name from the fields returned by this getRecordUi function by writing this code:
    data.records[this.recordId].fields["Name"].value
  • We are able to access fields from the Account Page Layout by using the “getRecordUi” function.

Step 3: Now, we have to update the showAccountInfobyRecordUi.html file to show the Account Name and Account Number.

<template>
  <lightning-card title="Account Information">
    <lightning-layout>
      <lightning-layout-item padding="around-small">
        Account: {accountName} <br />
        Account Number: {accountNumber}
      </lightning-layout-item>
    </lightning-layout>
  </lightning-card>
</template>

Step 4: Place this component in any Account record page and we will get this following output

2,520 total views, 9 views today

Posted in Lightning Web Component, Salesforce Lightning | Comments Off on How to read Page Layout in LWC?

How to increase the width of Quick Action and call the LWC from Quick Action?

Problem Statement: In many projects, I got the requirement to call the Lightning Web Component from Quick Action, but the width of that Lightning Web Component is almost 80% of the screen. How can you accomplish this?

Solution: We all know how to invoke Lightning Web Component from Lightning Aura Component which can be associated with the Quick Action in Salesforce Lightning Experience. Now, if we will open any Quick Action settings, we can update the height of the standard quick action modal as per business requirement, but what we will do if we have to increase the width of the standard quick action modal. Here is the solution.

If we will try to use standard slds class such as “slds-modal_container, we can increase the width of the standard quick action modal, but in this case, other modals such as Edit or any other quick action will be affected. So, we should not consider this approach.

First, we will try to hide the Standard Quick Action Modal and at the same time we will invoke the Lightning Web Component using lightning:overlayLibrary with attaching the standard cssClass as “slds-modal_large“.

We will describe this with an easy example. Let’s say, we want to show a greeting message from a Quick Action on the Lease Record Detail Page.

Step 1: We will create two components such as Aura Component and Lightning Web Component. First, we will create a Lightning Web Component named “greeting” in which will show the greeting message such as

greeting.html

<template>
    <lightning-card title="Welcome My Friends">
        <lightning-layout>
            <lightning-layout-item flexibility="auto" padding="around-small"> 
                
<div class="contentClass">                   
                    I hope you are doing well.
                </div>

            </lightning-layout-item>
        </lightning-layout>      
    </lightning-card>
</template>

we don’t need to write anything in js or xml file. Because we will call this component from the Aura Component which will be associated with the Quick Action in Salesforce Lightning.

Step 2: Create a Lightning Aura Component named “showMessage” which will be associated with the Quick Action.

showMessage.cmp

<aura:component implements="force:lightningQuickActionWithoutHeader"> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
    <lightning:overlayLibrary aura:id="overlayLib"/>
</aura:component>

If you see, we have used standard lightning:overlayLibrary to open a modal when the user will click on Quick Action.

showMessageController.js

({
    doInit : function(component, event, helper) {        
        var modalBody;
        
        setTimeout(()=>{  
            // Priority -> 1 || Please check if it will not work, consider Priority 2.
                //$A.get("e.force:closeQuickAction").fire(); 
        
            //Priority -> 2
                var stdModal = document.getElementsByClassName("uiModal forceModal");    
                stdModal.forEach(function(a, b) {
                $A.util.addClass(a, "slds-hide");
                });        
        },10);  
    
        $A.createComponent("c:greeting", {},
        function(content, status) {
            if (status === "SUCCESS") {
                modalBody = content;
                component.find('overlayLib').showCustomModal({
                    header: "Greeting Message",
                    body: modalBody,
                    showCloseButton: true,
                    cssClass: "slds-modal_large",
                    closeCallback: function() {                       
                    }
                })
            }
        });  
    }                
})

Now, we will discuss about two operations such as setTimeOut() and $A.createComponent() used in doInit() method.

setTimeOut(): We are hiding the standard quick action modal by applyting “slds-hide” class to the standard quick action modal class in 10ms. However, please try this standard quick action closure function

$A.get("e.force:closeQuickAction").fire();

first, if it will not work then use the “slds-hide” class to the standard quick action modal class as the second approach.

$A.createComponent(): We are calling our “greeting” component using this function with lightning:overlayLibrary. We have set the cssClass as “slds-modal_large” to increase the width of the modal in where Lightning Web Component will be invoked.

Step 3: Now, we will attach this Lightning Aura Component to the Quick Action of Lead Object(for example).

Quick Action: Show Message

 

 

 

 

 

 

 

 

 

 

Place this Quick Action into the Lead Page Layout.

Result: Open the Lead record and click on “Show Message” quick action, you can see the greeting Lightning Web Component Modal window on the detail page as per the following image. Actually, when it’s opened, in backend standard quick action modal is disappeared.

 

Thanks for your time!!

6,844 total views, 12 views today

Posted in Lightning Components, Lightning Experience, Lightning Web Component, Salesforce Lightning | Leave a comment

Include SLDS into LWC Open Source Application

In this tutorial, we will see how to include Salesforce Lightning Design System(SLDS) component into the LWC Open Source Application. But, before this, please complete this previous tutorial.

As per the previous tutorial, we already have created a customer-service-app using LWC Open Source framework where we are showing all Case Records from Salesforce. But, We have not applied SLDS into this application. Now, we will see how to include SLDS into this LWC Open Source application. Let’s start.

Step 1: Open customer-service-app in VS Code.

Step 2: Please install @salesforce-ux/design-system node modules to load all the SLDS Styles into your project by executing the following command from the terminal of the VS Code.

npm install @salesforce-ux/design-system

After the execution of this, we can see the dependencies in package.json file.

Step 3: Before applying SLDS into our application, first we have to understand the difference between native shadow DOM and synthetic shadow DOM for LWC.

Native Shadow DOM: Native Shadow DOM is by default enabled in LWC Open Source. Basically, we are calling app component from index.html in this project. So, If we will include the SLDS styles using tag in the header of our index.html file, the immediate app.html can get all the SLDS Styles, but this is the wrong statement. app.html can not inherit the styles applied for the parent html i.e., index.html file. Because, Native Shadow DOM encapsulates all our components in the application that means every component can define its own style.

Synthetic Shadow DOM: This is the exception of Native Shadow DOM means it will not encapsulate all the components. So, app.html can inherit the styles applied for the parent html i.e., index.html file.

First, we will apply Synthetic Shadow DOM. Then, we will learn about Native Shadow DOM.

Step 4: Need to install @lwc/synthetic-shadow node module from the terminal of the VS Code to enable synthetic shadow DOM.

 npm install @lwc/synthetic-shadow 

Step 5: Open lwc-services.config.js file and include the exact directory for salesforce-lightning-design-system.css file in this way.

// Find the full example of all available configuration options at
// https://github.com/muenzpraeger/create-lwc-app/blob/master/packages/lwc-services/example/lwc-services.config.js
module.exports = {
    resources: [{ from: 'src/client/resources', to: 'dist/resources/' },
    {
        from: 'node_modules/@salesforce-ux/design-system/assets',
        to: 'src/SLDS'
    },
    {
        from: 'node_modules/@salesforce-ux/design-system/assets',
        to: 'dist/SLDS'
    }
],
    sourceDir: './src/client',
    moduleDir: './src/client/modules',
    devServer: {
        proxy: { '/': 'http://localhost:3002' }
    }
};

Here, you can see that program will create new src/SLDS directory where all SLDS style files will be there.

Step 6: Open src\client\ index.js file and import @lwc/synthetic-shadow into this file just like:

import '@lwc/synthetic-shadow';
import { createElement } from 'lwc';
import MyApp from 'my/app';

const app = createElement('my-app', { is: MyApp });
// eslint-disable-next-line @lwc/lwc/no-document-query
document.querySelector('#main').appendChild(app);

Step 7: Open src\client\index.html file and include the salesforce-lightning-design-system.css file using link tag in the header of the html file.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Customer Service Application</title>
        <style>
            body {
                font-family: Arial, Helvetica, sans-serif;
            }
        </style>
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <link rel="shortcut icon" href="/resources/favicon.ico" />
        <link rel="stylesheet" type="text/css" href="/SLDS/styles/salesforce-lightning-design-system.css" />
    </head>
    <body>        
        <div id="main">

        </div>       
    </body>
</html>

Step 8: Now, we need to include SLDS styles into our html table of the src\client\modules\my\app\app.html file.

<template>
    <header>
        <img src="resources/lwc.png" alt="App logo">
        <h2>Customer Service Application</h2>
    </header>

    <!-- Page code -->
    <main class="content">
        
            <!--<input type="search" placeholder="Search contacts..."
                    oninput={searchdata} />-->

            <table class="slds-table slds-table_cell-buffer slds-table_bordered">
                <thead>
                    <tr class="slds-line-height_reset">
                        <th scope="col">
                            <div class="slds-truncate">
                                <input type="checkbox"></input>
                            </div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Name">Case Number</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Subject">Subject</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Status">Status</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Priority">Priority</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Created Date">Created Date</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Closed Date">Closed Date</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template for:each={cases} for:item="cs">
                        
                            <tr key={cs.id}>
                                    <th scope="col">
                                        <div>
                                            <input type="checkbox" value={cs.CaseNumber} data-id={cs.id}></input>
                                        </div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.CaseNumber}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.Subject}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.Status}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.Priority}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.CreatedDate}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.ClosedDate}</div>
                                    </th>
                                </tr>


                    </template>
                </tbody>
            </table>

       
    </main>
</template>

Step 9: So, now app.html can use the SLDS component from the salesforce-lightning-design-system.css file declared in index.html file. This is possible by applying Synthetic Shadow DOM.

Step 10: Run the command from the terminal of the VS Code as

 npm run watch 

and we will get the output at http://localhost:3001 as the Case records are visible in the table using SLDS styles as per the following image:

 

Good Job! Now, you have successfully included SLDS Styles into the customer-service-app built by LWC Open Source framework.

But, we have done this by Synthetic Shadow DOM which is not enabled by default in LWC Open Source. Let’s try the same thing with Native Shadow DOM into the next tutorial.

 

3,294 total views, 27 views today

Posted in Lightning Web Component Open Source, Salesforce Lightning | Leave a comment

Connect Salesforce from LWC Open Source Application

Please complete the previous tutorial about building a simple application by LWC Open Source.

Our object is that customer-service-app will show the Case records from Salesforce. Already, we have created customer-service-app as per the previous tutorial. Now, we have to connect to Salesforce to get the Case records and we have to upgrade the UI layer for our customer-service-app.

Step 1: Please open the customer-service-app in VS Code and you will get this type of project structure.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Step 2: Before updating any file, let’s discuss the importance of some existing files.

  • api.js: We can see the api.js in this path src/server. This js file helps to execute this customer service application in the localhost or event in a specific port.
  • lwc-services.config.js: We can see this file in the root directory of this project. This file defines the path for the resources, sourceDir, moduleDir. So, system will understand the executable files.
  • index.html:  We can see the index.html page in this path src/client. This html is the starter page of the application. From this html file we will call our lwc template by index.js.
  • index.js: We can see the index.js in this path src/client.  This js file helps to call our lwc template named “app” during running of the application.
  • app folder: We can get this folder in this path src/client/modules/my. This folder contains app.html and app .js file where we will write our business logic.
  • greeting folder: We can also get this folder in this path src/client/modules/my. This is invoked from app.html file. This folder contains greeting.html and greeting.js file to show the greeting message by default.
  • package.json: At last, we can see the information related to installed node modules in dependencies and devDependencies tag and how can we run the application using npm run watch.

Take time. No hurry. I would like to request you please see the above-mentioned files carefully before we will change the code to fulfill the business objective of our customer-service-app.

Step 3: First we will create a folder named “data” under this path src/client/modules. In this data folder, please create another folder called “caseServices“.  In this “caseServices” folder, please create a caseServices.js file. So, now, the module looks like:

 

 

 

 

 

Step 4: Please update the following code snippet for the customerServices.js file.

const URL = '/api/cases';
let cases = [];
export const getCases = () => fetch(URL)
  .then(response => {
    if (!response.ok) {
      throw new Error('No response from server');
    }
    return response.json();
  })
  .then(result => {
    cases = result.data;
    return cases;
  });

Step 5: Please execute this command from the terminal of the VS Code.

npm install jsforce dotenv

This will help to install the jsforce node modules to build communication with Salesforce and dotenv node modules to work with environment files. After successful execution, you can see the dependencies of package.json file looks like:

 

 

 

 

 

Step 6: Please create a new file named “.env” in the root directory of the project just like

SF_LOGIN_URL=LOGIN_URL
SF_USERNAME=YOUR_USERNAME
SF_PASSWORD=YOUR_PASSWORD  
SF_TOKEN=YOUR_SECURITY_TOKEN

This “.env” files contains credential information to log into Salesforce Instance. So, please fill up the correct information.

Step 7: Now, we will update the api.js file under the path src/server. So, please update the api.js file in this following code snippet.

// Simple Express server setup to serve for local testing/dev API server
const compression = require('compression');
const helmet = require('helmet');
const express = require('express');

const jsforce = require('jsforce');
require('dotenv').config();
const { SF_USERNAME, SF_PASSWORD, SF_TOKEN, SF_LOGIN_URL } = process.env;
if (!(SF_USERNAME && SF_PASSWORD && SF_TOKEN && SF_LOGIN_URL)) {
    console.error(
        'Cannot start app: missing mandatory configuration. Check your .env file.'
    );
    process.exit(-1);
}
const conn = new jsforce.Connection({
    loginUrl: SF_LOGIN_URL
});
conn.login(SF_USERNAME, SF_PASSWORD + SF_TOKEN, err => {
    if (err) {
        console.error(err);
        process.exit(-1);
    }
});


const app = express();
app.use(helmet());
app.use(compression());

const HOST = process.env.API_HOST || 'localhost';
const PORT = process.env.API_PORT || 3002;

app.get('/api/cases', (req, res) => {
    const soql = `SELECT Id, CaseNumber, Subject, Status, Priority, format(CreatedDate) formattedCreatedDate, format(ClosedDate) formattedClosedDate FROM Case`;
    
    conn.query(soql, (err, result) => {
        if (err) {
            res.sendStatus(500);
        } else if (result.records.length === 0) {
            res.status(404).send('Session not found.');
        } else {
            const formattedData = result.records.map(caseRecord => {
                let cases = [];
                return {
                    id: caseRecord.Id,
                    CaseNumber: caseRecord.CaseNumber,
                    Subject: caseRecord.Subject,
                    Status: caseRecord.Status,
                    Priority: caseRecord.Priority,
                    CreatedDate: caseRecord.formattedCreatedDate,
                    ClosedDate: caseRecord.formattedClosedDate,
                    cases
                };
            });
            res.send({ data: formattedData });
        }
    });
});

app.listen(PORT, () =>
    console.log(
        `✅  API Server started: http://${HOST}:${PORT}/api/v1/endpoint`
    )
);

Step 8: Now, we will update the app.html,app.js and app.css files under this path src/client/modules/my/app.
So, update the app.js file first:

app.js

import { LightningElement, track } from 'lwc';
import { getCases } from 'data/caseServices';

export default class App extends LightningElement {
    @track cases = [];

   connectedCallback() {
        getCases().then(result => {
        this.cases = result;
        });
    }

}

app.html

<template>
    <header>
        <img src="resources/lwc.png" alt="App logo">
        <h2>Customer Service Application</h2>
    </header>
    <!-- Page code -->
    <main class="content">      
            <table>
                <thead>
                    <tr>
                        <th scope="col">
                            <div>
                                <input type="checkbox"></input>
                            </div>
                        </th>
                        <th scope="col">
                            <div title="Name">Case Number</div>
                        </th>
                        <th scope="col">
                            <div title="Subject">Subject</div>
                        </th>
                        <th scope="col">
                            <div title="Status">Status</div>
                        </th>
                        <th scope="col">
                            <div title="Priority">Priority</div>
                        </th>
                        <th scope="col">
                            <div title="Created Date">Created Date</div>
                        </th>
                        <th scope="col">
                            <div title="Closed Date">Closed Date</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template for:each={cases} for:item="cs">                        
                            <tr key={cs.id}>
                                    <th scope="col">
                                        <div>
                                            <input type="checkbox" value={cs.CaseNumber} data-id={cs.id}></input>
                                        </div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.CaseNumber}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.Subject}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.Status}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.Priority}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.CreatedDate}</div>
                                    </th>
                                    <th scope="col">
                                        <div>{cs.ClosedDate}</div>
                                    </th>
                                </tr>
                    </template>
                </tbody>
            </table>       
    </main>
</template>

app.css

.content {
    padding-top: 2rem;
    padding-left: 2rem;
    padding-right: 2rem;
    padding-bottom: 2rem;
}
header {
    padding: 1rem;
    display: flex;
    color: #ffffff;
    background: #0288d1;
    box-shadow: 0 4px 3px rgba(1, 87, 155, 0.5);
    align-items: center;
}
header img {
    height: 3rem;
    margin-right: 0.3rem;
}
header h2 {
    font-size: 1.75rem;
    font-weight: 300;
}

Step 9: Now, we will delete the unused folder or files. We can delete greeting folder as there is no dependency on this folder for our customer-service-app. We can delete “__tests__” folder as we will not work on this at this moment. So, the entire src structure looks like:

 

 

 

 

 

 

 

Step 10: Now, run the command

npm run watch 

from the terminal of VS Code and you will get the output at http://localhost:3001

 

Fantastic! you have successfully communicated with Salesforce for this LWC Open Source app.

In this example, we can see all the Case records into our own customer-service-app, but the UI doesn’t look good. Something is missing. Yes, you are right. Still, we have not applied Salesforce Lightning Design Styles. Let’s focus this into the next tutorial.

1,488 total views, 9 views today

Posted in Lightning Components, Lightning Web Component Open Source | Leave a comment

Build a simple application by LWC Open Source

In the previous articles, we have seen how to create simple node application with express server. Now, we will see how to create a simple application using Lightning Web Component(LWC) Open Source.

In this tutorial, we will try to host an application for Customer Service Programme. So, please maintain the following steps:

Step 1: Still, if you have not installed Node.js please install it first.  After that please set the environment variable for Node JS framework.

Step 2: Please open a command line or terminal and point to any drive.

Step 3: Just write down this line

 npx create-lwc-app customer-service-app 

Here, customer-service-app is our application name.

Step 4: During the execution of this command, please enter the necessary information as per the following image:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

It will take a few minutes to create a customer-service-app using LWC Open Source.  And, you will get this confirmation.

Step 5: Now, open this application customer-service-app from Visual Studio Code.

Step 6: Please execute the following command from the terminal of your VS Code or command line to see the result:

npm run watch

 

 

 

Step 7: Now, if we will run this URL: http://localhost:3001, we will get the result:

 

 

Amazing! Now, we are able to create and execute a simple application using Lightning Web Component Open Source.

Special Thanks to Salesforce to help us to create an application using Lightning Web Component Open Source in a very short time.

2,001 total views, 9 views today

Posted in Lightning Components, Lightning Web Component Open Source | Leave a comment

How to use SLDS in Node JS?

In this tutorial, we will see how can we include Salesforce Lightning Design System (SLDS) component into a node application. But, before this please read this blog (Build Simple Application by Node JS) first.

In the previous blog (Build Simple Application by Node JS), we have seen how will we execute a simple node application by express server framework. Now, we will include SLDS component into the same application. So, please maintain all the following steps:

Step 1: Open VS Code and open the same folder named “simple-node-app“.

Step 2: Open the terminal from your VS Code by using Shortcut Key (ctrl + `) (for windows).

Step 3: Now, we will install SLDS Library into the node_modules folder by executing the following command from the terminal of VS Code.

 npm install @salesforce-ux/design-system 

Step 4: After installation, you can see that dependency files are upgraded with @salesforce-ux/design-system in package.json file as per the following image.

 

 

 

 

 

 

 

 

 

 

We can get all the SLDS details from this url: https://lightningdesignsystem.com

Step 5:(optional): Please create a .gitignore file in the project’s root directory. This file will direct
the respective files/modules to be ignored during git push process. Here, we don’t want to push the “node_modules” folder in GIT repository. So, we will update the .gitignore file in this way:

# Tooling files
node_modules

Step 6: Create an index.html file in the project’s root directory with the following code snippet:

<html lang="en">
    <head>
        <title>HTML with SLDS by Node</title>
    </head>
    <body style="background-color:rgb(243, 242, 243)">    
       <div class="slds-card">          
          <div class="slds-p-around_medium">Hello World!</div>
       </div>
    </body>
</html>    

We will just show the “Hello World!” message.

Step 7: Now, the structure of our project looks like:

 

 

 

 

 

Step 8: Now, open the index.js file and update the code snippet with the following lines:

const express = require('express');
const app = express();
const path = require('path');
 
var PORT = process.env.port || 3001;

const SLDS_DIR = '/node_modules/@salesforce-ux/design-system/assets';

app.use('/slds', express.static(__dirname + SLDS_DIR));
 
app.get('/', function (req, res) {
  //res.send('Hello World!');
  res.sendFile(path.resolve('index.html'));
});

app.listen(PORT, function () {
  console.log(`App listening on port ${PORT}`);
});

Here, you can see we have changed multiple lines. Let’s discuss one by one:

  • We have declared a constant variable named “SLDS_DIR” where we have given the pathname in which salesforce-lightning-design-system styles folder exists.
  • Next, we are passing this variable in express.static() method with “__dirname” to declare the “/slds” path at line no. 9. So, for the next time, in the html file, if we need to call the salesforce-lightning-design-system.css we only need to use “/slds/styles/salesforce-lightning-design-system.css“.
  • In the next step, we will call our index.html file by using the following syntax: res.sendFile(path.resolve(‘index.html’));

Step 9: Now, run the application by executing this command

 node index.js 

from the terminal of the VS Code. The application will be hosted on localhost:3001.

So, we will get the output in this url: http://localhost:3001 as per the following image

Oh no! But, we are not getting the styles from SLDS. Something is missing.
Don’t worry! Let’s execute the next Step.

Step 10: Please link the salesforce-lightning-design-system.css file in the header of the html file just like:

<html lang="en">
    <head>
        <title>HTML with SLDS by Node</title>
        <link rel="stylesheet" type="text/css" href="/slds/styles/salesforce-lightning-design-system.css" />
    </head>
    <body style="background-color:rgb(243, 242, 243)">    
       <div class="slds-card">          
          <div class="slds-p-around_medium">Hello World!</div>
       </div>
    </body>
</html>

Now, refresh your browser or executing this url: http://localhost:3001 again to see the correct output as per the following image

WOW! Now, we can see the “Hello World” message with SLDS design in SLDS card. Enjoy!!

2,637 total views, no views today

Posted in Lightning Components, Lightning Web Component Open Source | Leave a comment

Build simple application by Node JS

In this session, we will learn how to develop a simple Node.JS application with express.js web application framework.

I thought before starting about Lightning Web Component Open Source, we need to learn about Node JS and other certain useful libraries. Let’s start:

Node JS was written by Sir Ryan Dahl in 2009 [wiki]. Node JS is not a programming language. It’s an open-source, cross-platform javascript run time environment that executes javascript code outside a web browser. Node JS supports event-driven architecture and also supports asynchronous I/O framework. Developers also can build server-side scripting by this Node JS. It’s built on the basis of Google’s V8 JavaScript engine.

Now, we will create a simple “Hello World” app which will be executed by server-side scripting.

So, please follow the mentioned steps.

Step 1: Install Node.js. If you have not installed earlier, please install node.js from this link.

Step 2: Please set the environment variable for Node JS.

Step 3: Please check the version for node and npm from command prompt with the following syntax.
npm(Node Package Manager) which manages all the packages/extensions developed by node.js to install in your local repository.

 

 

 

Step 4: Create a new folder. Let’s say, I have created a new folder named “simple-node-app”.

Step 5: Now, we will create a project for the node using this initializing command from the command prompt of the same project directory.

npm init

It will ask you to provide the following information as per the following image. For now, just you can press enter to set the default for all the line items. After executing this command, it will create a package.json file and it will install all node js dependency frameworks/libraries into the node_modules folder.

 

 

 

 

 

 

 

 

 
 

Step 6: Now, open this folder “simple-node-app” from your VS Code.

Step 7: Now, we will install express js web application framework to execute server-side scripting and provide a response to the Client. Please execute the following command to install express js from the command prompt or from the terminal of the VS Code for this folder/project root directory.

npm install express

It will install express js framework in your node_modules folder of the project directory.

Step 8: Great, you have completed all the installation process. Now, it’s time to write the code.
So, please create a js file named “index.js” in the same project directory. After creation of this file, your project directory looks like:

 

 

 

 

 

 

 

Step 9: Now, please write the following code snippets for index.js file.

var express = require('express');
var app = express();

var PORT = process.env.port || 3001;

app.get('/', function (req, res) {
  res.send('Hello World!');
});
app.listen(PORT, function () {
  console.log(`App listening on port ${PORT}`);
});

As per the code snippets, we have imported the express js library and define the port. process.env.port is required to run the application on any platform just like Heroku instead of only localhost.

After that, we have defined the application get feature to declare the “Hello world!” message to the client side/web browser. At last, we have set the application listening on the particular port using app.listen() method.

Step 10: Now, it’s time to execute. So, please run this following command node index.js from the command prompt or from the terminal of the VS Code. After some time, your first node application will be run on the localhost: http://locahost:3001

 

Output: When we will execute this URL: http://localhost:3001 from the browser, we will get “Hello World!” message in the browser,

 

 

 

 

                                                 Thanks for your time!!

2,148 total views, no views today

Posted in Lightning Web Component Open Source, Salesforce Lightning | Leave a comment

Introduction of Jest – JavaScript Testing Framework

What is Jest?
Jest is a JavaScript Testing Framework for the client-side application using Node, Babel, React, TypeScript, Angular as well as Lightning Web Component and more. Jest is a JavaScript library and it is distributed as an NPM package.

We will learn how to use Jest to test our Lightning Web Component in the next chapter. Before that, we need to know the basic idea of Jest to test any JavaScript file. Let’s start:

Now, we will test our own sample js file which will return the “Hello World!” message.

Step 1: Let’s say, we have created one folder called “JestTest” where we will create the sample js file.

Step 2: We have created one sample js file named “helloWorld.js” which will return the message “Hello World!“.

function helloWorld(){
    return 'Hello World!';
}
module.exports = helloWorld;

Here, we have given provision to access this js function from other js files in the same folder using “module.exports” feature.

Step 3: Now, we have to install Jest library by running the following command in the terminal from the VS Code or from CLI. It will take little time to install. After successful installation, you can see the sub-folder named “node_modules” in your main directory/folder.

npm install --save-dev jest

Step 4: Till now, we didn’t get package.json file where we can derive the test commands. For that, we have to run the following command “npm init” from the terminal. It will ask so many questions about your project configuration. But, you can leave as it’s blank for now. After successful execution, you can see the package.json file has been created.

Step 5: So, in package.json file, we have to update the following commands:

"scripts": {
    "test": "jest"
 },

Jest Configuration is done. Excellent Job !!

Step 6: Now, we will create the test file. Naming Convention would be mainFileName.test.js. So, we have created a test file named “helloworld.test.js” to test our helloWorld function. In this file, we have imported our original “helloWorld.js” function by using require statement.

const helloWorld = require('./helloWorld');

describe('helloWorld', () => {
    it('displays message', () => {
        expect(helloWorld()).toBe('Hello World!');
    });
});

We can describe the blocks in this way:

  • describe() block is nothing but a test suite. It can be used to test more business use cases.
  • it() block defines the test block. A single it() block describes a single test. We can use test() block instead of it() block.
  • expect() block is the assertion statement and it returns boolean variable depends on the matching between real value and expected value.

Step 7: Now, we will run the following command from the terminal of the VS Code to test our helloWorld function.

npm test

Result:

 

 

 

 

 

 

 

Here, we can see our test case is passed by matching “Hello World!” statement.

Step 8: If we want to see code coverage, we have to update the scripts in the package.json file.

"scripts": {
    "test": "jest --coverage"

  },

Step 9: Now, run the same Jest runner syntax from the terminal such as “npm test” just like Step 7.

Result:

 

 

 

 

 

 

 

 

 

Step 10: If you want to see the collective coverage report in HTML for all the js files in the same folder, you have to include the jest commands after scripts in your package.json file.

"jest": {
    "coverageReporters": ["html"]
  },

Now, the entire package.json file looks like

{
  "name": "jesttest",
  "version": "1.0.0",
  "description": "",
  "main": "helloWorld.js",
  "dependencies": {
    "jest": "^24.9.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "jest --coverage"

  },
  "jest": {
    "coverageReporters": ["html"]
  },
  "author": "",
  "license": "ISC"
}

Step 11: Again, we have to run “npm test” command and we will get one sub-folder called “coverage” in your main directory/folder named “JestTest“. In the Coverage folder, please run the “index.html” file to check the entire coverage report in HTML just like:

If you want to learn more about Jest, please read the reference document of Jest library from the following link: https://jestjs.io/

Enjoy! We have explored the fundamentals of Jest. In the next chapter, we will learn Jest for Lightning Web Component.     

Thank you! 

2,655 total views, 3 views today

Posted in Lightning Components, Lightning Web Component | Leave a comment

Join #Journey2Salesforce Ecosystem

Hello everyone,

Please join #Journey2Salesforce ecosystem. It’s a great learning opportunity from Salesforce to build your career in Salesforce Platform.

2,550 total views, no views today

Posted in Einstein, Lightning Components, Lightning Experience, Lightning Web Component, Salesforce Lightning | Leave a comment

Learning Einstein Vision

Please download the Einstein Vision Cheatsheet (unofficial)

PDF – Einstein Vision Cheatsheet

DOCX – Einstein Vision Cheatsheet

 

1,162 total views, 1 views today

Posted in Einstein | Leave a comment