Salesforce Lightning Web Component (LWC) Basics With Hands On

Salesforce Lightning Web Component (LWC) Basics With Hands On


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.

          
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.) 😊
        
                                                               NEXT >>

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

28 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
    2. Thank youu for so helpful and easy learning of LWC. Please make more such blogs for LWC series and for more topics of Salesforce development. Thank youu once again

      Delete
  2. Replies
    1. Thank You So Much Mohit 😇 !! I Make Sure This Will be Helpful For You in The Future as well.

      Delete
  3. Replies
    1. Thanks Vamsi 😊I hope this platform will help you in the future as well

      Delete
  4. Superior post, keep up with this exceptional work. It's nice to know that this topic is being also covered on this web site so cheers for taking the time to discuss this! Thanks again and again! Wordpress Hosting

    ReplyDelete
    Replies
    1. Thanks for your valuable words. I am glad that you liked the post.
      Thanks for you valuable time 😊

      HAPPY LEARNING 😊

      Delete
  5. Interesting post. I’ll be sticking around to hear much more from you guys. Thanks! san fran design firms

    ReplyDelete
  6. I was very pleased to find this website. I wanted to thank you for your time for this wonderful post!! I definitely enjoy reading it and I have you bookmarked to check out new stuff you blog post. iphone sketch

    ReplyDelete
  7. Very Helpful content and great efforts to make it as simple as possible.Thank you!!

    ReplyDelete
    Replies
    1. Hey Narsing,

      Thank you so much for your valuable words 😊 #KeepLearning
      ⚡️ HAPPY LEARNING ⚡️

      Delete
  8. Good information. Really helpful thanks for your efforts

    ReplyDelete
    Replies
    1. Hey!! Thanks Lalit Glad to know that 😊 #KeepLearning

      ⚡️HAPPY LEARNING⚡️

      Delete
  9. very clear and easy to understand
    I have a requirement lets say, I have check box field on Product object. when it is true I wanted to display Product SKU field with Product Code instead of Product Name. else Product name and SKU.
    Could you help me how to achieve it?

    ReplyDelete
    Replies
    1. Hi,

      You need to use conditional statements to display the data like this :


      //Dispalying True Part


      //Dispalying True Part



      For more information on conditional rendering in LWC please check the separate Episode on it here :
      https://www.sfdckid.com//2020/05/lwc-conditional-rendering-in-salesforce.html

      If you still have any question feel free to post it in Q/A Section available on top.

      ⚡️ HAPPY LEARNING ⚡️

      Delete
  10. the query is now giving CRUD error - below works

    try {
    lstProd = [SELECT id,Name,ProductCode FROM Product2 WHERE Name LIKE :strProdName WITH SECURITY_ENFORCED];
    }
    catch(System.QueryException qe) {
    System.debug(qe.getMessage());
    }

    return lstProd;

    ReplyDelete
  11. This comment has been removed by a blog administrator.

    ReplyDelete
  12. Really nice blog, thank you so much for sharing this. Visit OGEN Infosystem for creative website design and digital marketing company for seo, ppc and other social services for your website in Delhi, Noida, and all over the india.
    PPC Company in Delhi

    ReplyDelete
  13. Very important information, I am heartily thankful to you that you have shared this essential information with us. I got some different kind of knowledge from your web page, and it is very helpful for everyone. Thanks once again for sharing it. mahindra 575 di

    ReplyDelete

  14. Salesforce Lightning Web Component (LWC) is a modern web development approach to build components that are secure, performant, and maintainable. seo services in noida . I anxiously propose Web progress Seo in Noida Relationship for their unbelievable Page improvement alliance.

    ReplyDelete
  15. The Salesforce Lightning Web Component (LWC) Basics With Hands On course is a great way to get started with the LWC platform. The jaipur jewelry . It provides a comprehensive overview of the fundamentals of the platform and provides hands-on exercises to help develop your skills. This course is ideal for those who want to quickly get up to speed with the LWC platform and start building robust, custom solutions.

    ReplyDelete
  16. Qloudhost Netherlands Offshore VPS hosting Server provides a reliable and secure hosting solution for those looking for offshore hosting services in the Netherlands. https://qloudhost.com/offshore-vps-hosting/netherlands/

    ReplyDelete
  17. Salesforce Lightning Web Components are a game-changer in web development! They provide a seamless integration with Salesforce CRM, allowing developers to create dynamic, reusable, and efficient components. It's a fantastic tool for building robust, user-friendly applications on the Salesforce platform. 🚀💼
    Also check out this amazing john wick black suit

    ReplyDelete
  18. Exploring the future in fashion-forward Star Trek Picard Season 3 Leather Jacket – Picard's Season 3 look is light-years ahead!

    ReplyDelete
  19. Wow, this is like the ultimate guide to Salesforce LWC for beginners! I love how you broke everything down - from kebab-case to setting up in Visual Studio Code. Honestly, it felt like having a friendly chat while learning some cool tech stuff. And speaking of Salesforce, I recently came across this guide on how to connect Gravity Forms to Salesforce that might be handy for some. I’m definitely trying your tutorial out over the weekend and sharing it with my team. Great job and thanks for making learning fun! Keep these gems coming! 🚀👏 #LearningMadeEasy

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.