• Soundar Raj Ponpandi
  • SMARTIE
  • 600 Points
  • Member since 2017
  • Senior Salesforce Developer
  • Smaartt

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 87
    Questions
  • 113
    Replies
Hi Gurus,

i am trying to attempt https://trailhead.salesforce.com/en/content/learn/superbadges/superbadge_apex and installed the managed package as suggested but when I got to setup>>object manager ,I am unable to edit the standard object 'Case' to 'Maintenance Request',how do I update the standard object

Regards,
Fiona
Hi,
Kindly anyone can help on below questions for PD:

Thanks in advance.


1. Create a visualforce page for opportunities that allows user to save or merge the current record. What approach -
A.  Custom Controller
B.  Custom Contoller extension
C.  Visualforce Java Script
D.  Standard Controller Methods.    

2. A developer must build an application that tracks which accounts have purchased specific pieces of equip Products. Each Account could purchase many pieces of equipment.

How should the developer track that an account has purchased a piece of equipment?
A.  Use the Asset object
B.  Use a custom object
C.  Use a Master-Detail on Product to Account
D.  Use a lookup on Account to Product    

 
  • July 05, 2020
  • Like
  • 0
Hello all,

We would like to change the subject ""First payment reminder" " as mentioned in below sample visulaforce code, based on the some condtions.
That means, If i send first reminder email then i am going to update the field "Total remider sent" value to 1,
Then later after checking other due dates conditions, ww would like to send another email but with different Subject i.e ". "Second payment reminder" and again update Total remider sent" value to 2.
can you please help how to handle such situation, This will help me to reuse same template for all the reminder;s, Invoice information will be picked up on run time, so no issues with that.


My Visualforce working code is - 

<messaging:emailTemplate subject="First payment reminder" recipientType="Contact" relatedToType="Account">

<!-- <messaging:plainTextEmailBody >
Congratulations!
This is your new Visualforce Email Template.
</messaging:plainTextEmailBody> -->

