• Tulasiram Chippala
  • NEWBIE
  • 50 Points
  • Member since 2018
  • Intelliswift

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 33
    Questions
  • 17
    Replies
Hi 
Can we convert below string into a DateTime Format? Please help me on this.

Tue Mar 2, 2021 8pm
We have a requirement like below,

Suppose if any Employee owner updates some values on Employee record, it has to generate new Employee with updated values and Active.

And Old employee should be INACTIVE with old values(Not with new values). I tried with different scenarios but not succeeded.

Please help me with this, how I can achieve this. Thanks in advance. 
 
We are displaying one banner on the Opportunity page. If Opportunity is edited this banner has to be refreshed and call apex method. 
I tried with below code but recursion is happening in page refresh, it is not stopping refresh call.
<aura:handler event="force:refreshView" action="{!c.onSuccessMethod}" />
 
onSuccessMethod : function(component, event, helper){
        console.log("Loading on Success");
        $A.get('e.force:refreshView').fire();
        
    }
 
<aura:component controller="PositionsStatus" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:hasSObjectName" 
                access="global">
	<aura:attribute name="statusMessage" type="String" default=""/>
  	<aura:attribute name="ShowMessage" type="boolean" default="true"/>
    <aura:attribute name="sobjecttype" type="String" default="{!v.sObjectName}"/>  
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
	<aura:handler event="force:refreshView" action="{!c.onSuccessMethod}" />

    <aura:if isTrue="{!v.ShowMessage}">
    <div  class="">
        <div aura:id = "barId" class="greenColor slds-notify slds-notify_alert slds-theme_alert-texture">
            <span class="slds-assistive-text ">warning</span>
            <h1>{!v.statusMessage}</h1>
            <div class="slds-notify__close">  
            </div>
        </div>
    </div>
        </aura:if>
</aura:component>
Please help me with this. Thanks.
 
We have a requirement for Dividing total contract value based on Quarters. 
Suppose Start Date = 2020, 5, 18
               End Date =  2021, 5, 18
For the above two dates, there are 5 quarters. 
             Q2, Q3, Q4 for 2020 and
             Q1, Q2 for 2021.

So, how to calculate how many quarters are there in between Start Date and End Date.

