• Sai Vineeth Maddula
  • NEWBIE
  • 105 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 58
    Questions
  • 38
    Replies
I have a requirement that after inserting a record in Campaign Account(Custom Object lookup with Account) it should check the Campaign Account Name with opportunities related to the Account. I was able to achieve the functionality using the trigger. But I wanted to optimize my code so can someone help me with my code.
 
public class CreateOppAfterCAInsertionHelper {
    public string name;
    public Id accId;
    public void insertOpp(List<Campaign_Account__c> campaignAccList) {
        Set<Id> accIds = new Set<Id>();
        List<Opportunity> oppList = new List<Opportunity>();
        List<Opportunity> updatedOpps = new List<Opportunity>();
        for(Campaign_Account__c campAcc : campaignAccList) {
            if(campAcc.Account__c != NULL) {
                accIds.add(campAcc.Account__c);
                name = campAcc.Name;
                accId = campAcc.Account__c;
            }
        }
        oppList = [SELECT Name, AccountId, Count__c 
                   FROM Opportunity 
                   WHERE AccountId IN:accIds AND Name =: name];
        if(oppList.size() > 0) {
            for(Opportunity opp : oppList) {
                opp.Count__c  = opp.Count__c + 1;
                updatedOpps.add(opp);
            }
        }
        if(oppList.size() == 0) {
            Opportunity newOpp = new Opportunity();
            newOpp.Name = name;
            newOpp.StageName = 'Prospecting';
            newOpp.CloseDate = date.today();
            newOpp.AccountId = accId;
            insert newOpp;
        }
        if(updatedOpps.size() > 0) {
            update updatedOpps;
        }
    }
}
I want to avoid the highlighted lines. Need help thank you...
 
Hi, I have a VF page with an input text box when I enter some string it should check whether the record exists or not. I was able to achieve the functionality but in my test class, I was not able to cover a few lines.
public class searchAndLinkRecordsToAccount {
    public String searchString{get;set;}
    public Integer count;
    public List<Account_Relation__c> accRelList{get;set;}
    public searchAndLinkRecordsToAccount(ApexPages.StandardController stdController) {
    }
    public void search() {
        List<Account_Relation__c> updatedRecordsList = new List<Account_Relation__c>();
        List<Account_Relation__c> insertedRecordsList = new List<Account_Relation__c>();
        accRelList = [SELECT Id, Name, Count__c, Latest_Submitted_Date__c 
                      FROM Account_Relation__c 
                      WHERE Account__c =:ApexPages.currentPage().getParameters().get('id') AND Name =:searchString];
        if(accRelList.size() > 0) {
            for(Account_Relation__c rel : accRelList) {
                rel.Count__c = rel.Count__c + 1;
                rel.Latest_Submitted_Date__c = Datetime.now();
                updatedRecordsList.add(rel);
                ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,'Record found with the Search String'));
            }
        }
        if(accRelList.size() == 0){
            Account_Relation__c accRel = new Account_Relation__c();
            accRel.Name = searchString;
            accRel.Account__c = ApexPages.currentPage().getParameters().get('id');
            accRel.Count__c = 1;
            accRel.Latest_Submitted_Date__c = Datetime.now();
            insertedRecordsList.add(accRel);
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,'Record inserted and sent for Approval'));
        }
        if(updatedRecordsList.size() > 0) {
            update updatedRecordsList;
        }
        if(insertedRecordsList.size() > 0) {
            insert insertedRecordsList;
        }
    }
}
//Test Class

