Salesforce Lightning Web Component (LWC) Basics With Hands On

Salesforce Lightning Web Component (LWC) Basics

Hello Everyone, Welcome to Lightning web component (LWC) series dedicated to all new salesforce folks to understand salesforce lightning component from very basics. So let's go kid....

In this, we will learn how to create lightning web component (LWC) to search product from very basics along with the important lightning web component concepts.

Have a look at today's recipe...

------------------------------------------------------------------------------------





------------------------------------------------------------------------------------

Kebab Case in LWC :
In standard Salesforce Lightning Component, whenever we are using a naming convention like camel case standard like firstwordSecondword where the first letter is small and whenever second-word starts, we write its first letter it as capital which is basically used to give proper names to your component.

In LWC, we used kebab-case in markup where a namespace is separated by a hyphen like search-component

Example 1 :
------------------------------------------------------------------------------------
<template>
    <c-search-component> </c-search-component>
</template>
------------------------------------------------------------------------------------

you can also use the underscores to separate the words. like search_component

Example 2 :
------------------------------------------------------------------------------------
<template>
    <c-search_component> </c-search_component>
</template>
------------------------------------------------------------------------------------

Track property in LWC :
- Track property is called private reactive property.
- You can use a track property directly in a template. Also, you can use a track property indirectly in a getter of a property that’s used in a template.

- Both @track and @api mark a property as reactive. If the property’s value changes, the component re-renders.
- Track properties are private,
------------------------------------------------------------------------------------
Import @track from the lwc module

import { LightningElement, track } from 'lwc';
------------------------------------------------------------------------------------

Public api property in LWC :
- Passing value from one component to another in salesforce lightning web component this is quite easy in Lightning web component using @api.
- Properties decorated with @api are public and can be set by another component.
- To expose a public property, decorate it with @api.
- Public properties defined as API for a component. An owner component that uses the component in its markup can access the component’s public properties.
- Public properties are reactive. If the value of reactive property changes, the component re-renders. When a component re-renders, all the expressions used in the template are re-evaluated.
- To mark a property as public, annotate it with the @api decorator.

When you use the @api decorator, you must import it explicitly from LWC.

For example :
------------------------------------------------------------------------------------
import { LightningElement, api } from 'lwc';
------------------------------------------------------------------------------------

Lightning data table in LWC :
A lightning-datatable component displays tabular data where each column can be displayed based on the data type. For example, an email address is displayed as a hyperlink with the mail to :
URL scheme by specifying the email type. The default type is text.

This component inherits styling from data tables in the Lightning Design System.

lightning-datatable is not supported on mobile devices.

Supported features include :
- Displaying and formatting of columns with appropriate data types
- Infinite scrolling of rows
- Inline editing for some data types
- Header-level actions
- Row-level actions
- Resizing of columns
- Selecting of rows
- Sorting of columns by ascending and descending order
- Text wrapping and clipping
- Row numbering column
- Cell content alignment
- Tables can be populated during initialization using the data, columns, and key-field attributes. The key-field attribute is required for correct table behaviour. It associates each row with a unique identifier.

------------------------------------------------------------------------------------
<template>
     <lightning-datatable data={searchData} 
                                 columns={columns} 
                                 key-field="id">
     </lightning-datatable>
</template>
------------------------------------------------------------------------------------

Retrieving Data Using an Apex Controller : 
Just like lightning component, we will create an apex class :
------------------------------------------------------------------------------------
public with sharing class SearchController {

    @AuraEnabled(Cacheable = true)
    public static List<Product2> retriveProducts(String strProdName) {
        strProdName = '%' + strProdName + '%';
        List<Product2> lstProd = [SELECT  Id, Name, ProductCode FROM Product2 WHERE Name LIKE :strProdName];
        return lstProd
    }
}
------------------------------------------------------------------------------------

The template fetches up the Data Table to the Product records using the Id field.
------------------------------------------------------------------------------------
<template>
<lightning-datatable data={searchData} 
columns={columns} 
key-field="id">
        </lightning-datatable>
</template>
------------------------------------------------------------------------------------

Load the columns using JavaScript :
This example fetches the retriveProducts Apex method
------------------------------------------------------------------------------------
import { LightningElement, track } from 'lwc';
import serachProds from '@salesforce/apex/SearchController.retriveProducts';

// datatable columns
const columns = [
{
    label: 'Name',
    fieldName: 'Name',
    type: 'url',
    typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}
}, {
    label: 'Product Code',
    fieldName: 'ProductCode',
    type: 'text',
}, 
];
export default class CustomSearchInLWC extends LightningElement {
@track searchData;
@track columns = columns;
@track strSearchProdName;

