Thursday, April 30, 2020

create record using apex in Lightning Web Components(lwc)

Hi All,

below are the Example for ,How create record using apex in Lightning Web Components(lwc)

Sample code:-

createAccountRecordInLWC.html
 <template>
    <lightning-card title="Create Account Record" icon-name="standard:account">
        <div style="margin-left: 6%" if:true={error}>
            <lightning-badge label={error} style="color: red;"></lightning-badge>
        </div>

        <template if:true={accRecord}>
            <div class="slds-m-around--xx-large">
                <div class="container-fluid">
                    <div class="form-group">
                        <lightning-input label="Enter Account Name" name="accName" required="required" type="text" value={accRecord.Name} onchange={handleNameChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Phone Number" name="accPhone" type="number" value={accRecord.Phone} onchange={handlePhoneChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Account Type" name="accEmail" required="required" type="text" value={accRecord.Type} onchange={handleTypeChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Industry" name="accEmail" type="text" value={accRecord.Industry} onchange={handleIndustryChange}></lightning-input>
                    </div>
                </div>
                <br/>
                <lightning-button label="Submit" onclick={handleSave} variant="brand"></lightning-button>
            </div>
        </template>
    </lightning-card>
</templat>
createAccountRecordInLWC.js
import { LightningElement, track} from 'lwc';

// Importing Apex Class method
import saveAccount from '@salesforce/apex/LWCExampleController.saveAccountRecord';

// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

// importing Account fields
import NAME_FIELD from '@salesforce/schema/Account.Name';
import Phone_FIELD from '@salesforce/schema/Account.Phone';
import Industry_FIELD from '@salesforce/schema/Account.Industry';
import Type_FIELD from '@salesforce/schema/Account.Type';

export default class createAccountRecordInLWC extends LightningElement {
    @track error;

    // this object have record information  * it should be object field Api Name
    @track accRecord = {
        Name : NAME_FIELD,
        Industry : Industry_FIELD,
        Phone : Phone_FIELD,
        Type : Type_FIELD
    };


    handleNameChange(event) {
        this.accRecord.Name = event.target.value;
        window.console.log('Name ==> '+this.accRecord.Name);
    }

    handlePhoneChange(event) {
        this.accRecord.Phone = event.target.value;
        window.console.log('Phone ==> '+this.accRecord.Phone);
    }

    handleTypeChange(event) {
        this.accRecord.Type = event.target.value;
        window.console.log('Type ==> '+this.accRecord.Type);
    }

    handleIndustryChange(event) {
        this.accRecord.Industry = event.target.value;
        window.console.log('Industry ==> '+this.accRecord.Industry);
    }


    handleSave() {
        saveAccount({objAcc: this.accRecord}) //objAcc - it should be same as per class method variable name
        .then(result => {
            // Clear the user enter values
            this.accRecord = {};

            window.console.log('result ===> '+result);
            // Show success messsage
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: 'Account Created Successfully!!',
                variant: 'success'
            }),);
        })
        .catch(error => {
            this.error = error.message;
        });
    }
}
createAccountRecordInLWC.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="createAccountRecordInLWC"> <apiVersion>45.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
Apex Class Sample:-
public inherited sharing class LWCExampleController {

    @AuraEnabled
    public static void saveAccountRecord(Account objAcc){
        try{
            insert objAcc;
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
}

Sunday, April 26, 2020

interact one lightning Web Component with Aura Component.

Step 1) First we create Lightning Web Component with name “linkToAnotherCmp”
  • Click this link on how to create Lightning Web Component.
  • Then, put this code into linkToAnotherCmp.html
<template>
<div>
I'm Lightning Web Component
<br/>
Input : <input class="txtInput" />
<lightning-button label="Send to Aura Component" onclick={raiseEvent}></lightning-button>
</div>
</template>
linkToAnotherCmp.html
Here, you see the difference between Aura Components and Lightning Web Component., In Aura Component, we use ‘colon’ in the tag.

And In Lightning Web Component, we use ‘dash’ in the tag.


  • Put this code into lintToAnotherCmp.js
import { LightningElement } from 'lwc';
export default class LinkToAnotherCmp extends LightningElement {
raiseEvent(event){
let txtInput = this.template.querySelector(".txtInput");
const v = txtInput.value;
const textChangeEvent = new CustomEvent('txtChange',{
detail : {v},
});
//Fire Event
this.dispatchEvent(textChangeEvent);
}
}
linkToAnotherCmp.js 
Here, we fire the event from Lightning Web Component to Aura Component. Instead of event.fire in an Aura Component, use the standard DOM Method, this.dispatchEvent(myEvent), in Lightning Web Component.
The first argument in the CustomEvent constructor set the name to be ‘txtChange’.
The second argument is an object that configures the object behaviour. In this object, we set the “detail” which is payload event. A handling component can read for data. In this case, we’re passing the “v”.And In variable(v), we set the “txtInput.value”.
Step 2) Create Lightning Aura Component with name “EventDemo”
  • Put this code into EventDemo.cmp
<aura:component>
<aura:attribute name="textFromEvent" type="String" />
<div class="slds">
In Parent Lightning Component : {!v.textFromEvent}
<c:linkToAnotherCmp ontxtChange = "{!c.lwcEventHandler}" />
</div>
</aura:component>
EventDemp.cmp 
Here, we link the Lightning Web Component and handle the event fired by LWC using “ontxtChange”.In LWC, we use “txtChange” name in CustomEvent constructor and when we handle the event we add the “on”.
  • Put this code into EventDempController.js