@isTest
public class searchAndLinkRecordsToAccountTest {
    public static testMethod void method1() {
        Account acc = new Account(Name='Test Acc');
        insert acc;

        Account_Relation__c accRel1 = new Account_Relation__c(Name='Test Relation');
        insert accRel1;
        acc.AnnualRevenue = 500;
        update acc;
        
        Test.startTest();
        ApexPages.StandardController stdController = new ApexPages.StandardController(acc);
        searchAndLinkRecordsToAccount recsToAcc = new searchAndLinkRecordsToAccount(stdController);
        recsToAcc.search();
        Test.stopTest();
    }
}
I was not able to cover the highlighted lines of code. Please help. Thanks in Advance.
Hi, I've built a trigger that will update the Owner for the Account and its related contacts based on the User Lookup field in the Account. I was able to update the Owner of related contacts with an update in the Account.
If I change the Account in any of the Contact then the new Accounts owner should be added as Contacts Owner. I tried using the Trigger.OldMap. Can someone help me with what needs to be changed in my trigger...
trigger AccountOwnerUpdate on Account (before insert, before update) {
    Set<Id> accIds = new Set<Id>();
    List<Contact> updatedConList = new List<Contact>();
    Map<Id, String> newOwnerIds = new Map<Id, String>();
    
    
    List<Contact> conList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: accIds];
    for(Account acc : trigger.new) {
        accIds.add(acc.Id);
        newOwnerIds.put(acc.Id, acc.Coverage_Lead__c);
        
        if(acc.Coverage_Lead__c != NULL) {
            acc.OwnerId = acc.Coverage_Lead__c;
        }
        if(acc.Coverage_Lead__c == NULL){
            acc.OwnerId = acc.LastModifiedById;                
        }
    }
    if(trigger.isUpdate) {
        for(Account acc : trigger.new) {
            for(Contact con : conList) {
                if(con.AccountId!= NULL) {
                    if(trigger.oldMap.get(con.Id).AccountId != con.AccountId) {
                        accIds.add(con.AccountId);
                    }
                }
                accIds.add(trigger.oldMap.get(con.Id).AccountId);
            }
        }
    }

    for(Account accs : [SELECT Id, LastModifiedById, (SELECT Id, Owner.Id, AccountId FROM Contacts) FROM Account WHERE Id IN:accIds]) {
        if(newOwnerIds.get(accs.Id) != NULL) {
            for(Contact con : accs.Contacts) {
                con.OwnerId = newOwnerIds.get(accs.Id);
                updatedConList.add(con);
            }
        }
        if(newOwnerIds.get(accs.Id) == NULL) {
            for(Contact con : accs.Contacts) {
                con.OwnerId = accs.LastModifiedById;
                updatedConList.add(con);
            }   
        }
        
    }
    update updatedConList;
}
Thanks in Advance.
Hi, I have a requirement where I am sending emails to Lead Email (Field in Lead) using a batch class. After sending the email I want to update the checkbox value to TRUE if the email is sent and FALSE if the email is not sent..
I've written the batch class but I am not sure how to update the field after email... Can someone help me with how to achieve this...
global class SendEmailToLeadBatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, Name, Email, Age_of_Lead__c, Email_Sent__c FROM Lead WHERE Age_of_Lead__c > 7 AND LeadSource = \'Partner Referral\'';
        return database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Lead> scope) {
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        for(Lead ldEmail : scope) {
            String body = 'The Lead '+ldEmail.Name+' age is '+ldEmail.Age_of_Lead__c+' Days';
            //String body = 'Hello '+ldEmail.Name+' is created '+ldEmail.Age_of_Lead__c+' Days;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            sendTo.add(ldEmail.Email);
            mail.setToAddresses(sendTo);
            mail.setSaveAsActivity(false);
            mail.setSubject('Hello '+ldEmail.Name+'');
            mail.setHtmlBody(body);
            emails.add(mail);
        }
        Messaging.SendEmailResult[] result = Messaging.sendEmail(emails);
        if(result[0].success) {
            
        }
    }
    global void finish(Database.BatchableContext BC) {
        
    }
}



 
Hi, Can someone help me with how to write a Test Class for the below Wrapper Class...
public class OppRelatedSolutionsController {
    public List<WrapperClass> wrapList{get;set;}
    public List<Solution__c> selectedRecords{get;set;}
    public OppRelatedSolutionsController(ApexPages.StandardController stdController) {
        wrapList = new List<WrapperClass>();
        for(Solution__c solRecs : [SELECT Name, Amount__c, Expected_Revenue__c FROM Solution__c WHERE Opportunity__c = NULL]) {
            wrapList.add(new WrapperClass(solRecs));
        }
        if(wrapList.size() <= 0) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'No Records found'));
        }
    }
    public pageReference saveRecords() {
        selectedRecords = new List<Solution__c>();
        for(WrapperClass wrapRecs : wrapList) {
            if(wrapRecs.selected == TRUE) {
                wrapRecs.sol.Opportunity__c = ApexPages.currentPage().getParameters().get('id');
                selectedRecords.add(wrapRecs.sol);
            }
        }
        update selectedRecords;
        if(selectedRecords.size() > 0) {
            pageReference ref = new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
            ref.setRedirect(true);
            return ref;
        }
        return null;
    }
    //Wrapper Class
    public class WrapperClass {
        public Solution__c sol{get;set;}
        public Boolean selected{get;set;}
        public WrapperClass(Solution__c s) {
            sol = s;
            selected = false;
        }
    }
}