<messaging:htmlEmailBody >
    <STYLE type="text/css">
        TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center }
        TD  {font-size: 11px; font-face: verdana }
        TABLE {border: solid #CCCCCC; border-width: 1}
        TR {border: solid #CCCCCC; border-width: 1}
     </STYLE>
     <font face="arial" size="2">

<font size="2" face="Lucida Sans Unicode" > Dear  {!relatedTo.Name}, </font><br/>
<br/>

<font size="2" face="Lucida Sans Unicode" >Our financial records show that -- subscription for the total amount {!relatedTo.CurrencyIsoCode}&nbsp;{!relatedTo.Total_Outstanding_Amount__c} </font><br/>
<br/>


 
<br/>
        <table border="0" > 
            <tr>
                <th align="right"><font size="2" face="Lucida Sans Unicode" >Invoice Number   ;</font><br/></th>
                <th align="right"><font size="2" face="Lucida Sans Unicode" >Payment Due Date   ;</font><br/></th>
                <th align="right"><font size="2" face="Lucida Sans Unicode" >Amount Due   ;</font><br/></th>
                <th align="right"><font size="2" face="Lucida Sans Unicode" >Currency   ;</font><br/></th>
                
            </tr>
            
            <apex:repeat var="cx" value="{!relatedTo.Invoices__r}" >

               <tr>
                        <td align="right"><font size="2" face="Lucida Sans Unicode" >{!cx.Invoice_Number__c}&nbsp;</font></td>
                        
                        <td align="right"><font size="2" face="Lucida Sans Unicode" >
                            <apex:outputText value="{0,date,dd'/'MMM'/'yyyy}">
                                <apex:param value="{!cx.Transaction_Due_Date_del__c}" /> 
                            </apex:outputText>&nbsp;</font>
                        </td>


                        <td align="right"><font size="2" face="Lucida Sans Unicode">&nbsp;
                            <apex:outputText style="float:right" value="{0, number, ###,##0.00}">
                                <apex:param value="{!cx.Outstanding_Amount_FC__c}"/>
                            </apex:outputText>&nbsp;</font>
                        </td>
                        
                        <td align="right"><font size="2" face="Lucida Sans Unicode" >{!cx.Currency__c}&nbsp;</font></td>
                                                                        
               </tr>
                                   
            </apex:repeat>
        </table>  
     </font>
                    
<br/>

<font size="2" face="Lucida Sans Unicode" >Our bank details:</font><br/>
<font size="2" face="Lucida Sans Unicode" >Payment reference: {!relatedTo.Exact_Online_Account_ID__c} </font><br/>
<font size="2" face="Lucida Sans Unicode" >Please do not hesitate to contact us with questions. Thank you in advance for your cooperation. </font><br/>

<br/>
<br/>
<br/>  
                
<font size="2" face="Lucida Sans Unicode" >Best regards,</font><br/>
<font size="2" face="Lucida Sans Unicode" >Collection department</font><br/>
<font size="2" face="Lucida Sans Unicode" >BV Amsterdam, the Netherlands</font><br/>
                
</messaging:htmlEmailBody>
</messaging:emailTemplate>
HI,

I need a accurate article / solution on the following scenario.

1. Upload a file under the Opportunity record.
2. User's can able to view this file who all are added in the opportunity team.
3. My quetion is --> If User A upload a file in the same opportunity why User B is viewing the same file which is not uploaded by user B ?
4. In this scenario User A can delete but user B only can view the the file.

Can you send me the accurate article for this one.

Regards,
Soundar.
Hello,

I am facing following issue in Standrd List View.

1. Trying to search a record in asearch view.
2. But it's not working correctly.
3. I didn't get any result after searchig, But records are available in the list view.
4. 1000 Plus records are available in this list view.

Thanks In Advance.

Regards,
Soundar.
Hello,

How to bulk upload a images in rich text field.

I have one custom object called Object_A__c and i have created a new rich text field it's called Rich__c. I have 1000 images i want to upload those images ito salesforce  (Images should be map in a  Rich__c field )

I created a CSV file / Make 2 colums / 1 for Name another one for Image.


Regards,
Soundar.
Hello,

I have done with customised module for custom object. In a laptop and android phone scrollbar is working as expected.

But it's not working in "iPhone 6" can you please guide me in a way to find the solution for that.




User-added image


Thanks in advance.

Regards,
Soundar.
Hello,

I am facing following issue in test class, can you please check and let me know the accurate solution for that.


User-added image


Here i have attached a actual class and test class.

Test class
_________________
 
@isTest
public class GD_QuoteApprovalController_Test {
    
    public static testmethod void coverQuoteApprovalController(){
        User adminUser=[Select id from user where isActive=true and profile.name='System Administrator' limit 1];
        Id deptAccountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Department').getRecordTypeId();
            
        GD_Organization__c org =  GD_TestDataFactory.createOrganization('TestOrganization', '1234');
        insert org;
        
        Account acc = GD_TestDataFactory.createCustomer('Test Account', 'Customer');
        acc.GD_Organization__c = org.Id;
        acc.RecordtypeId=deptAccountRecordTypeId;
        insert acc;
        
        GD_Department__c dept = GD_TestDataFactory.createDepartment(org.Id, 'Medical Equipment');
        dept.GD_Department_Admin__c = userinfo.getUserId();
        insert dept;
        
         GD_Business_Unit__c businessUnit = GD_TestDataFactory.createBusinessUnit(dept.Id, 'GD_ME_SURGERY');
        insert businessUnit;
        system.debug('businessUnit'+businessUnit.Name);
        Opportunity opp = GD_TestDataFactory.createOpportunity('Test Opportunity', 'Project', 'Proposal', System.today().adddays(5), acc.Id);
        opp.GD_Expected_Revenue__c = 1000;
        insert opp;
        
        GD_Quote__c quotee = GD_TestDataFactory.createQuote(opp.Id,'Price List','Class A');
        quotee.GD_Business_Unit__c = businessUnit.Id;
        insert quotee; 
        quotee=[Select id,GD_Business_Unit__c,CreatedById,GD_Skip_Coorinator_approval__c,GD_Sales_Coordinator__c,GD_Sales_Rep__c,name from GD_Quote__c where id=:quotee.id];
        system.debug('businessUnitquotee. '+quotee.GD_Business_Unit__c);
        Test.startTest();
        GD_QuoteApprovalController.getQuoteDetails(quotee.Id);
        //string comment = 'Please Approve';
        GD_QuoteApprovalController.submitForApproval(quotee, 'Please Approve');
        Test.stopTest();
        
    }
}

Actual Class
_______________
public without sharing class  GD_QuoteApprovalController {
    
    @AuraEnabled
    public static GD_Quote__c getQuoteDetails(String quoteId){
        try{
            GD_Quote__c quote = new GD_Quote__c();
            quote = [SELECT Id,GD_Status__c,GD_Quote_Name__c,OwnerId,GD_Quote_Margin__c,GD_Warranty_Years__c,GD_Has_FOC__c,GD_Quote_Approval_Status__c,
                     GD_Business_Unit__c,GD_Business_Unit__r.Name,GD_Total_In_AED__c,GD_Sales_Rep__r.ManagerId,CreatedById
                     FROM GD_Quote__c WHERE Id=: quoteId ];
            
            User dvisionManager = [SELECT Id,Name,profile.name FROM User WHERE profile.name = 'GD ME Division Manager' LIMIT 1];
            User loggedInUser = [SELECT Id,Name,profile.name FROM User WHERE Id=:userInfo.getUserId()];
            User createdBy = [SELECT Id,Name,profile.name FROM User WHERE Id=: quote.CreatedById];
            string loggedIn = loggedInUser.profile.name;
            string createdByProfile = createdBy.profile.name;
            List<User> approvalUsers = new List<User>();
            
            quote.GD_Division_Manager__c = dvisionManager.Id;
            quote.GD_Sales_Manager__c = quote.GD_Sales_Rep__r.ManagerId;
            //Submitted By Sales Coordinator
            if(loggedIn.contains('Coordinator')){
                quote.GD_Sales_Coordinator__c = loggedInUser.Id;
            }else if(createdByProfile.contains('Coordinator')){
                quote.GD_Sales_Coordinator__c = quote.CreatedById;
            }else{
                quote.GD_Sales_Coordinator__c = loggedInUser.Id;
            }
            
            update quote;
            return quote;
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage());    
        }
    }
    
    @AuraEnabled
    public static InitData submitForApproval(GD_Quote__c quoteRecord,String approvalComments){
        
        boolean Process_success;
        InitData init = new InitData();
        try{
            
            User loggedInUser = [SELECT Id,Name,profile.name FROM User WHERE Id=:userInfo.getUserId()];
            string loggedIn = loggedInUser.profile.name;
            User createdBy = [SELECT Id,Name,profile.name FROM User WHERE Id=: quoteRecord.CreatedById];
            string createdByProfile = createdBy.profile.name;
            
            /* Created By SalesRep & Submitted By Sales Rep*/
            if(!loggedIn.contains('Coordinator') /*&& !createdByProfile.contains('Coordinator')*/){
                quoteRecord.GD_Skip_Coorinator_approval__c = True;
            }
            
            update quoteRecord;
            
            List<Approval.ProcessSubmitRequest> approvalRequestList = new List<Approval.ProcessSubmitRequest>();
            String approverId;
            
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments(approvalComments);
            req1.setObjectId(quoteRecord.Id); 
            req1.getSubmitterId(); 
            req1.getNextApproverIds();
            approvalRequestList.add(req1);
            system.debug('approvalRequestList.size() ****' + approvalRequestList.size());
            if(approvalRequestList.size() >0){
                 Savepoint sp = Database.setSavepoint();
                List<Approval.ProcessResult> resultList = Approval.process(approvalRequestList);   
                //Approval.process(approvalRequestList);
                
                for(Approval.ProcessResult results: resultList ){  
                    if(results.getInstanceStatus() != 'Rejected'){
                        system.debug('*** Success ***');
                        Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
                        Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                        
                        id submitterId;
                        for(ProcessInstanceWorkitem pItem : [Select p.Id,p.ActorId,p.ProcessInstance.SubmittedById from ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId =: quoteRecord.Id]){
                            submitterId=pItem.ProcessInstance.SubmittedById;
                            req.setWorkitemId(pItem.Id);
                        }
                        if(submitterId!=null){
                            list<User> userDetails =[SELECT Id, Name, Profile.Name, UserRole.Name FROM User where Id=:submitterId];
                            /*Created By && Submitted By same user (Sales Coordinator) */
                            if(createdByProfile == 'GD ME Sales Coordinator' && submitterId == quoteRecord.GD_Sales_Coordinator__c){
                                req.setComments('Approving request for ' + quoteRecord.Name);
                                req.setAction('Approve'); 
                                Approval.ProcessResult result = Approval.process(req);
                                
                                /*Created By && Submitted by same user (Sales Rep )*/
                            } else if(createdByProfile == 'GD ME Sales Rep' && submitterId == quoteRecord.GD_Sales_Rep__c){
                                system.debug('Entered *** Sales Rep');
                                req.setComments('Approving request for ' + quoteRecord.Name);
                                req.setAction('Approve'); 
                                Approval.ProcessResult result = Approval.process(req); 
                                
                                /*Created By Sales Coordinator && Submitted Sales Rep */   
                            }else if(createdByProfile == 'GD ME Sales Coordinator' && submitterId == quoteRecord.GD_Sales_Rep__c){
                                system.debug('Entered As expected ****');
                                List<Approval.ProcessWorkitemRequest> allReq = new List<Approval.ProcessWorkitemRequest>(); 
                                req.setComments('Approving request for ' + quoteRecord.Name);
                                req.setAction('Approve'); 
                                allReq.add(req);
                                Approval.ProcessResult result = Approval.process(req);
                                boolean coordApproved = true;
                                
                                /*Cannot approve two records at same time, So set a dummy boolean as coordApproved*/
                                if(coordApproved = true){
                                    for(ProcessInstanceWorkitem pItem1 : [Select p.Id,p.ActorId,p.ProcessInstance.SubmittedById from ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId =: quoteRecord.Id]){
                                        submitterId=pItem1.ProcessInstance.SubmittedById;
                                        req2.setWorkitemId(pItem1.Id);
                                    }
                                    req2.setComments('Approving request for ' + approvalComments);
                                    req2.setAction('Approve'); 
                                    allReq.add(req2);
                                    Approval.ProcessResult result1 = Approval.process(req2);
                                }
                                
                                /*Set<Id> qtIds = (new Map<Id, GD_Quote__c>([SELECT Id FROM GD_Quote__c where id =: quoteRecord.Id])).keySet();
Set<Id> pIds = (new Map<Id, ProcessInstance>([SELECT Id,Status,TargetObjectId FROM ProcessInstance where TargetObjectId in :qtIds])).keySet();
Set<Id> pInstanceWorkitems = (new Map<Id, ProcessInstanceWorkitem>([SELECT Id,ProcessInstanceId FROM ProcessInstanceWorkitem WHERE ProcessInstanceId in :pIds limit 2])).keySet();
system.debug('pInstanceWorkitems ****' + pInstanceWorkitems);
for (Id pInstanceWorkitemsId:pInstanceWorkitems){
system.debug(pInstanceWorkitemsId);
Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
req2.setComments('Approving request for ' + quoteRecord.Name);
req2.setAction('Approve'); //to approve use 'Approve'
//req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
// Use the ID from the newly created item to specify the item to be worked
req2.setWorkitemId(pInstanceWorkitemsId);
// Add the request for approval
allReq.add(req2);
}
Approval.ProcessResult[] result2 =  Approval.process(allReq);*/
                            }
                        }
                        system.debug('*** Process Pass ***');
                        init.Process_success = true;
                        //Process_success = true;
                    }else {
                       /*Got Auto Rejected - Here Empty the quote approval status and delete process instance*/
                        Database.rollback(sp);
                        
                        quoteRecord.GD_Quote_Approval_Status__c = '';
                        update quoteRecord;
                        init.Process_success = false;
                        
                        
                        
                        
                    }
                }
                
                
            }
            else{
                system.debug('**** Not Met ****');
            }
            
        }catch(Exception e){
            system.debug('EXCEPTION ******* '+e.getStackTraceString());
            throw new AuraHandledException(e.getMessage());    
        }
        system.debug('init ***' + init);
        return init;
    }
    
    
     Public class InitData{
        @Auraenabled public Boolean Process_success;
        public InitData(){
            Process_success = false;
        }
    }
    
    
}

Thannks in advance.

Regards,
Soundar.
 
Hi,

I am looking for a email validation in lightning component.

1. Is that possible by using in a component ? without using controller or helper ?

2. If No, Can you guide me to get a following email validation.

3.  It should end with ( .COM). Let's say for example it should the validation if it's  in following format " abc@d.o " .


Regards,
Soundar.
Hi,

1. I have configured a standrd approval process.
2. Triggered this approval process with customize button.
3. I am facing an issue with following scenario.

A. Created a record by using "User A".
B. Trying to submit this record by using "User B".
C. User B having an edit access for this record.
D. WHen i am submitting for an approval it's showing "In-sufficient Access " issue.
C. This issue is not replicated if i given a modify all access to "User B - Profile"


What is the actual issue on that ?

Note:
Role is aded in initial submitter.



Regards,
Soundar.
Hi,

I have created a standard approval process and apex class to trigger this approval process. Here i am facing one challanges, while submitting the approval process it should skip the step 1 (if submitter is sales rep). Please find the approver hierarchy below.

1. Sales Coordinator
2. Slaes Rep
3. Sales Manager
4. Division Manager

If sales rep is submit for an approval it should skip first step (Sales coordinator) approval. 

here i have written apex class, Please check and let me know where i did mistake.
public class GD_QuoteApprovalController {
    
    @AuraEnabled
    public static GD_Quote__c getQuoteDetails(String quoteId){
        try{
            GD_Quote__c quote = new GD_Quote__c();
            List<User> approvalUsers = new List<User>();
            quote = [SELECT Id,GD_Status__c,OwnerId,GD_Quote_Margin__c,GD_Warranty_Years__c,GD_Has_FOC__c,
                     GD_Business_Unit__c,GD_Business_Unit__r.Name,GD_Total_In_AED__c,GD_Sales_Rep__r.ManagerId,CreatedById
                     FROM GD_Quote__c WHERE Id=: quoteId ];
            approvalUsers = [SELECT Id,Name FROM User WHERE userRole.Name =: Label.GD_ME_Division_Manager_Role_Name];
            User loggedInUser = [SELECT Id,Name,profile.name FROM User WHERE Id=:userInfo.getUserId()];
            User createdBy = [SELECT Id,Name,profile.name FROM User WHERE Id=: quote.CreatedById];
            string coordinator = loggedInUser.profile.name;
            string createdByProfile = createdBy.profile.name;
            if(approvalUsers.isEmpty()){
                throw new AuraHandledException('No Division manager assigned.');    
            }
            quote.GD_Sales_Manager__c = quote.GD_Sales_Rep__r.ManagerId;
            quote.GD_Division_Manager__c = approvalUsers.get(0).Id;
            
            //Submitted By Sales Coordinator
            if(coordinator.contains('Coordinator')){
                quote.GD_Sales_Coordinator__c = loggedInUser.Id;
            }else if(createdByProfile.contains('Coordinator')){
                quote.GD_Sales_Coordinator__c = quote.CreatedById;
            }
            
            //Submitted By Sales Rep
            if(coordinator.contains('Sales Rep')){
                quote.GD_Sales_Coordinator__c = loggedInUser.Id;
                quote.GD_Submitted_By_Sales_Rep__c = true;
            }else if(createdByProfile.contains('Sales Rep')){
                quote.GD_Sales_Coordinator__c = quote.CreatedById;
                quote.GD_Submitted_By_Sales_Rep__c = true;
            }

            update quote;
            return quote;
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage());    
        }
    }
    
    @AuraEnabled
    public static void submitForApproval(GD_Quote__c quoteRecord,String approvalComments){
        
        STRING GD_ME_GI_ET = System.Label.ME_Business_Unit_GI_ET;
        STRING GD_ME_CRITICAL_CARE = System.Label.ME_Business_Unit_Critical_Care;
        STRING GD_ME_INFECTION_CONTROL = System.Label.ME_Business_Unit_Infection_Control;
        STRING GD_ME_CWS = System.Label.ME_Business_Unit_Clinical_Workplace_Solution;
        STRING GD_ME_SURGERY = System.Label.ME_Business_Unit_Surgery;
        STRING GD_ME_DIALYSIS = System.Label.ME_Business_Unit_Dialysis;
        STRING GD_ME_IMAGING_SYSTEM = System.Label.ME_Business_Unit_Imaging;
        STRING GD_ME_PHARMACY_AUTOMATION = System.Label.ME_Business_Unit_Pharmacy_Automation;
        system.debug('GD_ME_GI_ET ' + GD_ME_GI_ET);
        try{
            List<Approval.ProcessSubmitRequest> approvalRequestList = new List<Approval.ProcessSubmitRequest>();
            String approverId;
            boolean toUpdate = false;
            system.debug('Business Unit Name '+quoteRecord.GD_Business_Unit__r.Name);
            if(quoteRecord.GD_Business_Unit__r.Name == GD_ME_SURGERY || quoteRecord.GD_Business_Unit__r.Name == GD_ME_INFECTION_CONTROL || 
               quoteRecord.GD_Business_Unit__r.Name == GD_ME_CWS || quoteRecord.GD_Business_Unit__r.Name == GD_ME_GI_ET || 
               quoteRecord.GD_Business_Unit__r.Name == GD_ME_DIALYSIS || quoteRecord.GD_Business_Unit__r.Name == GD_ME_IMAGING_SYSTEM || 
               quoteRecord.GD_Business_Unit__r.Name == GD_ME_PHARMACY_AUTOMATION || quoteRecord.GD_Business_Unit__r.Name == GD_ME_CRITICAL_CARE){
                   toUpdate = true;
               }
            
            if(toUpdate){
                system.debug('*** Entered ***');
                Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
                req1.setComments(approvalComments);
                req1.setObjectId(quoteRecord.Id); 
                req1.getSubmitterId(); 
                req1.getNextApproverIds();
                approvalRequestList.add(req1);
                if(approvalRequestList.size() >0){
                    Approval.process(approvalRequestList);
                //} removed 

                Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
                id submitterId;
                for(ProcessInstanceWorkitem pItem : [Select p.Id,p.ActorId,p.ProcessInstance.SubmittedById from ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId =: quoteRecord.Id]){
                    system.debug('pItem *** ' + pItem);
                    submitterId=pItem.ProcessInstance.SubmittedById;
                    req.setWorkitemId(pItem.Id);
                }
                system.debug('submitterId *** ' + submitterId);
                if(submitterId!=null){
                    list<User> userDetails =[SELECT Id, Name, Profile.Name, UserRole.Name FROM User where Id=:submitterId];
                    system.debug('userDetails *** ' + userDetails);
                    if(userDetails!=null && userDetails.size()>0 && (userDetails[0].Profile.Name=='GD ME Sales Coordinator' || userDetails[0].Profile.Name=='GD ME Sales Rep' || userDetails[0].Profile.Name=='GD ME Sales Manager')){
                        req.setComments('Approving request for' + quoteRecord.Name);
                        req.setAction('Approve'); //Approve Record 
                        system.debug('req *** ' + req);
                        Approval.ProcessResult result = Approval.process(req);
                        system.debug('result *** ' + result);
                    }
                }
            }//Added 
                else{
                    system.debug('**** Not Matched with Critiria ****');
                }
            }
            
        }catch(Exception e){
            system.debug('EXCEPTION ******* '+e.getStackTraceString());
            throw new AuraHandledException(e.getMessage());    
        }
    }
    
}