({
lwcEventHandler : function(component, event, helper) {
var eventData = event.getParam('v');
component.set("v.textFromEvent",eventData);
}
})
EventDempController.js
Here, we get the value that fired by LWC using “event.getParam(‘v’)”.
Step 3) Create Lightning App with name “Demo”
  • Put this code into Demo.app
<aura:application extends="force:slds">
<div class="slds-box slds-text-heading_large slds-text-align_center">
Lightning Web Component - Apex Hours
<div class=" slds-grid slds-gutters slds-align_absolute-center slds-wrap">
<div class="slds-size_8-of-12">
<c:EventDemo />
</div>
</div>
</div>
</aura:application>
Demo.app 



We can call the Lightning Web Components into Aura Component and Lightning Web Components.
Note:- We do not call Aura Component into Lightning Web Components.

Quick Start: Lightning Web Components

Lightning WebComponent

Introducing of Lightning Web Component
Now, you can build Lightning Components using two programming models:
  1. Lightning Web Components (use core Web Components standards)
  2. Aura Components
What is Lightning Web Component or LWC?
A lightning web component that includes an HTML file, a JavaScript file, and a metadata configuration file. Lighting Web Components are custom HTML elements built using HTML and modern JavaScript. The files must use the same name so the framework can auto-wire them.

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="createRelatedRecord">

  <apiVersion>45.0</apiVersion>

  <isExposed>true</isExposed>

  <targets>

    <target>lightning__AppPage</target>

    <target>lightning__RecordPage</target>

    <target>lightning__HomePage</target>

  </targets>

</LightningComponentBundle>

helloWorldHtmlJsMetaXML

Power of LWC:
  • HTML Templates
The power of Lightning Web Components is using template tag. Content inside a template tag will not be rendered. The content can be visible and rendered later by using Javascript.
  • CSS
In Lightning web Components, you can use Lightning Design System or Custom Css.
  • JavaScript
In Lightning Web Components, JavaScript files are in ES6 modules.
  • Composition
You can add components to Aura Component, Aura App and Lightning Web Component.
  • Access Static Resources, Labels, Internationalization Properties, and User IDs
  • Component Lifecycle

Why Lightning Web Componets(LWC)?

  • In 2014, Web Standards had limited functionality. So, various framework came to fulfil the gap like ReactJs, CommonJs etc.
  • Aura framework was also part of that initiative where they push web standards to build enterprise applications.
  • Fast Forward to today and much has changed.
    • Web Standards had a rich set of functionality, supported by Native Browsers.
    • Templating, CustomElements, ShadowDom, classes to name few.
  • So, why Salesforce turns to modern JavaScript and introducing Lightning Web Components.
  • Lightning Web Components takes the best of modern JavaScript and provides only what’s necessary to perform well in browsers supported by Salesforce.
Let’s see how to Create Lightning Web Component
Step 1) Setup Salesforce Dx in VSCode
  1. Install Salesforce CLI.
  2. Download and install VSCode.
  3. Install required Extension.
    1. Salesforce Extension Pack.


  1. Lightning Web Components.

  1. Salesforce CLI Integration.
Step 2) Upgrade to Pre-release Org
  1. Sign up for Pre-release Developer edition at https://www.salesforce.com/form/signup/prerelease-spring19/.
  2. Upgrade Pre-release version of Salesforce CLI
sfdx plugins:install salesforcedx@pre-release



  1. Enable the domain in your developer org.

Step 3) Create SalesforceDX Project
  1. Open VSCode. Press “CTRL+SHIFT+P” and then enter “SFDX:Create Project with Manifest”. Then enter a project name and select folder.
Authorize an Org
Press “CTRL+SHIFT+P” and then enter “SFDX:Authorize an Org”.

Step 4) Finally, Create your first Lightning Web Component.
  1. Press “CTRL+SHIFT+P” and then enter “SFDX: Create Lightning Web Component”.
-Give the name of lighting web component.

  1. Then Select “lwc” folder.

  1. Then enter your Lightning Web Component Name. Please use camelCase for Lightning Web Components.It’s the best practice.
Let’s see your Lightning Web Component under “lwc” folder.

Step 5) Now, Lightning Web Component created. Let’s see how to use Lightning Web Component.
  • Put this code into helloWorld.html
<template>
<lightning-card title="HelloWorld" icon-name="standard:custom_notification">
<div class="slds-m-around_medium slds-p-around_small">
<p>Welcome to, {greet}!</p>
<lightning-input label="Name" value={greet} onchange={onNameChange}></lightning-input>
</div>
</lightning-card>
</template>
helloWorld.html 
  • Put this code into helloWorld.js
import { LightningElement, track } from 'lwc';
export default class HelloWorld extends LightningElement {
@track greet = 'Beautiful World';
onNameChange(event) {
this.greet = event.target.value;
}
}
helloWorld.js 
  • Put this into helloWorld.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
helloWorld.js-meta.xml
Step 6) Finally, deploy your component into Developer Org.

Step 7) Go to your Developer Org.
  • Click App Launcher Icon and then Select Sales App.

  • Then Click at Setup Icon and select edit page.

  • Then Drag “helloWorld” Component at pageLayout. After that, click at Activation and choose “OrgDefault”.Next, Activate.

Note: Domain is enabled in your Org. Else Custom Component will not be visible in your Org.
Here is your first Lightning Web Component.