I am trying to learn how to write Test Classes. So any response would be appreciated... Thanks in Advance.

 
I have a list of Opportunities that needs to send through email. In the email body, the list elements are displaying as (Rec1, Rec2, Rec3)...
But, I want to display is as,
  • Rec1
  • Rec2
  • Rec3
Is there any possibility that I can change the Email body. Any help would be appreciated...
Hi,
I have a requirement where I have a search box in VF Page which displays Contacts based on Search String. If there is only one record matches the string the page should automatically redirect to that Contact record.
I am using Page Reference and Param to get the Id from the Search String. But it's throwing an error says URL is broke.
//Controller
public class SearchContactsController {
    public List<Contact> conList{get;set;}
    public String search {get;set;}
    public String Id{get;set;}
    public PageReference contacts() {
        Id = ApexPages.currentPage().getParameters().get('id');
        conList = [SELECT Id, FirstName, LastName FROM Contact WHERE LastName =:search];
        if(conList.size() == 0) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'No Records Found'));
        }else {
            if(conList.size() == 1) {
                PageReference pr = new PageReference('/'+Id);
                pr.setRedirect(true);
                return pr;
            }
        }
        return null;
    }
}
//VF Page
<apex:page controller="SearchContactsController">
    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock >
            <apex:inputText value="{!search}" label="Search Contacts"/>
            <apex:commandButton value="Search" action="{!contacts}">
                <!--<apex:param name="id" assignTo="{!search}" value=""/>-->
            </apex:commandButton>
        </apex:pageBlock>
        <apex:pageBlock >
            <apex:pageBlockTable value="{!conList}" var="con">
                <apex:column headerValue="FirstName" value="{!con.FirstName}"/>
                <apex:column headerValue="LastName">
                    <apex:outputLink value="/{!con.Id}">{!con.LastName}
                        <apex:param name="id" assignTo="{!search}" value="{!con.Id}"/>
                    </apex:outputLink>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Can someone help me with what's wrong with my code. Thanks in Advance...
Hi,
I have a VF Page where I am calling multiple methods using different command buttons. I want to call all the methods in the class one after another with only one command button. Is it possible to call one method from another method which is in the same class...

Thanks in Advance...
Hi,

I want to display an error message for the user who doesn't have Read Access to Lead Object when he opens a VF Page without using a custom controller. Is it possible to achieve it from VF Page itself...
Thanks in Advance...
Hi,

I have a requirement in the Approval Process where it has multiple approvers assigned. When I submit the record for approval if 1st Approver approved and 2nd Rejected then the Approval Request should reach to 3rd Approver also...
I
knew that if any of the approvers rejects the record it will not go to the next approver. But, is there any possibility of achieving this...
Thanks in Advance...
Hi, 
I have a VF page where I need to display an error message using Custom Labels when the checkbox is not checked after hitting the save button. Can anyone help me how to use custom labels since I am using it for the first time...

Thanks in Advance.
Hi, I want my phone field to be auto-populated as below after record is saved.
+XX (XXX) XXX-XXXX

I've tried regex to format. But, it's working only if I enter a formatted phone number. Can someone help me how to format the phone upon saving the record... The regex function I used is...
^((\\+)(\\d{2})?\\s?\\(\\d{3}\\)\\s?\\d{3}\\-\\d{4})?$
Thanks in Advance...
Hi, I want my phone number field number to display the number in the format of +XX (XXX) XXX-XXXX. Can someone help me how to achieve this.

Thanks in Advance...
Hi,
I want to show/hide a specific field in an object when a picklist value is selected. Can someone help me how to implement this using script which I want to access using action function...

Thanks in Advance.
Hi,

I have a requirement where I need to display only 2 Contacts related to each Account in a list view. Can someone help me how to build the query for my requirement...

Thanks in Advance...
Hi, I am trying to populate Account Type on Contact by creating custom picklist 'Type' using Maps.

public class ContactAccountMap {
    public void accountMap() {
        Set<Id> accountIds = new Set<Id>();
        List<Contact> conList = [SELECT Id, Name, Type__c, AccountId FROM Contact];
        for(Contact con : conList) {
            accountIds.add(con.AccountId);
        }
        List<Account> accList = [SELECT Id, Name, Type FROM Account WHERE Id IN:accountIds];
        //System.debug('accounts'+accountIds);
        //System.debug('contacts'+conList);
        Map<Id,Account> accMap = new Map<Id,Account>([SELECT Id, Name, Type FROM Account WHERE Id in:accountIds]);
        for(Contact con : conList) {
            if(con.AccountId != NULL) {
                con.Type__c = accMap.get(con.AccountId).Type;
            }
        }
    }
}

The code doesn't throw any errors but the I am not getting the functionality. Can someone help me with this...

Thanks in advance...
Hi, I would like to validate the phone number field to accept only numbers except zeros.

Acceptable : 9987541452
Not Acceptable : 9010058471

Can someone help me achieve the functionality...

Thanks in advance...
I have a scenario where I have a Custom Object 'Owner Assignment' with fields Owner ID filled with different Users. I want to develop a trigger which will assign the Owner from 'Owner Assignment' object in Round Robin fashion whenever a Contact is created. Can someone help me build the logic for the above scenario since I am new to Salesforce...
Thanks in Advance...
Hi,

I would like to add opportunities whose Stage and Type is New Opportunity and New Business. I have added a new account record and these opportunities should be linked to the newly created account record.

//Batch Class

global class BatchForAddingOpps implements Database.Batchable<sObject> {
    List<Opportunity> oppList {get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Name, Type, StageName, CreatedDate 
                                         FROM Opportunity 
                                         WHERE Type = 'New Business' AND StageName = 'New Opportunity']);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> oppList) {
        List<Opportunity> newList = new List<Opportunity>();
        for(Opportunity opp : oppList) {
            opp.StageName = 'Closed Lost';
        }
        update oppList;
        System.debug('newList'+oppList);
    }
    global void finish(Database.BatchableContext BC) {
        
    }
}

I've got the opportunities but unable to add these opportunities to newly created account record...Can someone help me achieve this...

Thanks in advance.
Hi, I have two different triggers on the opportunity. One will update the Total Tasks custom field and another one creates a new task when the opportunity stage is set to 'Closed Won'. Can someone help me how to merge these two functionalities into one trigger...

//Trigger 1
trigger OpportunityTaskCount on Task (after insert, after update, after delete, after undelete) {
    Set<Id> oppList = new Set<Id>();
    Set<Id> tskList = new Set<Id>();
    List<Opportunity> updateList = new List<Opportunity>();
    if(trigger.isInsert || trigger.isUndelete) {
        for(Task tsk : trigger.new) {
            if(tsk.WhatId != NULL) {
                oppList.add(tsk.WhatId);
                tskList.add(tsk.Id);
            }
        }
    }
    if(trigger.isDelete || trigger.isUpdate) {
        for(Task tsk : trigger.old) {
            if(tsk.WhatId != NULL) {
                tskList.add(tsk.WhatId);
            }
        }
    }
    for (Opportunity opp : [SELECT Id, Name, Total_Tasks__c ,(SELECT Id, Status FROM Tasks) 
                            FROM Opportunity 
                            WHERE Id in : oppList]) {
                                opp.Total_Tasks__c = opp.Tasks.size();
                                updateList.add(opp);
                            }
    update updateList;
}

//Trigger 2
trigger ClosedOpportunityTrigger on Opportunity (before insert, before update) {
    List<Task> taskList = new List<Task>();
    for(Opportunity opp : trigger.new) {
        if(trigger.isInsert || trigger.isUpdate) {
            if(opp.StageName == 'Closed Won') {
                Task tsk = new Task();
                tsk.Subject = 'Follow Up Test Task';
                tsk.WhatId = opp.Id;
                taskList.add(tsk);
            }
        }
    }
    if(taskList.size() > 0) {
        insert taskList;
    }
}

Thanks in advance :)
Hi, I have a requirement where I am sending emails to Lead Email (Field in Lead) using a batch class. After sending the email I want to update the checkbox value to TRUE if the email is sent and FALSE if the email is not sent..
I've written the batch class but I am not sure how to update the field after email... Can someone help me with how to achieve this...
global class SendEmailToLeadBatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, Name, Email, Age_of_Lead__c, Email_Sent__c FROM Lead WHERE Age_of_Lead__c > 7 AND LeadSource = \'Partner Referral\'';
        return database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Lead> scope) {
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        for(Lead ldEmail : scope) {
            String body = 'The Lead '+ldEmail.Name+' age is '+ldEmail.Age_of_Lead__c+' Days';
            //String body = 'Hello '+ldEmail.Name+' is created '+ldEmail.Age_of_Lead__c+' Days;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            sendTo.add(ldEmail.Email);
            mail.setToAddresses(sendTo);
            mail.setSaveAsActivity(false);
            mail.setSubject('Hello '+ldEmail.Name+'');
            mail.setHtmlBody(body);
            emails.add(mail);
        }
        Messaging.SendEmailResult[] result = Messaging.sendEmail(emails);
        if(result[0].success) {
            
        }
    }
    global void finish(Database.BatchableContext BC) {
        
    }
}



 
I have a list of Opportunities that needs to send through email. In the email body, the list elements are displaying as (Rec1, Rec2, Rec3)...
But, I want to display is as,
  • Rec1
  • Rec2
  • Rec3
Is there any possibility that I can change the Email body. Any help would be appreciated...
Hi,

I want to display an error message for the user who doesn't have Read Access to Lead Object when he opens a VF Page without using a custom controller. Is it possible to achieve it from VF Page itself...
Thanks in Advance...
Hi, 
I have a VF page where I need to display an error message using Custom Labels when the checkbox is not checked after hitting the save button. Can anyone help me how to use custom labels since I am using it for the first time...

Thanks in Advance.
Hi,

I have a requirement where I need to display only 2 Contacts related to each Account in a list view. Can someone help me how to build the query for my requirement...

Thanks in Advance...
HI Experts,

Can anyone help me out, how can i send an email to public group users under a queue based on language. Thanks in advance
Hi, I am trying to populate Account Type on Contact by creating custom picklist 'Type' using Maps.

public class ContactAccountMap {
    public void accountMap() {
        Set<Id> accountIds = new Set<Id>();
        List<Contact> conList = [SELECT Id, Name, Type__c, AccountId FROM Contact];
        for(Contact con : conList) {
            accountIds.add(con.AccountId);
        }
        List<Account> accList = [SELECT Id, Name, Type FROM Account WHERE Id IN:accountIds];
        //System.debug('accounts'+accountIds);
        //System.debug('contacts'+conList);
        Map<Id,Account> accMap = new Map<Id,Account>([SELECT Id, Name, Type FROM Account WHERE Id in:accountIds]);
        for(Contact con : conList) {
            if(con.AccountId != NULL) {
                con.Type__c = accMap.get(con.AccountId).Type;
            }
        }
    }
}

The code doesn't throw any errors but the I am not getting the functionality. Can someone help me with this...

Thanks in advance...
Hi, I would like to validate the phone number field to accept only numbers except zeros.

Acceptable : 9987541452
Not Acceptable : 9010058471

Can someone help me achieve the functionality...

Thanks in advance...
I have a scenario where I have a Custom Object 'Owner Assignment' with fields Owner ID filled with different Users. I want to develop a trigger which will assign the Owner from 'Owner Assignment' object in Round Robin fashion whenever a Contact is created. Can someone help me build the logic for the above scenario since I am new to Salesforce...
Thanks in Advance...
Hi, I have a batch class which was running continuously form a long time. Can someone tell me how to abort the job? I have tried aborting from Setup -> Apex Jobs but that didn't work. Is there any other way to abort the job. Please tell me if there is any another way...

Thanks in Advance...
Hi, I have written a batch class to send email to contact owner with Contact details created by lead conversion. I have tried Test class for the same but it was not running. Can someone help me resolve this.

//Batch Class
global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    public List<Contact> conList {get;set;}
    public String body{get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead lead : scope) {
            conList = ([SELECT FirstName, LastName, Email, Phone
                        FROM Contact 
                        WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
        system.debug('Contacts List'+conList);
        String.join(conList,',');
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        body = 'Contact Details : ' +conList+ '';
        email.setPlainTextBody(body);
        email.setSubject('Contact Details from Converted Lead');
        email.setToAddresses(new string[]{'maddulasaivineeth@gmail.com'});
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        //system.debug('Contacts'+conList);
    }
    global void Finish(Database.BatchableContext BC) {
        
    }
}

//Test Class
@isTest
public class EmailWithAttachment_TC {
    public static testMethod void EmailWithAttachment_TCMethod() {
        Lead led = new Lead (
            LastName = 'Test Lead',
            Company = 'Test Company',
            Status = 'Open - Not Contacted'
        );
        insert led;
        Database.LeadConvert lc = new Database.LeadConvert();
        lc.setLeadId(led.Id);
        lc.setDoNotCreateOpportunity(false);
        lc.setConvertedStatus('Converted');
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        
    }
}
Hi, I have a batch class which should send email to contact owner which includes contacts created from lead conversion. I was unable to use contact owner email in ToAddress field. Here is my batch class..

//Batch Class

global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    public List<Contact> conList {get;set;}
    public String body{get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead lead : scope) {
            conList = ([SELECT FirstName, LastName, Email, Phone
                        FROM Contact 
                        WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
        system.debug('Contacts List'+conList);
        String.join(conList,',');
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        body = 'Contact Details : ' +conList+ '';
        email.setPlainTextBody(body);
        email.setSubject('Contact Details from Converted Lead');
        email.setToAddresses(new string[]{'maddulasaivineeth@gmail.com'});
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        //system.debug('Contacts'+conList);
    }
    global void Finish(Database.BatchableContext BC) {
        
    }

Can someone please help me write a test class for the same.

Thanks in Advance...
Hi, I have written a batch class where I would like to send an email to contact owner with the contact details created by lead conversion.

//Batch Class
global class LeadConversionEmail implements Database.Batchable <sObject>, Database.Stateful{
    //public List<Contact> conList {get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, LeadSource, ConvertedDate FROM Lead WHERE ConvertedContactId != NULL';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead ld : scope) {
            conList.add([SELECT FirstName, LastName 
                         FROM Contact 
                         WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
    }
    global void Finish(Database.BatchableContext BC) {
       messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String body = 'FirstName ' +conList.FirstName+ 'LastName ' +conList.LastName+ 'done'; 
    }
}

I am getting errors at body saying Variable does not exist. Can you help me resolve the problem and how to send email to contact owner.

Thanks in Advance.
Hi, I was stuck at a point where I need to get the contacts created by lead conversion. Can someone tell me how to query those contacts when a lead is converted...
I am new to salesforce so please help me do this.

Thanks in advance...
I have a Batch Class where it sends an email when Expiry Date (Custom Date Field) is today. The mail body contains the list of opportunities whose Expiry Date is Today. I have created a list and added the opportunities whose Expiry Date is today. But I am stuck at calling Opportunity Name from the List. Can someone help me to solve this.
//Batch Class

global class OpportunityExpiryDate_New implements DataBase.Batchable <sObject> {
    global DataBase.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Name, Expiry_Date__c  FROM Opportunity WHERE Expiry_Date__c = TODAY';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope) {
        List<Opportunity> oppList = new List<Opportunity>();
        for(Opportunity opp : scope) {
            if(opp.Expiry_Date__c == date.today()) {
                oppList.add(opp);
            }
        }
        update oppList;
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        String body = 'The Opportunity ' +oppList+ ' is expiring today.';
        email.setToAddresses(new String[]{'maddulasaivineeth@gmail.com'});
        email.setSubject('Opportunities Expiring Today');
        email.setPlainTextBody(body);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
    global void finish(Database.BatchableContext BC) {   
    }
}
Hi,
I have an apex trigger to count the total Opportunities related to an Account and Sum of Opportunity Amount related to Account. I am trying to implement "after undelete" in my trigger. But it isn't working. Can someone help to do this?
Below is my Trigger

trigger OpportunityCount on Opportunity (after insert, after delete, after update, after Undelete) {
    Map<Id, List<Opportunity>> acctIdOpptyListMap = new Map<Id, List<Opportunity>>();
    Set<Id> acctIds = new Set<Id>();
    List<Opportunity> opptyList = new List<Opportunity>();
    if(trigger.isUpdate && trigger.isInsert){
        for(Opportunity oppty : trigger.New){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(trigger.isDelete){
        for(Opportunity oppty : trigger.old){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(acctIds.size() > 0){
        opptyList = [SELECT Amount, AccountId 
                     FROM Opportunity 
                     WHERE AccountId IN : acctIds];
        for(Opportunity oppty : opptyList){
            if(!acctIdOpptyListMap.containsKey(oppty.AccountId)){
                acctIdOpptyListMap.put(oppty.AccountId, new List<Opportunity>());
            }
            acctIdOpptyListMap.get(oppty.AccountId).add(oppty); 
        }
       
        List<AggregateResult> lstResult = [SELECT AccountId, COUNT(Id) countId 
                                           FROM Opportunity 
                                           WHERE AccountId IN:acctIds
                                           GROUP BY AccountId];
        
        List<Account> lstAccount = new List<Account>();
        for(AggregateResult result:lstResult){
            Account acct = new Account (Id=(Id)result.get('AccountId'), Total_Opportunities__c = (Integer)result.get('countId'));
            lstAccount.add(acct);
        }
        update lstAccount;  
        
        List<Account> acctList = new List<Account>();
        acctList = [SELECT Total_Amount__c 
                    FROM Account 
                    WHERE Id IN: acctIds];
        for(Account acct : acctList){
            List<Opportunity> tempOpptyList = new List<Opportunity>();
            tempOpptyList = acctIdOpptyListMap.get(acct.Id);
            Double totalOpptyAmount = 0;
            for(Opportunity oppty : tempOpptyList){
                if(oppty.Amount != null){
                    totalOpptyAmount += oppty.Amount;
                }
            }
            acct.Total_Amount__c = totalOpptyAmount;
        }
        update acctList;
    }
}
Hi, I've created a custom, VF Page. It is having two pageBlockTables inside it. When I click a button "Get Records" the two tables should get refreshed. I am trying to refresh my entire page Block but that's not working n my case. I am attaching my page here along with a screenshot of my page.
 <apex:page standardController="Account" extensions="newWrapperClass">
    <apex:form >
        <apex:pageMessages></apex:pageMessages>
        <apex:pageBlock id="block">
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Get Records" action="{!processedRecords}" reRender="table1,table2"/>
                <apex:commandButton value="Send Email" action="{!sendEmail}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Detail Records">
                <apex:pageBlockTable value="{!wrapperTaskList}" var="wrap" id="table1">
                <apex:column >
                    <apex:inputCheckbox value="{!wrap.selected}"/>
                </apex:column>
                <apex:column value="{!wrap.chg.Name}" headerValue="Name"/>
                <apex:column value="{!wrap.chg.Phone__c}" headerValue="Phone"/>
                </apex:pageBlockTable>
                <apex:pageBlockTable value="{!existingRecords}" var="sel" id="table2">
                    <apex:column value="{!sel.Name}" headerValue="Name"/>
                    <apex:column value="{!sel.Phone__c}" headerValue="Phone"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>User-added image