        handleProductName(event) {
            this.strSearchProdName = event.detail.value;
            serachProds({strProdName : this.strSearchProdName})
            .then(result => {
            this.searchData = result;
        })
    }
}
------------------------------------------------------------------------------------

Now how we can proceed with Visual Studio Code ?
Don't worry, your kid is here to help you.....follow these simple steps to execute the lightning web component hands-On Demo

So let's get started.....

LWC Hands - On Demonstration :

STEP 1 :

Install Visual code studio to your system.
Click here for download link   (Open In Desktop)

STEP 2 :

Click on the extension icon to install Salesforce Extension pack


Now search for Salesforce Extension Pack


Now click on install and wait until it finishes

STEP 3 :

Now click Command + Shift + P (on Mac) or Ctrl + Shift + P (on Windows)

- Select > SFDX : Create Project with manifest 
- Select Standard
- Enter the Project Name which will create project folder on your computer.
- Now again press Command + Shift + P (on Mac) or Ctrl + Shift + P (on Windows)
and select Authorize Org

STEP 4 :

Select manifest and now click on right-click and select SFDX: Retrieve Source in Manifest from Org.

- Which will retrieve all the data and now you can see all the data and codes in your force-app, You can click on force-app and select what type of files you want to create or edit like Apex class, Lightning Component, LWC etc.

 

- Now click on right-click on LWC and SFDX : Create Lightning Web Component and now enter the name



Now follow and test the below code of Search Product Component In  LWC with Checkbox

Get....  Set...  Go...

----------------------searchComponentLWC.html--------------------------
<template>
    <lightning-card title="Search Product" icon-name="standard:product">
            <lightning-layout multiple-rows="true" vertical-align="end">
            <lightning-layout-item size="12" small-device-size="10" medium-device-size="8" large-device-size="12" padding="around-small">
                    <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                    <lightning-input type="text" 
                                                     value={strSearchProdName}
                                                     label="Enter Product Name" 
                                                     onchange={handleProductName} placeholder="Search Product">                                         </lightning-input>
                            </div>
                        </div> 
            </lightning-layout-item>
            </lightning-layout><br/>

        <div if:true={searchData}>
            <lightning-datatable data={searchData} 
                                 columns={columns} 
                                 key-field="id"></lightning-datatable>
        </div>
    </lightning-card>
------------------------------------------------------------------------------------

--------------------------searchComponentLWC.js-------------------------

import { LightningElement, track } from 'lwc';
import serachProds from '@salesforce/apex/SearchController.retriveProducts';

// datatable columns
const columns = [
{
    label: 'Name',
    fieldName: 'Name',
    type: 'url',
    typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}
}, {
    label: 'Product Code',
    fieldName: 'ProductCode',
    type: 'text',
}, 
];
export default class CustomSearchInLWC extends LightningElement {
@track searchData;
@track columns = columns;
@track strSearchProdName;

        handleProductName(event) {
            this.strSearchProdName = event.detail.value;
            serachProds({strProdName : this.strSearchProdName})
            .then(result => {
            this.searchData = result;
        })
    }
}
------------------------------------------------------------------------------------

--------------------searchComponentLWC.js-meta.xml------------------

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

Create SearchController Apex Class for this lightning component

-------------------------SearchController-------------------------------------

public with sharing class SearchController {

    @AuraEnabled(Cacheable = true)
    public static List<Product2> retriveProducts(String strProdName) {
        strProdName = '%' + strProdName + '%';
        List<Product2> lstProd = [SELECT  Id, Name, ProductCode FROM Product2 WHERE Name LIKE :strProdName];
        return lstProd
    }
}
------------------------------------------------------------------------------------

Now go to manifest and again right-click there and Deploy this Source to Org 

Check... Check... Check...

Now login to salesforce... and open any object for example Account

- Click on Gear Icon  and select Edit Page 
- Now from the pallet, you can select




And drop your searchComponentLWC wherever you want and save it.



Now search for any product..... type something.....



Coooool 😎...... Kid, you have just learnt LWC lesson to search for products and display the result in data table.

I hope you guys understood basic some concepts of Lightning Web Component in salesforce.

⚡️THANKS FOR THIS BLOG CONTRIBUTION⚡️

WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE LIGHTNING WEB COMPONENT (LWC) BASICS WITH SEARCH COMPONENT EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊

salesforce kid on play store

Salesforce Lightning Web Component (LWC) Basics With Hands On Salesforce Lightning Web Component (LWC) Basics With Hands On Reviewed by on Rating: 5

3 comments:

  1. Helpful and understandable. Thank you !

    ReplyDelete
    Replies
    1. We are glad that it is helpful for you, Thank You for your valuable time 😊

      Delete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.