Custom Lead Conversion Popup in Lightning Web Component

Hello friends, I am sharing the code for creating custom lead conversion popup in lightning web component. I hope you enjoy the blog post.

Create Custom Quick Action – Convert

Add “Convert” to Lead Page Layout

Start Coding

leadCreation.html

<template>

    <header class="slds-modal__header">
        Convert Lead
      </header>
      
    <div class="slds-m-top_medium"
            style="text-align: center">
                <lightning-button
                class="buttonClass"
                type="submit"
                name="save"
                label="Convert"
                onclick={convertL}
                ></lightning-button>
                &nbsp; &nbsp;
                <lightning-button
                
                type="submit"
                name="save"
                label="Cancel"
                onclick={closepopup} 
            ></lightning-button>
            </div>
    <div class="standards">    

            <lightning-messages></lightning-messages>
    
    <br/>
                <h2>Convert Lead</h2>
            <br/>
            <div class="slds-grid">
            <div class="slds-col" >
            <span><lightning-input type="text" label="Record Owner" value={owner} readonly></lightning-input>
            </span>
            </div>
            <div class="slds-col">
            <span><lightning-input type="Checkbox" label="Send Email To Owner" onchange={checkSendEmail}></lightning-input>
            </span></div>
        
    </div>
    <div class="slds-grid">

           <div class="slds-col slds-size_1-of-2 ">
           <span>
        
                <lightning-combobox
                name="CreateOption"
                label="Create Option"
                
                placeholder="Select One"
                options={createOptions}
                onchange={handleChange}
                ></lightning-combobox>
           
            </span> </div>
            <template if:true={showAttachTo}>  <div class="slds-col slds-size_1-of-2 test">
                
                <span><c-lwc-Custom-Lookup objectname="Account" fieldname="Name" selectrecordid={selectRecordId}
                       selectrecordname={selectrecordname} iconname = "action:new_account" onselected={selectedrecords}></c-lwc-Custom-Lookup>
                     </span>
    </div></template>
    </div>
    <div class="slds-grid">
    
        <div class="slds-col slds-size_1-of-2">
            <lightning-combobox
            name="status"
            label="Converted Status"
            value={value}
            placeholder="Qualified"
            options={optionsStatus}
            ></lightning-combobox>
            </div>
        <div class="slds-col slds-size_1-of-2">
        <lightning-input name='opportunityName' type="text" label="Opportunity Name" onchange={checkinput} value={oppName}></lightning-input>
        </div>
    </div>
    <br/>
    <div class="slds-grid">
    <div class="slds-col slds-size_1-of-2">
    <lightning-input name='noOpp' type="Checkbox" label="Do not create new opportunity upon conversion" onchange={checkSendEmail}></lightning-input>
        </div>
    </div>
    </div>
    <br/>
    <div class="slds-m-top_medium"
    style="text-align: center">
    <lightning-button
        type="submit"
        name="save"
        label="Convert"
        onclick={convertL}
    ></lightning-button>
        &nbsp; &nbsp;
    <lightning-button
       class="buttonClass"
       type="submit"
       name="save"
       label="Cancel"
       onclick={closepopup} 
    ></lightning-button>
     <br/>
     <br/>
    </div>
    </template>

leadCreation.js

/* eslint-disable no-undef */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-console */
/* eslint-disable no-alert */
/* eslint-disable no-dupe-class-members */
import { LightningElement,api,track} from 'lwc';
//import {getRecord,getFieldValue} from 'lightning/uiRecordApi';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

import Subject_FIELD from '@salesforce/schema/Task.Subject';
import ActivityDate_FIELD from '@salesforce/schema/Task.ActivityDate';
import { NavigationMixin } from 'lightning/navigation';
//import CallDurationInSeconds_FIELD from '@salesforce/schema/Task.CallDurationInSeconds';
//import Type_FIELD from '@salesforce/schema/Task.Type';
import Description_FIELD from '@salesforce/schema/Task.Description';
import Status_FIELD from '@salesforce/schema/Task.Status';
import Priority_FIELD from '@salesforce/schema/Task.Priority';
//import IsReminderSet_FIELD from '@salesforce/schema/Task.IsReminderSet';
import convertLead from '@salesforce/apex/leadConversion.convertLead';


export default class LeadCreation extends NavigationMixin(LightningElement) {
    @track error;
    @track selectRecordId;
    @track selectrecordname;
    @track hasValue=false;
    hastrue=true;
    hasfalse=false;
    @track showAttachTo=true;