Thanks in advance.

Regards,
Soundar.
HI, 

I have created one batch class, This is sending a no activity reminder to record owner CC with manager.

Right now i am getting a manager email by additional field, GD_Sales_Manager__c

But i want to take this manager email via Query only. But it should not inside of the for loop.

Can you please guide me in a proper way, Please review the below code.
global class GD_NoActivityReminder implements Database.Batchable<sObject>, Database.Stateful{
    
    list<GD_Lead__c> leadListToUpdate_Task = new list<GD_Lead__c>();
    list<GD_Lead__c> leadListToUpdate_Event = new list<GD_Lead__c>();
    list<GD_Lead__c> leadListToUpdate_ET = new list<GD_Lead__c>();
    GD_No_Activity_Reminder__mdt reminderDays = [select id,GD_Days__c from GD_No_Activity_Reminder__mdt Limit 1];     
    Integer days =integer.valueOf(reminderDays.GD_Days__c);
    global final String leadQuery ='Select Id,OwnerId,Name,GD_Lead_Status__c,Owner.Email,GD_Sales_Manager_Email__c  from GD_Lead__c where GD_Lead_Status__c != \'Converted\' and GD_Lead_Status__c != \'Unqualified\' and GD_Lead_Status__c != \'Retired\' LIMIT 2';
    set<id> leadId = new set<id>();
    List<GD_Lead__c> noDupes;
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(leadQuery); 
    }
    
    global void execute(Database.BatchableContext BC,List<GD_Lead__c> scope){
        Map<Id,GD_Lead__c> originalLeadMap = new Map<Id,GD_Lead__c>(scope);
        Map<Id,List<Task>> taskByLead = new Map<Id,List<Task>>();
        Map<Id,List<Event>> eventByLead = new Map<Id,List<Event>>();
        Date d = System.today() - days;
        
        //Task
        for(Task t : [select id,status,lastModifiedDate, WhatId from Task where WhatId =:originalLeadMap.keySet() and status != 'Completed' and LastModifiedDate <:d]){
            if(taskByLead.containsKey(t.WhatId)){
                taskByLead.get(t.WhatId).add(t);
            }else{
                taskByLead.put(t.WhatId,new List<Task>{t});
            }
        }        
        
        for(Id leadId : originalLeadMap.keySet()){
            if(/*!*/taskByLead.containsKey(leadId)){
                leadListToUpdate_Task.add(originalLeadMap.get(leadId));
            }
        }
        
        //Event
        for(Event e : [select id,WhatId,endDate from Event where WhatId =:originalLeadMap.keySet()  and EndDate <:d /*days*/]){
            system.debug('Entered ***'  );
            if(eventByLead.containsKey(e.WhatId)){
                eventByLead.get(e.WhatId).add(e);
            }else{
                eventByLead.put(e.WhatId,new List<Event>{e});
            }
        }
        
        for(Id leadId : originalLeadMap.keySet()){
            if(/*!*/eventByLead.containsKey(leadId)){
                leadListToUpdate_Event.add(originalLeadMap.get(leadId));
            }
        }
        
        leadListToUpdate_ET.addAll(leadListToUpdate_Task);
        leadListToUpdate_ET.addAll(leadListToUpdate_Event);
        //Remove The Duplicate Records
        noDupes = new List<GD_Lead__c>(new Set<GD_Lead__c>(leadListToUpdate_ET));
        
        map<id, user> ownerId = new map<id, user>([select id,name from user]);
        
    }
    
    global void finish(Database.BatchableContext BC){  
        EmailTemplate template = [select id,body from EmailTemplate where DeveloperName='GD_Lead_No_Activity_Email_Notification_Template' limit 1];
        contact con = [select id, Email from contact where email <> null limit 1];
        List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
        for(GD_Lead__c leadRecord : noDupes){
            list<string> ownerEmail = new list<string>();
            list<string> cCEmails = new list<string>();
            ownerEmail.add(leadRecord.owner.email);
            cCEmails.add(leadRecord.GD_Sales_Manager_Email__c);
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.setTreatTargetObjectAsRecipient(false);
            message.setSaveAsActivity(false); 
            message.setTemplateId(template.id);
            message.setWhatId(leadRecord.id);
            message.setTargetObjectId(con.id); 
            message.setToAddresses(ownerEmail);
            message.setCcAddresses(cCEmails);
            lstMsgs.add(message);
        }
        
        Savepoint sp = Database.setSavepoint();
        Messaging.sendEmail(lstMsgs);
        Database.rollback(sp);
        
        List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
        for (Messaging.SingleEmailMessage email : lstMsgs) {
            Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
            emailToSend.setToAddresses(email.getToAddresses());
            emailToSend.setCcAddresses(email.getccAddresses());
            emailToSend.setPlainTextBody(email.getPlainTextBody());
            emailToSend.setHTMLBody(email.getHTMLBody());
            emailToSend.setSubject(email.getSubject());
            lstMsgsToSend.add(emailToSend);
        }
        Messaging.sendEmail(lstMsgsToSend);   
    }
}

Thanks,
Soundar.
Hi,

1. I created one approval process with three level of approvers.

2. Approver 1, Approver 2 and Approver 3.

3. If approver 1 submitted for approval, It should get auto approval and assign to approver 2.

4. If approver 2 submitted it should skip approver 1 and auto approved in approver 2 level,Then assign to approver 3 for approval.

Is that possible by configuration ? else can you please share sample customizaton code.

Regards,
Soundar.
Hi,

I have enabled multi currecny in my organisation.

1. I like to map "CurrencyIsoCode" in apex class. But it's not mapping, let's say for example i am selected a value from currency dropdown as USD in a lead object (Custom Object).

2. While convert to opportunity lead currecncy should map with opportunity currecncy. but always it's taking a corperate currecny.

3. Can you please give me a valid suggestion why this multi currecny is not mapping in apex code.
 
public static Id convertToOpportunity(GD_Lead__c leadRecord) {
        Opportunity opp = new Opportunity();
			opp.GD_Lead__c = leadRecord.Id;
			opp.Name= leadRecord.name;
			opp.stageName = 'Qualification';
			Opp.CloseDate = Date.Today().addDays(30);
			opp.CurrencyIsoCode = leadRecord.CurrencyIsoCode;
			system.debug('Opp ' + opp.CurrencyISOCode + ' Lead ' + leadRecord.CurrencyISOCode);
			insert opp;
			return opp.id;
	}

Thanks in advance,
Soundar.
Hi,

I am writting a approval process, i would like to assign a approver from a sales Rep (User Lookup) of currecnt record.

In a standard process, it's a way to choose while create a approval process. But in my scenario i want to assign to record's sales Rep (User). 

Do i need to create any apex class ? Else can i achieve it from a standard way.

Regards,
Soundar.
HI,

I am facing Too manu email Invocations in batch calss. Can you please guide me where i did a mistake.
 
global class GD_LeadEscalation implements Database.Batchable<sObject>,Database.Stateful {
    
    global final String escalationQuery = 'Select Id,ownerId,Name,GD_Assigned_To_Email__c,GD_Lead_Status__c,GD_Escalated__c,GD_Stop_Escalation__c'
        + ' from GD_Lead__c where GD_Stop_Escalation__c = false and (GD_Lead_Status__c != \'Converted\' OR GD_Lead_Status__c != \'Unqualified\')';
   
    contact con = [select id, Email from contact where email <> null limit 1];
    EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];
    boolean lev1 = false;boolean lev2 = false;boolean lev3 = false;
    list<GD_Lead__c> LeadEscList = new List<GD_Lead__c>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(escalationQuery); 
    }
    
    global void execute(Database.BatchableContext BC,List<GD_Lead__c> scope){
        for(GD_Lead_Escalation_Setup__mdt monitor : [select id,GD_Escalation_Emails__c,GD_Escalation_Days__c,GD_Escalation_Days1__c,GD_Level_Of_Escalation__c from GD_Lead_Escalation_Setup__mdt]){
            if(monitor.GD_Level_Of_Escalation__c == 'Level 1'){
                for(GD_Lead__c leadRecord : scope){
                    if(leadRecord.GD_Escalated__c == Decimal.valueOf(monitor.GD_Escalation_Days__c)){
                        leadRecord.GD_Escalation_Level__c = 'Level 1';
                        leadRecord.GD_EscalatedFlag__c = true;
                        lev1 = true;
                        LeadEscList.add(leadRecord);
                    }
                }
            }
            
            if(monitor.GD_Level_Of_Escalation__c == 'Level 2'){
                for(GD_Lead__c leadRecord : scope){
                    if(leadRecord.GD_Escalated__c == Decimal.valueOf(monitor.GD_Escalation_Days__c)){
                        leadRecord.GD_Escalation_Level__c = 'Level 2';
                        lev2 = true;
                        LeadEscList.add(leadRecord);
                    }
                }
            }
            
            if(monitor.GD_Level_Of_Escalation__c == 'Level 3'){
                for(GD_Lead__c leadRecord : scope){
                    if(leadRecord.GD_Escalated__c == Decimal.valueOf(monitor.GD_Escalation_Days__c)){
                        leadRecord.GD_Escalation_Level__c = 'Level 3';
                        lev3 = true;
                        LeadEscList.add(leadRecord);
                    }
                }
            }
        }
        system.debug('LeadEscList ' + LeadEscList.size());
        if(LeadEscList.size() > 0 ){update LeadEscList;}
    } 
    
    global void finish(Database.BatchableContext BC){   
        
        list<string> cCEmails_lev1 = new list<string>();
        list<string> cCEmails_lev2 = new list<string>();
        list<string> cCEmails_lev3 = new list<string>();
        
        EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];       
        for(GD_Lead__c leadRecord : LeadEscList){
            List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
           
            for(user u: [select id,name, manager.email, manager.GD_No_Escalation__c, manager.manager.email, manager.manager.GD_No_Escalation__c, manager.manager.manager.email, manager.manager.manager.GD_No_Escalation__c from user where id=: leadRecord.OwnerId]){
                if(lev1 = true){
                    if(u.manager.email != null && u.manager.email != '' && u.manager.GD_No_Escalation__c == false /*&& u!=null && !u.isEmpty()*/){
                        string mngrEmail_1 = u.manager.email;
                        cCEmails_lev1.add(mngrEmail_1);
                    }
                }
                if(lev2 = true){
                    if(u.manager.manager.email != null && u.manager.manager.email != '' && u.manager.manager.GD_No_Escalation__c == false ){
                        string mngrEmail_1 = u.manager.email;
                        string mngrEmail_2 = u.manager.manager.email;
                        cCEmails_lev2.add(mngrEmail_1);
                        cCEmails_lev2.add(mngrEmail_2);
                        
                    }
                }
                
                if(lev3 = true){
                    if(u.manager.manager.manager.email != null && u.manager.manager.manager.email != '' && u.manager.manager.manager.GD_No_Escalation__c == false ){
                        string mngrEmail_1 = u.manager.email;
                        string mngrEmail_2 = u.manager.manager.email;
                        string mngrEmail_3 = u.manager.manager.manager.email;
                        cCEmails_lev3.add(mngrEmail_1);
                        cCEmails_lev3.add(mngrEmail_2);
                        cCEmails_lev3.add(mngrEmail_3);
                        
                    }
                }
                
            }
            msg.setTemplateId(template.id);
            msg.setWhatId(leadRecord.id);
            msg.setTargetObjectId(con.id); 
            msg.setSaveAsActivity(false);
            String[] repEamail = new String[] {leadRecord.GD_Assigned_To_Email__c};
            msg.setToAddresses(repEamail);
            if(lev1 = true){msg.setCcAddresses(cCEmails_lev1);}
            if(lev2 = true){msg.setCcAddresses(cCEmails_lev2);}
            if(lev3 = true){msg.setCcAddresses(cCEmails_lev3);}
            lstMsgs.add(msg);
            Savepoint sp = Database.setSavepoint();
            Messaging.sendEmail(lstMsgs);
            Database.rollback(sp);
            List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
            for (Messaging.SingleEmailMessage email : lstMsgs) {
                Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
                emailToSend.setToAddresses(email.getToAddresses());
                emailToSend.setCcAddresses(email.getccAddresses());
                emailToSend.setPlainTextBody(email.getPlainTextBody());
                emailToSend.setHTMLBody(email.getHTMLBody());
                emailToSend.setSubject(email.getSubject());
                lstMsgsToSend.add(emailToSend);
            }
            Messaging.sendEmail(lstMsgsToSend);
        }
    }
}

Thanks & Regards,
Soundar.
HI,

I am sending a escalation email based on Level and few conditions. Same logics are repeated with few changes.

1. For level 1 - sending to two persons 

2. For Level 2 - sending to three persons.

3. For Level 3 - Sending to four persons.

Can you please check my code and reduce the code by using Map.
 
global class GD_LeadEscalation implements Database.Batchable<sObject>,Database.Stateful {
    
    //Level 1
    GD_Lead_Escalation_Setup__mdt escMonitor1 = [select id,GD_Escalation_Emails__c,GD_Escalation_Days__c,GD_Level_Of_Escalation__c from GD_Lead_Escalation_Setup__mdt where GD_Level_Of_Escalation__c = 'Level 1'];
    string level1Days = escMonitor1.GD_Escalation_Days__c;
    List<GD_Lead__c> firstLevelEscalation = [Select Id,Name,GD_Assigned_To_Email__c,GD_Level_3_Manager__c,GD_Level_2_Manager__c,GD_Level_1_Manager__c,GD_Sales_Rep_Name__c,Lead_Unique_Number__c,GD_Lead_Priority__c,GD_Lead_Status__c,GD_Revenue__c,GD_Expected_Opportunity_Date__c,GD_First_Expected_Opportunity_Date__c,GD_Organisation__c,GD_Territory__c,GD_Department__c,GD_Business_Unit__r.name,GD_Account__r.Name,GD_Parent_Account__c,GD_Contact__r.name,GD_Escalated__c 
                                             from GD_Lead__c where GD_Escalated__c =: Decimal.valueOf(level1Days) and GD_Stop_Escalation__c = false and (GD_Lead_Status__c != 'Converted' OR GD_Lead_Status__c != 'Unqualified')];
    
    //Level 2
    GD_Lead_Escalation_Setup__mdt escMonitor2 = [select id,GD_Escalation_Emails__c,GD_Escalation_Days__c,GD_Level_Of_Escalation__c from GD_Lead_Escalation_Setup__mdt where GD_Level_Of_Escalation__c = 'Level 2'];
    string level2Days = escMonitor2.GD_Escalation_Days__c;
    List<GD_Lead__c> secondLevelEscalation = [Select Id,Name,GD_Assigned_To_Email__c,GD_Level_3_Manager__c,GD_Level_2_Manager__c,GD_Level_1_Manager__c,GD_Sales_Rep_Name__c,Lead_Unique_Number__c,GD_Lead_Priority__c,GD_Lead_Status__c,GD_Revenue__c,GD_Expected_Opportunity_Date__c,GD_First_Expected_Opportunity_Date__c,GD_Organisation__c,GD_Territory__c,GD_Department__c,GD_Business_Unit__r.name,GD_Account__r.Name,GD_Parent_Account__c,GD_Contact__r.name,GD_Escalated__c 
                                              from GD_Lead__c where GD_Escalated__c =: Decimal.valueOf(level2Days) and GD_Stop_Escalation__c = false and (GD_Lead_Status__c != 'Converted' OR GD_Lead_Status__c != 'Unqualified')];
    
    //Level 3
    GD_Lead_Escalation_Setup__mdt escMonitor3 = [select id,GD_Escalation_Emails__c,GD_Escalation_Days__c,GD_Level_Of_Escalation__c from GD_Lead_Escalation_Setup__mdt where GD_Level_Of_Escalation__c = 'Level 3'];
    string level3Days = escMonitor3.GD_Escalation_Days__c;
    List<GD_Lead__c> thirdLevelEscalation = [Select Id,Name,GD_Assigned_To_Email__c,GD_Level_3_Manager__c,GD_Level_2_Manager__c,GD_Level_1_Manager__c,GD_Sales_Rep_Name__c,Lead_Unique_Number__c,GD_Lead_Priority__c,GD_Lead_Status__c,GD_Revenue__c,GD_Expected_Opportunity_Date__c,GD_First_Expected_Opportunity_Date__c,GD_Organisation__c,GD_Territory__c,GD_Department__c,GD_Business_Unit__r.name,GD_Account__r.Name,GD_Parent_Account__c,GD_Contact__r.name,GD_Escalated__c 
                                             from GD_Lead__c where GD_Escalated__c =: Decimal.valueOf(level3Days) and GD_Stop_Escalation__c = false and (GD_Lead_Status__c != 'Converted' OR GD_Lead_Status__c != 'Unqualified')];
    
    //Dummy Query for start locator
    global final String query_leadEsc1 ='Select id from GD_Lead__c where GD_Lead_Status__c != \'Converted\'';
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query_leadEsc1); 
    }
    
    /* Execute Method */
    global void execute(Database.BatchableContext BC,List<GD_Lead__c> scope){
        //for(GD_Lead__c lead : scope){}
    }
    
    /* Finish Method */
    global void finish(Database.BatchableContext BC){   
        //Level 1 Escalation
        system.debug('firstLevelEscalation.size() ***'  + firstLevelEscalation.size());
        if(firstLevelEscalation.size() > 0 && firstLevelEscalation.size() != null){ // Check Empty
            EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];
            for(GD_Lead__c lead : firstLevelEscalation){
                //Dummy Contact for Email Template
                //Contact con = [select id, Email from Contact where email <> null limit 1];
                List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId(template.id);
                msg.setWhatId(lead.id);  /// Check without whatId
                //msg.setTargetObjectId(con.id); 
                String[] repEamail = new String[] {lead.GD_Assigned_To_Email__c};
                    String[] ccAddresses = new String[] {lead.GD_Level_1_Manager__c};
                        system.debug('ccAddresses' + ccAddresses);
                //msg.setToAddresses(new List<String>{repEamail});
                msg.setToAddresses(repEamail); 
                msg.setCcAddresses(ccAddresses);
                lstMsgs.add(msg);
                system.debug('lstMsgs' + lstMsgs);
                Savepoint sp = Database.setSavepoint();
                Messaging.sendEmail(lstMsgs);
                Database.rollback(sp);
                List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
                for (Messaging.SingleEmailMessage email : lstMsgs) {
                    Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
                    emailToSend.setToAddresses(email.getToAddresses());
                    emailToSend.setCcAddresses(email.getccAddresses());
                    emailToSend.setPlainTextBody(email.getPlainTextBody());
                    emailToSend.setHTMLBody(email.getHTMLBody());
                    emailToSend.setSubject(email.getSubject());
                    lstMsgsToSend.add(emailToSend);
                }
                Messaging.sendEmail(lstMsgsToSend);
                
            }
        }
        
        //Level 2 Escalation
        system.debug('secondLevelEscalation.size() ***'  + secondLevelEscalation.size());
        if(secondLevelEscalation.size() > 0 && secondLevelEscalation.size() != null){
            for(GD_Lead__c lead : secondLevelEscalation){
                //Dummy Contact for Email Template
                Contact con = [select id, Email from Contact where email <> null limit 1];
                List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];
                msg.setTemplateId(template.id);
                msg.setWhatId(lead.id);
                msg.setTargetObjectId(con.id); 
                String[] repEamail = new String[] {lead.GD_Assigned_To_Email__c};
                    String[] ccAddresses = new String[] {lead.GD_Level_1_Manager__c, lead.GD_Level_2_Manager__c};
                        msg.setToAddresses(repEamail); 
                msg.setCcAddresses(ccAddresses);
                lstMsgs.add(msg);
                Savepoint sp = Database.setSavepoint();
                Messaging.sendEmail(lstMsgs);
                Database.rollback(sp);
                List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
                for (Messaging.SingleEmailMessage email : lstMsgs) {
                    Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
                    emailToSend.setToAddresses(email.getToAddresses());
                    emailToSend.setCcAddresses(email.getccAddresses());
                    emailToSend.setPlainTextBody(email.getPlainTextBody());
                    emailToSend.setHTMLBody(email.getHTMLBody());
                    emailToSend.setSubject(email.getSubject());
                    lstMsgsToSend.add(emailToSend);
                }
                Messaging.sendEmail(lstMsgsToSend);
                
            }
        }
        
        //Level 3 Escalation
        system.debug('thirdLevelEscalation.size() ***'  + thirdLevelEscalation.size());
        if(thirdLevelEscalation.size() > 0 && thirdLevelEscalation.size() != null){
            for(GD_Lead__c lead : thirdLevelEscalation){
                //Dummy Contact for Email Template
                Contact con = [select id, Email from Contact where email <> null limit 1];
                List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];
                msg.setTemplateId(template.id);
                msg.setWhatId(lead.id);
                msg.setTargetObjectId(con.id); 
                String[] repEamail = new String[] {lead.GD_Assigned_To_Email__c};
                    String[] ccAddresses = new String[] {lead.GD_Level_1_Manager__c,lead.GD_Level_2_Manager__c,lead.GD_Level_3_Manager__c};
                        msg.setToAddresses(repEamail); 
                msg.setCcAddresses(ccAddresses);
                lstMsgs.add(msg);
                Savepoint sp = Database.setSavepoint();
                Messaging.sendEmail(lstMsgs);
                Database.rollback(sp);
                List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
                for (Messaging.SingleEmailMessage email : lstMsgs) {
                    Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
                    emailToSend.setToAddresses(email.getToAddresses());
                    emailToSend.setCcAddresses(email.getccAddresses());
                    emailToSend.setPlainTextBody(email.getPlainTextBody());
                    emailToSend.setHTMLBody(email.getHTMLBody());
                    emailToSend.setSubject(email.getSubject());
                    lstMsgsToSend.add(emailToSend);
                }
                Messaging.sendEmail(lstMsgsToSend);
                
            }
        }
    }
    }

Regards,
Soundar Rajan.​​​​​​​
Hi,

I have enabled multi currecny in my organisation.

1. I like to map "CurrencyIsoCode" in apex class. But it's not mapping, let's say for example i am selected a value from currency dropdown as USD in a lead object (Custom Object).

2. While convert to opportunity lead currecncy should map with opportunity currecncy. but always it's taking a corperate currecny.

3. Can you please give me a valid suggestion why this multi currecny is not mapping in apex code.
 
opportunity.CurrencyIsoCode = leadRecord.CurrencyIsoCode;
insert opportunity;

Thanks and Regards,
Soundar Rajan P.
Hi,

I am sending a Eamil notification with classic template. Here i am mapping To address and CC address as well. But mail is not sending to CC Address, It's only sending to To address. 

Can you pelase check my code and guide me where i need to change a code.
 
if(firstLevelEscalation.size() > 0 && firstLevelEscalation.size() != null){
            for(GD_Lead__c lead : firstLevelEscalation){
            //Dummy Contact for Email Template
            Contact con = [select id, Email from Contact where email <> null limit 1];
            List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
            EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];
            msg.setTemplateId(template.id);
            msg.setWhatId(lead.id);
            msg.setTargetObjectId(con.id); 
            String[] repEamail = new String[] {lead.GD_Assigned_To_Email__c};
            String[] ccAddresses = new String[] {lead.GD_Level_1_Manager__c};
            system.debug('ccAddresses' + ccAddresses);
            msg.setToAddresses(repEamail); 
            msg.setCcAddresses(ccAddresses);
            lstMsgs.add(msg);
            system.debug('lstMsgs' + lstMsgs);
            Savepoint sp = Database.setSavepoint();
            Messaging.sendEmail(lstMsgs);
            Database.rollback(sp);
            List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
            for (Messaging.SingleEmailMessage email : lstMsgs) {
                Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
                emailToSend.setToAddresses(email.getToAddresses());
                emailToSend.setPlainTextBody(email.getPlainTextBody());
                emailToSend.setHTMLBody(email.getHTMLBody());
                emailToSend.setSubject(email.getSubject());
                lstMsgsToSend.add(emailToSend);
                }
            Messaging.sendEmail(lstMsgsToSend);
        
        }
        }

Thanks & Regards,
Soundar. 
Hi,

Can you please help me to update with bulkify of this coding.
 
ContentDocumentLink exFile=[SELECT Id, LinkedEntityId, ContentDocumentId, Visibility, IsDeleted, ShareType FROM ContentDocumentLink WHERE LinkedEntityId =: request.get(0).id];
                ContentDocumentLink newFile= exFile.clone();
                newFile.LinkedEntityId = con.id;
                
                insert newFile;
                delete exFile;

Thanks in Advance ,
Soundar.
Hi,

I created one batch class, which is sending a notofication based on few conditions.

As of now i am sending a static message body as mentioned in the given code.

I would like to call email template instead of this static message body.

Can you please check my code and let me know where i should change my code.
 
global void finish(Database.BatchableContext BC){     
EmailTemplate emailTemplate = [Select id,name from EmailTemplate where name = 'GD Lead No Activity Email Notification Template' limit 1];
        for(GD_Lead__c lead : leadList){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] repEamail = new String[] {lead.GD_Assigned_To_Email__c};
            mail.setSaveAsActivity(false);
            mail.setTemplateID(emailTemplate.Id); 
            //mail.setTargetObjectId(lead.Id);
            mail.setWhatId(lead.Id);
            mail.setToAddresses(repEamail); 
            //mail.setccAddresses(managerEmail);
            mail.setSubject('No Activity Reminder');
            mail.setPlainTextBody('Hi  '+ lead.GD_Sales_Rep_Name__c+', \n \nPlease be informed, we have not found any activities on this Lead since last '+ days + ' days.\n \nKindly take an immediate action before escalate.  \n \n Lead Name : '+lead.Name +' \n \n Lead Number : '+ lead.Lead_Unique_Number__c +'\n \nRegards, \nGulf Drug Group.');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }

Thanks in advance,
Soundar.
Hi,

I written one validation, That validation is not allowed a  user to edit the record once converted. It's working fine in a desktop mode. But it's allowed to edit a record in mobile view. Validation is appearing after record save (In Mobile View).

Please check my validation code and advise me what was the misatke on that AND is that any possible ways to reduce the validation rule.
 
AND(
OR(
ISPICKVAL(GD_Lead_Status__c, 'Working'),
ISPICKVAL(GD_Lead_Status__c, 'Nurturing'),
ISPICKVAL(GD_Lead_Status__c, 'Retired'),
ISPICKVAL(GD_Lead_Status__c, 'Unqualified'),
ISCHANGED( GD_Bid_Bond__c ) ,
ISCHANGED( GD_Lead_Priority__c ) ,
ISCHANGED( GD_Lead_Status__c ) ,
ISCHANGED( GD_Lead_Source__c ) ,
ISCHANGED( GD_Expected_Opportunity_Date__c ) ,
ISCHANGED( GD_Revenue__c) ,
ISCHANGED( GD_Lead_Description__c ) ,
ISCHANGED( GD_Source_Description__c ) ,
ISCHANGED( GD_Account__c ) ,
ISCHANGED( GD_Contact__c ) ,
ISCHANGED( GD_Retired_Reason__c ) ,
ISCHANGED( GD_Retired_Upto__c ) ,
ISCHANGED( GD_Competitor_Information__c ) ,
ISCHANGED( GD_Rejected_Reason__c ),
ISCHANGED( GD_Lead_Type__c ),
ISCHANGED( OwnerId )
),
ISPICKVAL(PRIORVALUE(GD_Lead_Status__c), 'Converted'),
Not($Profile.Name = "System Administrator"),
If(GD_Converted__c = True, true, false)
)

 Regards,
Soundar.
HI,

I have following  scenarios,

1. I am enabling multi currency in my organisation.

2. So i can't create a roll-up summary fields in account object (to calculate total revenue from opportunity).

3. Is there only one way to create a roll-up summary field by flow builder (Without Apex).

4. So i decided to update a roll-up summary by using flow builder.

5. I am new to flow, can you please tell me step by step to achieve this process.

Regards,
Soundar.
Hi,

I am looking for a email validation in lightning component.

1. Is that possible by using in a component ? without using controller or helper ?

2. If No, Can you guide me to get a following email validation.

3.  It should end with ( .COM). Let's say for example it should the validation if it's  in following format " abc@d.o " .


Regards,
Soundar.
Hi,

1. I have configured a standrd approval process.
2. Triggered this approval process with customize button.
3. I am facing an issue with following scenario.

A. Created a record by using "User A".
B. Trying to submit this record by using "User B".
C. User B having an edit access for this record.
D. WHen i am submitting for an approval it's showing "In-sufficient Access " issue.
C. This issue is not replicated if i given a modify all access to "User B - Profile"


What is the actual issue on that ?

Note:
Role is aded in initial submitter.



Regards,
Soundar.
Hi,

1. I created one approval process with three level of approvers.

2. Approver 1, Approver 2 and Approver 3.

3. If approver 1 submitted for approval, It should get auto approval and assign to approver 2.

4. If approver 2 submitted it should skip approver 1 and auto approved in approver 2 level,Then assign to approver 3 for approval.

Is that possible by configuration ? else can you please share sample customizaton code.

Regards,
Soundar.
" create SOQL query in apex classes"
here  challange is create class AccountUtility
My code is :
public class AccountUtility { 
public static void viewAnnualRevenue () {
List<Account> accountsList = [SELECT Name, AnnualRevenue FROM Account]; 
String acctRev;
for(Account a : accountsList) { acctRev = a.Name + ': ' + a.AnnualRevenue;
system.debug(acctRev);
 } } }
I received an error plz help here to clear any one ,
Thank you.
HI,

I am facing Too manu email Invocations in batch calss. Can you please guide me where i did a mistake.
 
global class GD_LeadEscalation implements Database.Batchable<sObject>,Database.Stateful {
    
    global final String escalationQuery = 'Select Id,ownerId,Name,GD_Assigned_To_Email__c,GD_Lead_Status__c,GD_Escalated__c,GD_Stop_Escalation__c'
        + ' from GD_Lead__c where GD_Stop_Escalation__c = false and (GD_Lead_Status__c != \'Converted\' OR GD_Lead_Status__c != \'Unqualified\')';
   
    contact con = [select id, Email from contact where email <> null limit 1];
    EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];
    boolean lev1 = false;boolean lev2 = false;boolean lev3 = false;
    list<GD_Lead__c> LeadEscList = new List<GD_Lead__c>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(escalationQuery); 
    }
    
    global void execute(Database.BatchableContext BC,List<GD_Lead__c> scope){
        for(GD_Lead_Escalation_Setup__mdt monitor : [select id,GD_Escalation_Emails__c,GD_Escalation_Days__c,GD_Escalation_Days1__c,GD_Level_Of_Escalation__c from GD_Lead_Escalation_Setup__mdt]){
            if(monitor.GD_Level_Of_Escalation__c == 'Level 1'){
                for(GD_Lead__c leadRecord : scope){
                    if(leadRecord.GD_Escalated__c == Decimal.valueOf(monitor.GD_Escalation_Days__c)){
                        leadRecord.GD_Escalation_Level__c = 'Level 1';
                        leadRecord.GD_EscalatedFlag__c = true;
                        lev1 = true;
                        LeadEscList.add(leadRecord);
                    }
                }
            }
            
            if(monitor.GD_Level_Of_Escalation__c == 'Level 2'){
                for(GD_Lead__c leadRecord : scope){
                    if(leadRecord.GD_Escalated__c == Decimal.valueOf(monitor.GD_Escalation_Days__c)){
                        leadRecord.GD_Escalation_Level__c = 'Level 2';
                        lev2 = true;
                        LeadEscList.add(leadRecord);
                    }
                }
            }
            
            if(monitor.GD_Level_Of_Escalation__c == 'Level 3'){
                for(GD_Lead__c leadRecord : scope){
                    if(leadRecord.GD_Escalated__c == Decimal.valueOf(monitor.GD_Escalation_Days__c)){
                        leadRecord.GD_Escalation_Level__c = 'Level 3';
                        lev3 = true;
                        LeadEscList.add(leadRecord);
                    }
                }
            }
        }
        system.debug('LeadEscList ' + LeadEscList.size());
        if(LeadEscList.size() > 0 ){update LeadEscList;}
    } 
    
    global void finish(Database.BatchableContext BC){   
        
        list<string> cCEmails_lev1 = new list<string>();
        list<string> cCEmails_lev2 = new list<string>();
        list<string> cCEmails_lev3 = new list<string>();
        
        EmailTemplate template = [select id from EmailTemplate where DeveloperName='GD_Lead_Escalation_Template' limit 1];       
        for(GD_Lead__c leadRecord : LeadEscList){
            List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
           
            for(user u: [select id,name, manager.email, manager.GD_No_Escalation__c, manager.manager.email, manager.manager.GD_No_Escalation__c, manager.manager.manager.email, manager.manager.manager.GD_No_Escalation__c from user where id=: leadRecord.OwnerId]){
                if(lev1 = true){
                    if(u.manager.email != null && u.manager.email != '' && u.manager.GD_No_Escalation__c == false /*&& u!=null && !u.isEmpty()*/){
                        string mngrEmail_1 = u.manager.email;
                        cCEmails_lev1.add(mngrEmail_1);
                    }
                }
                if(lev2 = true){
                    if(u.manager.manager.email != null && u.manager.manager.email != '' && u.manager.manager.GD_No_Escalation__c == false ){
                        string mngrEmail_1 = u.manager.email;
                        string mngrEmail_2 = u.manager.manager.email;
                        cCEmails_lev2.add(mngrEmail_1);
                        cCEmails_lev2.add(mngrEmail_2);
                        
                    }
                }
                
                if(lev3 = true){
                    if(u.manager.manager.manager.email != null && u.manager.manager.manager.email != '' && u.manager.manager.manager.GD_No_Escalation__c == false ){
                        string mngrEmail_1 = u.manager.email;
                        string mngrEmail_2 = u.manager.manager.email;
                        string mngrEmail_3 = u.manager.manager.manager.email;
                        cCEmails_lev3.add(mngrEmail_1);
                        cCEmails_lev3.add(mngrEmail_2);
                        cCEmails_lev3.add(mngrEmail_3);
                        
                    }
                }
                
            }
            msg.setTemplateId(template.id);
            msg.setWhatId(leadRecord.id);
            msg.setTargetObjectId(con.id); 
            msg.setSaveAsActivity(false);
            String[] repEamail = new String[] {leadRecord.GD_Assigned_To_Email__c};
            msg.setToAddresses(repEamail);
            if(lev1 = true){msg.setCcAddresses(cCEmails_lev1);}
            if(lev2 = true){msg.setCcAddresses(cCEmails_lev2);}
            if(lev3 = true){msg.setCcAddresses(cCEmails_lev3);}
            lstMsgs.add(msg);
            Savepoint sp = Database.setSavepoint();
            Messaging.sendEmail(lstMsgs);
            Database.rollback(sp);
            List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
            for (Messaging.SingleEmailMessage email : lstMsgs) {
                Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
                emailToSend.setToAddresses(email.getToAddresses());
                emailToSend.setCcAddresses(email.getccAddresses());
                emailToSend.setPlainTextBody(email.getPlainTextBody());
                emailToSend.setHTMLBody(email.getHTMLBody());
                emailToSend.setSubject(email.getSubject());
                lstMsgsToSend.add(emailToSend);
            }
            Messaging.sendEmail(lstMsgsToSend);
        }
    }
}

Thanks & Regards,
Soundar.
Hi,

I have enabled multi currecny in my organisation.

1. I like to map "CurrencyIsoCode" in apex class. But it's not mapping, let's say for example i am selected a value from currency dropdown as USD in a lead object (Custom Object).

2. While convert to opportunity lead currecncy should map with opportunity currecncy. but always it's taking a corperate currecny.

3. Can you please give me a valid suggestion why this multi currecny is not mapping in apex code.
 
opportunity.CurrencyIsoCode = leadRecord.CurrencyIsoCode;
insert opportunity;

Thanks and Regards,
Soundar Rajan P.
Hi,

Can you please help me to update with bulkify of this coding.
 
ContentDocumentLink exFile=[SELECT Id, LinkedEntityId, ContentDocumentId, Visibility, IsDeleted, ShareType FROM ContentDocumentLink WHERE LinkedEntityId =: request.get(0).id];
                ContentDocumentLink newFile= exFile.clone();
                newFile.LinkedEntityId = con.id;
                
                insert newFile;
                delete exFile;

Thanks in Advance ,
Soundar.
Hi,

I created one batch class, which is sending a notofication based on few conditions.

As of now i am sending a static message body as mentioned in the given code.

I would like to call email template instead of this static message body.

Can you please check my code and let me know where i should change my code.
 
global void finish(Database.BatchableContext BC){     
EmailTemplate emailTemplate = [Select id,name from EmailTemplate where name = 'GD Lead No Activity Email Notification Template' limit 1];
        for(GD_Lead__c lead : leadList){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] repEamail = new String[] {lead.GD_Assigned_To_Email__c};
            mail.setSaveAsActivity(false);
            mail.setTemplateID(emailTemplate.Id); 
            //mail.setTargetObjectId(lead.Id);
            mail.setWhatId(lead.Id);
            mail.setToAddresses(repEamail); 
            //mail.setccAddresses(managerEmail);
            mail.setSubject('No Activity Reminder');
            mail.setPlainTextBody('Hi  '+ lead.GD_Sales_Rep_Name__c+', \n \nPlease be informed, we have not found any activities on this Lead since last '+ days + ' days.\n \nKindly take an immediate action before escalate.  \n \n Lead Name : '+lead.Name +' \n \n Lead Number : '+ lead.Lead_Unique_Number__c +'\n \nRegards, \nGulf Drug Group.');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }

Thanks in advance,
Soundar.
Hi,

I written one validation, That validation is not allowed a  user to edit the record once converted. It's working fine in a desktop mode. But it's allowed to edit a record in mobile view. Validation is appearing after record save (In Mobile View).

Please check my validation code and advise me what was the misatke on that AND is that any possible ways to reduce the validation rule.
 
AND(
OR(
ISPICKVAL(GD_Lead_Status__c, 'Working'),
ISPICKVAL(GD_Lead_Status__c, 'Nurturing'),
ISPICKVAL(GD_Lead_Status__c, 'Retired'),
ISPICKVAL(GD_Lead_Status__c, 'Unqualified'),
ISCHANGED( GD_Bid_Bond__c ) ,
ISCHANGED( GD_Lead_Priority__c ) ,
ISCHANGED( GD_Lead_Status__c ) ,
ISCHANGED( GD_Lead_Source__c ) ,
ISCHANGED( GD_Expected_Opportunity_Date__c ) ,
ISCHANGED( GD_Revenue__c) ,
ISCHANGED( GD_Lead_Description__c ) ,
ISCHANGED( GD_Source_Description__c ) ,
ISCHANGED( GD_Account__c ) ,
ISCHANGED( GD_Contact__c ) ,
ISCHANGED( GD_Retired_Reason__c ) ,
ISCHANGED( GD_Retired_Upto__c ) ,
ISCHANGED( GD_Competitor_Information__c ) ,
ISCHANGED( GD_Rejected_Reason__c ),
ISCHANGED( GD_Lead_Type__c ),
ISCHANGED( OwnerId )
),
ISPICKVAL(PRIORVALUE(GD_Lead_Status__c), 'Converted'),
Not($Profile.Name = "System Administrator"),
If(GD_Converted__c = True, true, false)
)

 Regards,
Soundar.
Hello senior,
I'm encountering error code MZDBJIKC when I try to "Check challenge". Does this mean I have to create a new trailhead playground and start-over my progress?
Hi Gurus,

i am trying to attempt https://trailhead.salesforce.com/en/content/learn/superbadges/superbadge_apex and installed the managed package as suggested but when I got to setup>>object manager ,I am unable to edit the standard object 'Case' to 'Maintenance Request',how do I update the standard object

Regards,
Fiona
HI,

I have following  scenarios,

1. I am enabling multi currency in my organisation.

2. So i can't create a roll-up summary fields in account object (to calculate total revenue from opportunity).

3. Is there only one way to create a roll-up summary field by flow builder (Without Apex).

4. So i decided to update a roll-up summary by using flow builder.

5. I am new to flow, can you please tell me step by step to achieve this process.

Regards,
Soundar.
Hi

I would like to give font-type Source Sans Pro for the entire html email template. How can I give inline css code in the following html template to achieve this?
 
<html style="overflow-y:hidden">
<head>
<title></title>
</head>
<body style="height:auto;min-height:auto">
<span style="font-size:30px"><b>Confirmation</b></span></br>
<span style="color:#f39c12"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;___________________</b></span></span>
<br /><br />
Thank you! We have successfully received your response<br />
and it is being processed.<br />
<br />
Your proof have been approved for PO#&nbsp;{!Clarification_Question__c.PO_Number__c}/SO#&nbsp;{!Clarification_Question__c.SO_Number__c}</br></br>
PO Number: {!Clarification_Question__c.PO_Number__c}</br>
Order Number: {!Clarification_Question__c.EBS_Order_Number__c}<br />
Approver First Name: {!Clarification_Question__c.Authorization_First_Name__c}</br>
Approver Last Name: {!Clarification_Question__c.Authorization_Last_Name__c}</br>
Company Name: {!Clarification_Question__c.Authorization_Organization__c}</br></br></span>
Now your order has moved straight into production, and you can keep tracking it right on our website! It’s quick</br> and easy when you<a href = "https://www.mackpro.com/US/login"> login</a> to your account or <a href = "https://www.mackpro.com/US/login">create a login</a> at <a href = "https://www.mackpro.com/US">mackpro.com</a>.</br></br>
All the Best,</br>
The Mackpro Customer Care Team

Thank you, 

Mit
  • August 03, 2020
  • Like
  • 0
Hi,

I want to create a rollup-summary-field without using a master Detail and apex class.

1. Through Flow Or Process builder.

Can you please write a steps to create a roll-up-summary fields, Scenarios is follows.


1. I am using Account & Aaccount team members standard object.
2. When i add a new team members filed to be update in account "No of sales rep".
3. When i delete a account team members the same field should update as well.

Thansk in advance.
Soundar. 
 
Hi,

I have the following scenarios.

1. I have Lead__c record, I need to track a record based on no activity.

2. it should based on Lead__c record and related task,events, and related list also.

3. what is the best way to implement this funcationality.

can you please suggest me a good way to achieve this functionality.

Regards,
Soundar.
Hi,

I am not able to view home tab in mobile view.

Can you please suggest me why it is not appearing in mobile application.

Please share a salesforce article link if you find it.

Regards,
Soundar.
IF( ISPICKVAL( StageName , "Closed Won") ||  ISPICKVAL( StageName,  "Closed Lost" )  ,    PRIORVALUE( StageName )  , PRIORVALUE( NOT ( StageName ) )  )

here I want the validation rule for when I select the Opportunity itself on the "stage" piclist value is selected in any one of "Closed Won " or "Closed Lost" then the value of the particular opportunity is not changed(that stage field in the "Closed Won" to Other(Closed Lost also) or "Closed Lost" to Other(Closed Won also) ) before. Here I tried as well as I know in the validation rule for the task but It's gives the error by followingly, "Error: Field StageName is a picklist field. Picklist fields are only supported in certain functions.".So please help me to complete ths task.For answers thanks in advance. 
Input search text given but output was not displaying

Lightning Component
Component
Controller
ControllerApex Class
Apex ClassOutput Preview
Output