Please help me with this. Thanks in Advance.
global class AccountIdGeneration implements Database.Batchable<sObject>,Database.Stateful{
    global String query ;
    List<Account> accountList = new List<Account>();
    global AccountIdGeneration(){
        query = 'Select id, Name, website from account where website != null';
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<account> scope){
        List<account> lstAccount = new List<account>(); 
        for(account acc : scope){
           lstAccount.add(acc);
            
        }
        accountList.addAll(lstAccount);
    }
    global void finish(Database.BatchableContext BC){
        String finalString = 'Generated Id, website, Account Id, Name \n';
        System.debug('--accountList Size---'+accountList.size());
        /*-------------------- Forming Excel String ---------------*/
        for(account acc : accountList){
            Blob cryptoKey = Blob.valueOf('abcdefghijklmnopqrstuvwxyzabcdef');
            // Converting website to blob
            Blob data = Blob.valueOf(acc.website);
            Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
            String encryptedDataStr = EncodingUtil.base64Encode(encryptedData); 
            String key = encryptedDataStr.replaceAll('[^a-zA-Z\\s]', '');
            String str = acc.website.SubStringBefore('.');
            String finalID = '';
            if(str.length() >= 4 ){ finalID = str.substring(0, 4).toUppercase()+key.substring(30, 32).toUppercase(); }
            else if(str.length() < 4 && str.length() == 3){ finalID = str.substring(0, 3).toUppercase() +key.substring(29, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 2){ finalID = str.substring(0, 2).toUppercase()+key.substring(28, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 1){ finalID = str.substring(0, 1).toUppercase()+key.substring(27, 32).toUppercase();} 
            String recordString = finalID+','+acc.website+','+ acc.id+','+acc.Name+'\n';
            finalString  =  finalString + recordString;    
            
        }
        System.debug('--finalString-'+finalString);
        /*-------------------- Forming Email ---------------*/
        
        Messaging.EmailFileAttachment attachmentFile = new Messaging.EmailFileAttachment();
        blob accountList = Blob.valueOf(finalString);
        string csvname= 'accListFile.csv';
        attachmentFile.setFileName(csvname);
        attachmentFile.setBody(accountList);
        Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
        String email1 = 'test@gmail.com';
        String[] toAddresses = new list<string> {email1};
            String subject ='Account Generated Id List';
        email.setSubject(subject);
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{attachmentFile});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
We are using this code for generating a 6-bit id for an account. When executing, the Finish method is not sending any email. logs showing batch apex status as "Ending position out of Bounds: 32".

Note: I am processing more than 10k records.

Please help me with this. Thanks in advance.
 
Hi I am using ONSUBMIT event for validating fields using below code. Unfortunately I am getting an error 

"[Cannot read property 'config' of undefined]"
<lightning:recordEditForm aura:id="recordViewForm"
                              objectApiName="Candidate__c"
                              recordId="{!v.recordId}"
                              recordTypeId=""
                              
                              onsubmit="{!c.onSubmit}"
                              onsuccess="{!c.handleSuccess}"
                              >
        <lightning:messages />

===================================================


<div class="slds-size_1-of-2 slds-max-small-size_1-of-1">
                       
                            <lightning:inputField aura:id="endDateOnProject" fieldName="End_Date_on_Project__c"/>
                    </div>
                    <div class="slds-size_1-of-2 slds-max-small-size_1-of-1">
                        <lightning:inputField aura:id="reasonProjectEnded" fieldName="Reason_Project_Ended__c"/>
                    </div>
                    <div class="slds-size_1-of-2 slds-max-small-size_1-of-1">
                        <lightning:inputField aura:id="DummyField1" fieldName="" />
                    </div>
                    <div class="slds-size_1-of-2 slds-max-small-size_1-of-1">
                        <lightning:inputField aura:id="Candidate-EndDate-NotifiedBy" fieldName="Candidate_EndDate_NotifiedBy__c" />
                    </div>

Controller:
onSubmit : function(component, event, helper) {
        
        var endDateProj = component.find("endDateOnProject");
        var endDateProjValue = endDateProj.get("v.value");
        console.log(endDateProj);
        var notifyBy = component.find("Candidate-EndDate-NotifiedBy");
        var notifyByValue = notifyBy.get("v.value");
        console.log(notifyByValue);
        if (endDateProjValue !== null){
            
            notifyBy.set("v.errors", [{"message":"Quantity can’t be blank."}]);
        }
        
    },
I am using code suggested by Salesforce Aura developer guide.
/*errorHandlingCustomController.js*/
{
    doAction : function(component, event) {
        var inputCmp = component.find("inputCmp");
        var value = inputCmp.get("v.value");

        // is input numeric?
        if (isNaN(value)) {
            inputCmp.set("v.errors", [{message:"Input not a number: " + value}]);
        } else {
            inputCmp.set("v.errors", null);
        }
    },

    handleError: function(component, event){
        /* do any custom error handling
         * logic desired here */
        // get v.errors, which is an Object[]
        var errorsArr  = event.getParam("errors");
        for (var i = 0; i < errorsArr.length; i++) {
            console.log("error " + i + ": " + JSON.stringify(errorsArr[i]));
        }
    },

    handleClearError: function(component, event) {
        /* do any custom error handling
         * logic desired here */
    }
}


I dont knew why i am getting this error.
please help me on this. Thanks in advance.​​​​​​​
OnLoad function on RecordEditForm: 

handleLoad : function(component, event, helper){
        var record = event.getParams().recordUi.record;
        console.log("onLoad");
        console.log(JSON.parse(JSON.stringify(record)));
        var obj = JSON.parse(JSON.stringify(record));
        console.log('Record Id',obj.id);
        console.log('Record Id',obj.fields.EmploymentStatus__c.value);
        var fieldValue = obj.fields.EmploymentStatus__c.value;
        if(fieldValue === 'C2C'){
            component.set("v.vendorDetailsFlag", true);
        }
        else {
            component.set("v.vendorDetailsFlag", false);
        }
        
    },
Onchange Event on InputField:

    onchangeCalled : function(component, event, helper){
        
        component.set("v.spinnerFlag",true);
        window.setTimeout(
            $A.getCallback(function() {
                var val = event.getSource().get("v.value");
                if(val === 'C2C'){
                    component.set("v.vendorDetailsFlag", true);
                } else {
                    component.set("v.vendorDetailsFlag", false);
                }
                component.set("v.spinnerFlag",false);
            }), 500
        );
        
    },
Error1:
While loading a record onchangeCalled function is calling by default from onLoad and displaying spinners and all
Error2:
If I change a value on the field it is calling "handleLoad" too and "component.set("v.vendorDetailsFlag", true);" is failing because handleLoad is loading record  again.
 
<lightning:recordEditForm aura:id="recordViewForm"
                              objectApiName="Candidate"
                              recordId="{!v.recordId}"
                              recordTypeId=""
                              onload="{!c.handleLoad}"
                              onsubmit="{!c.handleSubmit}"
                              onsuccess="{!c.handleSuccess}"
                              >
 
<lightning:inputfield name="employmentStatus" aura:id="employmentStatus" fieldName="EmploymentStatus__c" onchange="{!c.onchangeCalled}"/>

Please help me on this
Hi All,

I am using lightning component form. I am using below url for opening Lightning component as an URL with parameters using isURLAddressable interface

https://instance.lightning.force.com/lightning/cmp/c__candidateApplicationForm?c__recordId=a0p8A000000R74PQAS

If I am using URL for opening component as an app like below

https://instance.lightning.force.com/c/c__candidateApplicationFormApp.app?c__recordId=a0p8A000000R74PQAS

I am getting an error like state is not defined in pagereference or url not found error.

Please advise how to use an URL for opening lightning component app with parameters.

 
I am using a hyperlink formula field for opening the record edit page. When I am displaying that formula field in lightning component, it is returning total formula not a display name of that formula field. 

can anyone help me with this?
Hi I am using force:navigateTosObject.

 
createRecord : function (component, event, helper) {
        var navEvt = $A.get("e.force:navigateToSObject");
        var recordId = event.target.id;
        navEvt.setParams({
            "recordId": recordId,
            "slideDevName": "detail"
        });
        navEvt.fire();
    }

I want to open this navigaton in a new window. But my code is opening in the same window.
I searched in google but I didn't find any solution for this. Please help me with this.
Hi, I am very interested to know how we can make it available our salesforce mobile app in google store.

Correct me if I am wrong,

Generally, We all create appexchange applications after our implementation is done. But I am wondering what we can install appexchange app's as a package only in salesforce org. 

But I want to know how we can build a salesforce mobile application that has to be installed like a google app.
Hi all.

1. I have a requirement to open Task page to create a task with some default values in LWC.
How below code works in LWC
createAcountContactEvent.setParams({ "entityApiName": "Contact", "defaultFieldValues": { 'Phone' : '415-240-6590', 'AccountId' : '001xxxxxxxxxxxxxxx' }
2. How below URL works in LWC
'"/lightning/cmp/c__URL_CreateRecordCmp?objectName=Contact&FirstName=Astro&LastName=Nomical&AccountId={!Account.Id}"'
I used above URL, but not able to find a solution because i am getting this page is not available in Lightning or something.

Please help me on this.
Hi I am trying to Override CONVERT button on Lead with Lightning Web Component. But the issue is Override Properties is not Showing an option to Select a Lightning Component. I am adding screenshot for understanding my problem
User-added imagePlease do I need to change any settings or something, please suggest me a solution.
Hi i am using below trigger:
My requirement is like : When i am inserting Lead in bulk
1. if Found and duplicate in contact
2. if Found any duplicate in Lead

if found any duplicates either in Contact or Lead then insert Non_Approved_Lead . I am using below code
trigger compareMultipleFieldLead on Lead (before insert) {
    List<Non_Approved_Leads__c> nonAplFinal = new List<Non_Approved_Leads__c>();
    List<Lead> errorLeadList = new List<Lead>();
    set<string> newEmailSet = new set<string>();
    
    
    set<WrapperClassWrapperClass> dbWrapperSet = new set<WrapperClassWrapperClass>();
    set<WrapperClassWrapperClass> newWrapperSet = new set<WrapperClassWrapperClass>();
    
    Map<String, String> mapLeadList = new Map<String, String>();
    List<Lead> leadInsertBeforeContactCheck = new List<Lead>();
    List<Lead> leadRejectList = new List<Lead>();
    List<Lead> listDumpLeads = new List<Lead>();
    
    set<string> emailSetForContactCheck = new set<string>();
    List<Lead> leadInsertAfterContactCheck = new List<Lead>();
    /* ********************************handling New records *************************************************** */
    if(trigger.isBefore && trigger.isInsert){
        for(lead ldRecord : trigger.new){
            
            WrapperClassWrapperClass iKey = new WrapperClassWrapperClass(ldRecord.Email, ldRecord.ownerid);
            
            if(newWrapperSet.contains(iKey)){
                system.debug('Found Duplicate Record'+ldRecord);
                leadRejectList.add(ldRecord);
                
            } else {
                listDumpLeads.add(ldRecord);
                newEmailSet.add(ldRecord.Email);
                newWrapperSet.add(iKey);
                //owneridSet.add(ownerid);
                system.debug('ikey is  --'+iKey);
            }
        }
        /* ********************************handling old records *************************************************** */
        for(Lead dbLead : [select id, LastName, email, phone, company, ownerid from lead where email IN: newEmailSet]){
            system.debug('came to query');
            dbWrapperSet.add(new WrapperClassWrapperClass(dbLead.Email, dbLead.ownerid));
        }
        for(lead ldRecord : listDumpLeads){
            system.debug('came to second loop iterate ove new list');
            
            WrapperClassWrapperClass iKey = new WrapperClassWrapperClass(ldRecord.Email, ldRecord.ownerid);
            system.debug('ikey is  --'+iKey);
            
            if(dbWrapperSet.contains(iKey)) {
                leadRejectList.add(ldRecord);
            }
            
            else {
                // mapLeadList.put(ldRecord.Email, ldRecord);
                emailSetForContactCheck.add(ldRecord.Email);
                leadInsertBeforeContactCheck.add(ldRecord);   
            }
            
        }
    }  
    system.debug('-----email list for duplicates'+emailSetForContactCheck.size());
    system.debug('lead Reject List after check in Leads'+leadRejectList.size());
    // Handling Contacts from lead filterd dump list
    List<Contact> consList;
    Set<String> emailSetContact=new Set<String>();
    if(emailSetForContactCheck.size()>0){
        consList = [select id, email from contact where email IN:emailSetForContactCheck];
        if(consList.size()>0){
        for(Contact con : consList ){
            emailSetContact.add(con.email);
            mapLeadList.put(con.email, con.Id);
        }
    }
    }
    system.debug('list lead dumps'+listDumpLeads.size());
    for(Lead ld:listDumpLeads){
        if(emailSetContact.size()>0 && emailSetContact != null && emailSetContact.contains(ld.Email)){
            system.debug('which contact contacins this email id'+mapLeadList.get(ld.email));
            leadRejectList.add(ld);
        }else {
            leadInsertAfterContactCheck.add(ld);
        }
    }   
    system.debug('lead Insert Before Contact Check'+leadInsertBeforeContactCheck.size());
    system.debug('lead Reject List after contact check also'+leadRejectList.size());
    system.debug('Final Lead List'+leadInsertAfterContactCheck.size());
    /* ******************************************* Creating Non Approved Leads for Duplicate Leads ******************************************** */     
    for(Lead ldRecord:leadInsertAfterContactCheck){
        Non_Approved_Leads__c nonApl = new Non_Approved_Leads__c(name = ldRecord.FirstName+' '+ldRecord.LastName,
                                                                 Email__c = ldRecord.Email,
                                                                 Phone__c = ldRecord.Phone,
                                                                 Direct_Phone__c = ldRecord.Direct_Phone__c,
                                                                 Lead_Contact_Job_Title__c = ldRecord.Lead_Contact_Job_Title__c,
                                                                 Lead_LinkedIn_Profile__c = ldRecord.Lead_LinkedIn_Profile__c,
                                                                 Personal_Email__c = ldRecord.Personal_Email__c,
                                                                 Comments__c = ldRecord.Comments__c,
                                                                 Website__c = ldRecord.Website,
                                                                 Title__c = ldRecord.Title,
                                                                 Status__c = ldRecord.Status, 
                                                                 Industry__c = ldRecord.Industry,
                                                                 Description__c = ldRecord.Additional_Contact_Information__c, 
                                                                 Company__c = ldRecord.Company, 
                                                                 Street__c = ldRecord.Street,
                                                                 City__c = ldRecord.City,
                                                                 State__c = ldRecord.State,
                                                                 Zip_Code__c = ldRecord.PostalCode, 
                                                                 Country__c = ldRecord.Country,
                                                                 ownerid = ldRecord.ownerid
                                                                );
        nonAplFinal.add(nonApl);
    }
    doCalloutFromFuture.callFromDupeTrigger(nonAplFinal);
    //insert nonAplFinal; // Inserting non approve Leads 
    //system.debug('-------insert non approved leads'+nonAplFinal);
    /* ******************************************* showing add Error for final Dupe List ******************************************** */ 
        for(Lead ld:leadRejectList){
            System.debug('contained duplicate trigger');
            ld.addError('This lead is existed');
    }
}

The error is, if it found any duplicate error it is showing addError message and not able to found inserted Non_Approved_Leads
I checked logs Non_Approved_Leads id's are showing but not able to find it. Please help me on this.
 
Hi I have a requirement like,

1. When a new lead is creating check for Duplicates in both Lead(Based on Email and Ownerid) and Contact(Based on Email).
if found any duplicate it has to show an error message and will store that Duplicate lead in Temp_Lead__c object.
2. When a User uploading bulk leads using DataLoader or Import Wizard, insert new leads and for duplicate leads show some error and store those Leads in Temp_Lead__c.

Which approach is better, please suggest me an Idea.
There is a button on a page, then click on it it will open a standard contact page for creating a new contact. I am using below code in javascript 
navigateToNewRecordPage() {
        // Opens the new Account record modal
        // to create an Account.
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'
            }
        });

How we can pass some field values into that page. Values like accountId, phone, email etc. Can anyone help me with this? Thank you!
 
I am using the below code and placed that component in the Home page using app builder. But it is displaying No Data available.
 
<template>
    <template if:true={contact}>
        <lightning-layout vertical-align="center">
            <lightning-layout-item padding="around-small">
                <p>{contact.Name}</p>
                <p>{contact.Title}</p>
                <p>
                    <lightning-formatted-phone
                        value={contact.Phone}
                    ></lightning-formatted-phone>
                </p>
            </lightning-layout-item>
        </lightning-layout>
    </template>
    <template if:false={contact}
        ><p>No contact data available.</p></template
    >
</template>

js code:
import { LightningElement, api } from 'lwc';

export default class ContactTile extends LightningElement {
    @api contact;
    
}

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

Where i am doing a mistake.User-added image​​​​​​​
How to get field createdby for a custom field.....
User-added image
We have a requirement for uploading lead. After inserting leads either through import wizard or dataloader, owner should be notified.

But the issue is sending too many emails to single users if he owned too many records.

How we can send single email for owner who owned too many records.

Ex: 20 owners for 200 records. Suppose first user has 10 records, then send single email to that owner instead of sending 10 emails to the same user(that mail has to include all 10 records info like Name, Company, id etc....).

We tried using for loop to create a mail body for all those 10 rcords for single owner. 

In this scenario there are 20 owners so my code is creating 20 mail bodies. Then it is creating 20 single email message methods. Exceeding limit.
Is there any option to avoid this limit??

Pls suggest me a solution...

Thank you!
Hi i am getting below error :
21:07:14:009 FATAL_ERROR System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set

Apex class:
@RestResource(urlMapping='/LeadManagement')
global with sharing class LeadManagement {
    @HttpPost
    global static LeadWrapper.ResposeWrappper LeadPost(){
        RestRequest req = RestContext.request;
        system.debug('----------hiiiiiiiii');
        String reqresponse = req.requestBody.toString().replace('{"size":124,"totalSize":124,"done":true,"queryLocator":null,"entityTypeName":"LeadWrapper.RequestWrappper","records":','');
        system.debug('---------'+reqresponse);
        List<LeadWrapper.RequestWrappper> objRequest =  (List<LeadWrapper.RequestWrappper>)JSON.deserialize(reqresponse, 
                                                                                                List<LeadWrapper.RequestWrappper>.class); 
        /*LeadWrapper.RequestWrappper[]  delegationMap = (LeadWrapper.RequestWrappper[])JSON.deserialize(req.requestBody.toString(), LeadWrapper.RequestWrappper[].class);*/
        system.debug('----------'+objRequest);
        // Checking the requested prameters are not null
        List<Lead> insertLeads = new List<Lead>();
        if(objRequest != null){
            for(Lead ld:getLeadMapping(objRequest)){
                insertLeads.add(ld);
            }
            Schema.SObjectField ftoken = Lead.Fields.External_Id__c;
            Database.UpsertResult[] srList = Database.upsert(insertLeads, false);
           /* for (Database.SaveResult sr : srList) {
                if (sr.isSuccess()) return new LeadWrapper.ResposeWrappper('Successfully inserted','');   
            } */
            return new LeadWrapper.ResposeWrappper('Successfully inserted','');   
        }
        else 
            return new LeadWrapper.ResposeWrappper('','No data to insert');  
    } //method
    private static List<Lead> getLeadMapping(LeadWrapper.RequestWrappper[] objRequest){
        List<Lead> lstLead = new List<Lead>();
        for(LeadWrapper.RequestWrappper lst:objRequest){
            Lead ld = new Lead(FirstName = lst.FirstName, 
                        LastName =lst.LastName, 
                        Company = lst.CompanyName,
                        Email = lst.Email,
                        Phone = lst.Phone,
                        Marketing_Rep_Name__c = lst.MarketingRepName,
                        LeadSource = lst.LeadSource,
                        Street = lst.Street,
                        City = lst.City,
                        State = lst.State, 
                        Country = lst.Country,
                        External_Id__c = integer.valueOf(lst.External_Id));
            lstLead.add(ld);
        }
        return lstLead;
    }
} //class

Wrapper Class:
global class LeadWrapper {
    global class RequestWrappper {
        global String FirstName;
        global String LastName;
        global String CompanyName;
        global String Email;
        global String Phone;
        global String MarketingRepName;
        global String LeadSource;
        global String Street;
        global String City;
        global String State;
        global String Country;
        global String External_Id;
    }
    global class ResposeWrappper{
        global String SuccessMsg;
        global String ErrorMsg;
        
        global ResposeWrappper(String SuccessMsg, String ErrorMsg){
            this.SuccessMsg = SuccessMsg;
            this.ErrorMsg = ErrorMsg;
        }
    }
}
global class AccountIdGeneration implements Database.Batchable<sObject>,Database.Stateful{
    global String query ;
    List<Account> accountList = new List<Account>();
    global AccountIdGeneration(){
        query = 'Select id, Name, website from account where website != null';
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<account> scope){
        List<account> lstAccount = new List<account>(); 
        for(account acc : scope){
           lstAccount.add(acc);
            
        }
        accountList.addAll(lstAccount);
    }
    global void finish(Database.BatchableContext BC){
        String finalString = 'Generated Id, website, Account Id, Name \n';
        System.debug('--accountList Size---'+accountList.size());
        /*-------------------- Forming Excel String ---------------*/
        for(account acc : accountList){
            Blob cryptoKey = Blob.valueOf('abcdefghijklmnopqrstuvwxyzabcdef');
            // Converting website to blob
            Blob data = Blob.valueOf(acc.website);
            Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
            String encryptedDataStr = EncodingUtil.base64Encode(encryptedData); 
            String key = encryptedDataStr.replaceAll('[^a-zA-Z\\s]', '');
            String str = acc.website.SubStringBefore('.');
            String finalID = '';
            if(str.length() >= 4 ){ finalID = str.substring(0, 4).toUppercase()+key.substring(30, 32).toUppercase(); }
            else if(str.length() < 4 && str.length() == 3){ finalID = str.substring(0, 3).toUppercase() +key.substring(29, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 2){ finalID = str.substring(0, 2).toUppercase()+key.substring(28, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 1){ finalID = str.substring(0, 1).toUppercase()+key.substring(27, 32).toUppercase();} 
            String recordString = finalID+','+acc.website+','+ acc.id+','+acc.Name+'\n';
            finalString  =  finalString + recordString;    
            
        }
        System.debug('--finalString-'+finalString);
        /*-------------------- Forming Email ---------------*/
        
        Messaging.EmailFileAttachment attachmentFile = new Messaging.EmailFileAttachment();
        blob accountList = Blob.valueOf(finalString);
        string csvname= 'accListFile.csv';
        attachmentFile.setFileName(csvname);
        attachmentFile.setBody(accountList);
        Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
        String email1 = 'test@gmail.com';
        String[] toAddresses = new list<string> {email1};
            String subject ='Account Generated Id List';
        email.setSubject(subject);
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{attachmentFile});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
We are using this code for generating a 6-bit id for an account. When executing, the Finish method is not sending any email. logs showing batch apex status as "Ending position out of Bounds: 32".

Note: I am processing more than 10k records.

Please help me with this. Thanks in advance.
 
Hi 

I'm new to this area & finding the instructions in this unit very thin on the ground. I haven't even got to the challenge yet, I'm trying to follow along in the unit example.

It links to these instuctions to follow from GitHub:
Set up your environment. Follow the steps in the Quick Start: Lightning Web Components Trailhead project. The steps include:
Enable Dev Hub in your Trailhead Playground
Install Salesforce CLI
Install Visual Studio Code
Install the Visual Studio Code Salesforce extensions, including the Lightning Web Components extension
If you haven't already done so, authenticate with your hub org and provide it with an alias (myhuborg in the command below):
sfdx force:auth:web:login -d -a myhuborg
Clone the repository:
git clone https://github.com/trailheadapps/ebikes-lwc cd ebikes-lwc
Create a scratch org and provide it with an alias (ebikes in the command below):
sfdx force:org:create -s -f config/project-scratch-def.json -a ebikes
Push the app to your scratch org:
sfdx force:source:push
Assign the ebikes permission set to the default user:
sfdx force:user:permset:assign -n ebikes
Load sample data:
sfdx force:data:tree:import --plan ./data/sample-data-plan.json
Open the scratch org:
sfdx force:org:open
In Setup, under Themes and Branding, activate the Lightning Lite theme.
In App Launcher, select the E-Bikes app.

I'm afraid I need a bit more direction at this point, like clone a repository, cool there's a link, what do i do with it? where do i put it?

If someone could go through the steps & elaborate would be great, with a step by step guide of what to do where. 

I'm completely new to coding & so far have been able to recognise the patterns & work it out for previous modules, but this is using a whole new tool with no instructions of how to use it.

Any help would be much appreciated
Thanks
How to get field createdby for a custom field.....
User-added image
I am using equals and hashcode methods. I am unable to include hashcode method in test class.
public class WrapperClassWrapperClass
{
    public string lastName;
    public string email;
    public string phone;
    public string company;
    public string ownerid;
    public WrapperClassWrapperClass(string leadName , string leadEmail, string leadphone , string leadcompany, string leadOwnerId){
            this.lastName = leadName != null ? leadName:null;
            this.email = leadEmail !=null ? leadEmail:null;
        	this.phone = leadphone != null ? leadphone:null;
        	this.company = leadcompany != null ? leadcompany:null;
        	this.ownerid = leadOwnerId != null ? leadOwnerId:null;
        }
    public Boolean equals(Object obj) {
        if (obj instanceof WrapperClassWrapperClass) {
            WrapperClassWrapperClass p = (WrapperClassWrapperClass)obj;
            return ((((lastName==p.lastName) && (email==p.email) && (phone==p.phone) && (company==p.company))||
                    (((lastName==p.lastName) &&  (company==p.company)) &&
                     ((email==p.email) || (phone==p.phone))))&& ownerid==p.ownerid);
        }
        return false;
    }
    public Integer hashCode() {
        return !test.isRunningTest() ? (1 * (lastName.hashCode() + phone.hashCode() + company.hashCode() + ownerid.hashCode())) ^ email.hashCode() : 123456;     
    }
}

I am calling using this wrapper class in a trigger.
 
I have requirement -- 
Find out the duplicate records based on Three different fields.
1. Email, 2. Phone, 3. OwnerId

if 1 and 2 satisfied but the owner is different then it has to allow for Lead creation otherwise add an Error.

How we can achieve this.
I have a VF page. There is a Link called Add Contact on VF page. When user clicks on Add contact, it should redirected to standard contact form page,. Then user enter some data and clicks on save. When he clicks on save, it should return Recordid. How i can acieve this. Is there any possibilities. Please help me on this.
How can we get the note related to a particular task object using SOQL. i have a requirement like there is a note on task, whenever i tried to create new note for the same task it has to append with old note values.
User-added image 
I have Contact and Opportunity. How we can display related opportunities based on contact id. Any query any code. Please suggest me. 
Thank you!
if(contact_number != 'UnKnown'){
    window.open('/003/e?name_firstcon2='+firstname+'&name_lastcon2='+lastname+'&con10='+contact_number, '_parent');
        } else {
            window.open('/003/e', '_parent'); 
        }
It is populating field values in classic. But in lightning it is not populating values, Only contact creation page is poping up.
 
I worte test class for below rest class, but some return response lines are not covering in code coverage....below are my code...please help me how to include those lines.
Rest class:
@HttpPost 
    global static Lead_API_Wrapper.LeadCreationResposeWrappper doPost(){
        try{
            RestRequest req = RestContext.request;
            Lead_API_Wrapper.LeadCreationRequestWrappper objRequest =  (Lead_API_Wrapper.LeadCreationRequestWrappper)JSON.deserialize(req.requestBody.toString(), 
                                                                        Lead_API_Wrapper.LeadCreationRequestWrappper.class);
            if(objRequest != null && (objRequest.PrimaryEmail != null || objRequest.PhoneNumber != null)){
                List<User> lstUser = [SELECT Id FROM User WHERE UserName = :objRequest.userEmail OR Email =: objRequest.userEmail];
                if(lstUser.isEmpty()) return new Lead_API_Wrapper.LeadCreationResposeWrappper(null, null, false, '', 'User does not exist. Please contact Salesforce Admin!'); 
                List<Lead> lstLead = new List<Lead>{getLeadMapping(objRequest, lstUser[0].Id)};
                Lead dupeLead = null;
                for(Datacloud.FindDuplicatesResult findDupeResult : Datacloud.FindDuplicates.findDuplicates(lstLead)) {
                    for(Datacloud.DuplicateResult dupeResult : findDupeResult.getDuplicateResults()){
                        for(Datacloud.MatchResult matchResult : dupeResult.getMatchResults()){
                            for(Datacloud.MatchRecord matchRecord : matchResult.getMatchRecords()) {
                                dupeLead = (Lead)matchRecord.getRecord();
                            }
                        }
                    }
                }
                dupeLead = dupeLead != null && dupeLead.Id != null ? getLead( dupeLead.Id) : null;            
                if(dupeLead == null){
                    Lead objLead = getLeadMapping(objRequest, lstUser[0].Id);
                    insert objLead;
                    return new Lead_API_Wrapper.LeadCreationResposeWrappper(getLead(objLead.Id), null, true, 'Lead created successfully in Salesforce.', '');
                } else if(dupeLead.OwnerId != lstUser[0].Id){
                    Temp_Lead__c objTempLead = getTempLeadMapping(objRequest, lstUser[0].Id);
                    insert objTempLead;
                    return new Lead_API_Wrapper.LeadCreationResposeWrappper(null, objTempLead, false, '', 'Lead already existed in Salesforce Created By : '+ dupeLead.Owner.Name +' and your Lead Information is submitted for approval');
                } else {
                    return new Lead_API_Wrapper.LeadCreationResposeWrappper(dupeLead, null, false, '', 'Lead already existed in Salesforce');
                }
            }
            return new Lead_API_Wrapper.LeadCreationResposeWrappper(null, null, false, '', 'Invalid Data.');
        }catch(Exception ex){
            return new Lead_API_Wrapper.LeadCreationResposeWrappper(null, null, false, '', ex.getMessage());
        }
    }
    @TestVisible
    private static Lead getLead(String leadID){
        return [SELECT Id, Company, Name, Status, CreatedDate, Owner.Name, OwnerId FROM Lead WHERE Id =: leadID];
    }
    @TestVisible
    private static Temp_Lead__c getTempLeadMapping(Lead_API_Wrapper.LeadCreationRequestWrappper objRequest, String ownID){
        return new Temp_Lead__c(First_Name__c = objRequest.FirstName, Last_Name__c=objRequest.LastName, 
                                Phone_Number__c = objRequest.PhoneNumber, Primary_Email__c = objRequest.PrimaryEmail,
                                Company_Name__c = objRequest.CompanyName, AddressLine1__c = objRequest.AddressLine1, 
                                AddressLine2__c = objRequest.AddressLine2, City__c = objRequest.City,
                                State__c = objRequest.State, ZIPCode__c = objRequest.ZIPCode, 
                                Country__c = objRequest.Country, EstimatedMRR__c = objRequest.EstimatedMRR,
                                EstimatedCloseDate__c = objRequest.EstimatedCloseDate, OwnerId = ownID);
    }
    @TestVisible
    private static Lead getLeadMapping(Lead_API_Wrapper.LeadCreationRequestWrappper objRequest, String ownID){
        String street = objRequest.AddressLine1;
        street = String.isNotBlank(street) && String.isNotEmpty(street) ? + street + ', ' + objRequest.AddressLine2 : objRequest.AddressLine2;
        return new Lead(FirstName = objRequest.FirstName, LastName =objRequest.LastName, 
                        Phone = objRequest.PhoneNumber, Email = objRequest.PrimaryEmail, OwnerId = ownID,
                        Company = objRequest.CompanyName, Street = street, City = objRequest.City, 
                        State = objRequest.State, PostalCode = objRequest.ZIPCode, Country = objRequest.Country
                        /*EstimatedMRR__c = objRequest.EstimatedMRR, EstimatedCloseDate__c = objRequest.EstimatedCloseDate*/);
            
    }
}
Wrapper class:
global class Lead_API_Wrapper {
    global class LeadCreationRequestWrappper {
        global String userEmail;
        global String CompanyName;
        global String FirstName;
        global String LastName;
        global String PrimaryEmail;
        global String PhoneNumber;
        global String AddressLine1;
        global String AddressLine2;
        global String City;
        global String State;
        global String ZIPCode;
        global String Country;
        global Decimal EstimatedMRR;
        global Date EstimatedCloseDate;
    }
    
    global class LeadCreationResposeWrappper{
        global Lead lead;
        global Temp_Lead__c TempLead;
        global Boolean IsSuccess;
        global String SuccessMsg;
        global String ErrorMsg;
        
        global LeadCreationResposeWrappper(Lead lead, Temp_Lead__c TempLead, Boolean IsSuccess, String SuccessMsg, String ErrorMsg){
            this.lead = lead;
            this.TempLead = TempLead;
            this.IsSuccess = IsSuccess;
            this.SuccessMsg = SuccessMsg;
            this.ErrorMsg = ErrorMsg;
        }
    }
}

Test class: 
@isTest
public class LeadManagementTestClass {
@testSetup static void testData() {
        //String userEmail = 'testuser1.user@user.com';
        User testUser1 = new user(LastName = 'Test_User1', Email = 'test.user1@user.com', Alias = 'Tcode', Username = 'testuser1.user@user.com', CommunityNickname = 'test12', LocaleSidKey = 'en_US', TimeZoneSidKey = 'GMT', ProfileID = '00e7000000198kn', LanguageLocaleKey = 'en_US', EmailEncodingKey = 'UTF-8');
                insert testUser1;        
    }
@isTest public static void testdoPost(){    
     String user1Email = 'test.user1@user.com';
     Decimal EstimatedMRR = null;
     Date EstimatedCloseDate = null;                 
     List<User> lstUser = [SELECT Id FROM User WHERE UserName = : user1Email OR Email =: user1Email];
     Test.startTest(); 
     RestRequest req = new RestRequest();
     RestResponse res = new RestResponse();
        req.addParameter('userEmail',user1Email);
        req.addParameter('CompanyName','xyz ');
        req.addParameter('FirstName','test ');
        req.addParameter('LastName','record ');
        req.addParameter('PrimaryEmail','test.record@xyz.com');
        req.addParameter('PhoneNumber','9999999999');
        req.addParameter('AddressLine1','lane 1');
        req.addParameter('AddressLine2','lane 2');
        req.addParameter('City','pune');
        req.addParameter('State','Maharastra');
        req.addParameter('ZIPCode','411014');
        req.addParameter('Country','India');
        req.addParameter('EstimatedMRR',string.valueOf(EstimatedMRR));
        req.addParameter('EstimatedCloseDate',string.valueOf(EstimatedCloseDate));
        req.requestURI = 'services/apexrest/LeadManagement/*';  
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;
        req.requestBody = Blob.valueOf(JSON.serialize(req.params)); 
        Lead_API_Wrapper.LeadCreationResposeWrappper result = LeadManagement.doPost();
        Lead_API_Wrapper.LeadCreationRequestWrappper objRequest =  (Lead_API_Wrapper.LeadCreationRequestWrappper)JSON.deserialize(req.requestBody.toString(), Lead_API_Wrapper.LeadCreationRequestWrappper.class);         
        LeadManagement.getTempLeadMapping(objRequest, lstUser[0].id);                                                               
        LeadManagement.getLeadMapping(objRequest, lstUser[0].id);
     Test.stopTest();
    }
}