    // this object have record information
    @track taskRecord = {
        Subject : Subject_FIELD,
        ActivityDate : ActivityDate_FIELD,
       // CallDurationInSeconds : CallDurationInSeconds_FIELD,
       
        Description : Description_FIELD,
        Status:Status_FIELD,
        Priority:Priority_FIELD,
        //IsReminderSet:IsReminderSet_FIELD,
       // convertLead:convertLead

    };

    @track sendEmailCheckbox;
    @api recordId;
    
    @api company;
    @api owner;
    @api LeadSource;
    //@track recordId;
    @track Task;
    @track oppName;
    accName;
    productid;
    accRecordId;
    donotcreateopp=false;
    selectedRec;
    
    get createOptions(){
        return[
        { label: 'Create New', value: 'CreateNew' },
        { label: 'Attach to exsisting Client/prospect', value: 'Existing' }
        ]
    }

       get options() {
        return [
            { label: 'Create New: Test Lead', value: 'New' },
            { label: 'In Progress', value: 'In Progress' },
            { label: 'Completed', value: 'Completed' },
        ];
    }
    get optionsStatus() {
        return [
            { label: 'Not Started', value: 'Not Started' },
            { label: 'In Progress', value: 'In Progress' },
            { label: 'Completed', value: 'Completed' },
            { label: 'Deferred', value: 'Deferred' },
        ];
    }
    get optionsType1() {
        return [
            { label: 'Low', value: 'Low' },
            { label: 'Normal', value: 'Normal' },
            { label: 'High', value: 'High' },
        ];
    }
    get optionsSubject() {
        return [
            { label: 'Call', value: 'Call' },
            { label: 'Email', value: 'Email' },
            { label: 'Send Letter', value: 'Send Letter' },
            { label: 'Send Quote', value: 'Send Quote' },
        ];
    }
    get optionsType() {
        return [
            { label: 'Call', value: 'Call' },
            { label: 'Meeting', value: 'Meeting' },
            { label: 'Other', value: 'Other' },
            { label: 'Email', value: 'Email' },
        ];
    }
    
       
    openTask(){
        this.hasValue=this.hastrue;
    }
    checkSendEmail(event){
        this.sendEmailCheckbox=event.target.checked;
        
        if(event.target.name==='noOpp'){
            this.donotcreateopp=event.target.checked;
            
        }

    }
    convertL(){
        
        if(this.hasValue===false){
           this.taskRecord=null;
           
           
           }
        
        console.log(this.taskRecord);
        convertLead({'recordId':this.recordId,'sendEmailCheckbox':this.sendEmailcheckbox,'donotcreateopp':this.donotcreateopp,'ExistingAccount':this.selectedRec,
      'ProductId':this.productid,'oppName':this.oppName,'taskRec':this.taskRecord})
      
        
      .then(result => {
        // Clear the user enter values
        this.taskRecord = {};
        this.accRecordId=result;

        window.console.log('result ===> '+result);
        // Show success messsage
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.accRecordId,
                objectApiName: 'Account',
                actionName: 'view'
            }
        });
       
        this.dispatchEvent(new ShowToastEvent({
            title: 'Success!!',
            message: 'Lead Converted Successfully!!',
            variant: 'success'
        }),);
    })
    .catch(error => {
        this.error = error.message;
        
        console.log(this.error);
    });

  
      }
      selectedrecords(event){
        this.selectedRec = event.detail.currentRecId;
        
      }
      checkinput(event){
          if(event.target.name==='createOption'){
              this.accName=event.target.value;
          }
          if(event.target.name==='productid'){
              this.productid=event.target.value;
          }
          if(event.target.name==='opportunityName'){
              this.oppName=event.target.value;
              
          }
           
      }
      handleChange(event){
        if(event.target.name==='Subject'){
            this.taskRecord.Subject=event.target.value;
        }
        if(event.target.name==='ActivityDate'){
            this.taskRecord.ActivityDate=event.target.value;
        }
        if(event.target.name==='CallDurationInSeconds'){
            this.taskRecord.CallDurationInSeconds=event.target.value;
        }
        if(event.target.name==='Description'){
            this.taskRecord.Description=event.target.value;
        }
        if(event.target.name==='Status'){
            this.taskRecord.Status=event.target.value;
        }
        if(event.target.name==='Priority'){
            this.taskRecord.Priority=event.target.value;
        }
        if(event.target.name==='IsReminderSet'){
            this.taskRecord.IsReminderSet=event.target.value;
        }
        if(event.target.name==='CreateOption'){
         if(event.target.value==='CreateNew'){
             this.showAttachTo=this.hasfalse;
         }
         if(event.target.value==='Existing'){
            this.showAttachTo=this.hastrue;
        }
        }     
      }
    }

leadCreation.css

h1{
    background-color: #F3F2F2;
    font-weight: bold;
    margin-left: -24px;

}
h2{
    background-color: #F3F2F2;
    font-weight: bold;
    margin-left: -185px;

}

.slds-modal__container{
    max-width: 70rem !important;
    width:80% !important;
}
.modal-body.scrollable.slds-modal__content.slds-p-around--medium{
    max-height:700px;
}
.test{
    margin-top: -25px;

}
.slds-input:required{
   max-width: 200px !important;
}
.slds-form-element{
    width: 200px !important;
}
.standards{
    padding-left: 160px;

}

leadCreation.js-meta.xml

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

leadCreation.apxc

public class leadConversion {
    @auraEnabled
    Public static Id convertLead(Id recordId,string sendEmailCheckbox,boolean donotcreateopp,Id ExistingAccount,string productId,String oppName,Task taskRec){
        system.debug('---'+taskRec);
        system.debug('---'+oppName);
        system.debug('---'+ExistingAccount);
        system.debug('---'+donotcreateopp);
        Database.LeadConvert lc=new Database.LeadConvert();
        lc.setLeadId(recordId);
        if(ExistingAccount!=null){
            lc.setAccountId(ExistingAccount);
            }
        if(sendEmailCheckbox=='options'){
            lc.setSendNotificationEmail(true);  
        }
        if(donotcreateopp){
            lc.setDoNotCreateOpportunity(true);
        }
        else{
            System.debug('--->'+oppName);
            lc.setOpportunityName(oppName);
        }
        leadstatus ls=[select id,MasterLabel,IsConverted from LeadStatus where IsConverted=true limit 1];
        
        lc.setConvertedStatus(ls.MasterLabel);
          
        Database.LeadConvertResult lcr=Database.convertLead(lc);
        id accid=lcr.getAccountId();
        Id conid=lcr.getContactId();
        Id oppId=lcr.getOpportunityId();
        
        try{
          
            if(taskRec!=null){
                taskRec.whoId=conid;
             taskRec.whatId=oppid;
        insert taskRec;
            }
            system.debug('id---'+taskRec);
        }
        catch(Exception ex) {
            System.debug('test'+ex.getMessage());
           throw new AuraHandledException(ex.getMessage());
        }
        return accid;
              
    }
    @auraEnabled
    Public static Lead getLeadInformation(Id recordId){
        
        Lead IsLead=[Select Id,Company,LeadSource,owner.Name from lead where Id=:recordId];
        return IsLead;
    }
    @auraEnabled
    Public static Id CreateTask(Id recordId,Task taskRec,Id ownerId){
        
       try{
          
            if(taskRec!=null){
                taskRec.WhatId=recordId;
                taskRec.ownerId=ownerId;
             
        insert taskRec;
            }
            system.debug('id---'+taskRec);
        }
        catch(Exception ex) {
            System.debug('test'+ex.getMessage());
           throw new AuraHandledException(ex.getMessage());
        }
        return taskRec.Id;
    }
     @auraEnabled
    Public static Account getAccountInformation(Id recordId){
        
        Account IsAccount=[Select Id,Name,Type,phone,(select Id,Name from opportunities),(Select Id,Name from contacts) from Account where Id=:recordId];
        return IsAccount;
    }
    @AuraEnabled(cacheable=true)
    public static List<SObJectResult> getResults(String ObjectName, String fieldName, String value) {
        List<SObJectResult> sObjectResultList = new List<SObJectResult>();
        system.debug(fieldName+'-------------'+ObjectName+'---++----------'+value);
        if(String.isNotEmpty(value))
            for(sObject so : Database.Query('Select Id,'+fieldName+' FROM '+ObjectName+' WHERE '+fieldName+' LIKE \'%' + value + '%\'')) {
                String fieldvalue = (String)so.get(fieldName);
                sObjectResultList.add(new SObjectResult(fieldvalue, so.Id));
            }
        
        return sObjectResultList;
    }
    
    public class SObJectResult {
        @AuraEnabled
        public String recName;
        @AuraEnabled
        public Id recId;
        
        public SObJectResult(String recNameTemp, Id recIdTemp) {
            recName = recNameTemp;
            recId = recIdTemp;
        }
    }

}

Together we can learn faster

You can join Whatsapp Group

You can join Facebook group

You can join Twitter

You can join Instagram 

 

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes