• Tanmay Sahai
  • NEWBIE
  • 20 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 40
    Replies
Hi all,

I am trying to display a pop-up alert with a message on the uncheck of checkbox. I am using Standard controller and need to implement this functionality on the Contact Page Layout. I have a custom checkbo field: Customer__c (default unchecked). What my requirement is that when I check this,it should save normally (this is happenning) but when some user tries to uncheck it, that user should get a pop-up alert with the message.

I have created a VF page for the same and a controller class. I have placed the VF page on the Standard Contact Page Layout keeping the Height as 0. But whenever I uncheck and try to save the record, the pop-up doesn't showup. What am I missing in my code (I don't get any compile/debug errors). Am I doing anything wrong??

Below is the code for VF:

<apex:page standardcontroller="Contact" rendered="{!(Contact.Customer__c)}" >
<script type="text/javascript">
    var msg="Unchecking this box will imply that the user has churned and will automatically de-activate in the Admin Panel.If you dont want that to happen, kindly check the box again";
    function throwalert{
       if ( {!Contact.Customer__c} == false)
       {
          alert(msg); setAlertVal();
       }
     }
     window.onclick = throwalert();
</script>
</apex:page>

This is the code for the controller:

public class PopUpAlert
{
public Contact cont;

  public PopUpAlert(ApexPages.StandardController controller){

   Contact cont = (Contact)controller.getRecord();
    cont=[select id,Customer__c from Contact where Id=: cont.ID];
    
  }
  public void setAlertVal(){
     cont.Customer__c = false;
     update cont;
  }
}

Look forward for quick and valuable comments/recommendations.
Thanks!
Hi All,

I am seeking help to write a Test Class for atleast 75% code coverage for my Trigger which I have written for Event. Below is my Trigger code:

trigger EventTrigger on Event (after update)
{

    List<opportunity> opportunities = new List<opportunity>();
    //List<Id> idAccountList = new List<Id>();
    List<Event> eventToprocessList = new List<Event>();
    String eventType;
    List<String> oppEventIdList = new List<String>();
    String sBreak = '</br>';
    
    for(Event event :Trigger.new)
    {
        eventType = event.Event_Type__c;
                if(!event.Event_Type__c.containsIgnoreCase('Demo') || event.Demo_Status__c != 'Complete')continue;
                //if(eventType!=NULL && eventType.containsIgnoreCase('email') )
            //if(event.WhatId!=NULL && event.WhatId.getSObjectType() == Account.SObjectType )
                //eventToprocessList.add(event);
                //if(!idAccountList.contains(event.whatid))
                    //idAccountList.add(event.WhatId);
          //if(event.WhatId.getSObjectType() != Account.SObjectType) continue;
        
        //idAccountList.add(event.WhatId);
        eventToprocessList.add(event);
        oppEventIdList.add(event.Id);
     }
   
       Set<String> eventIdSet = new Set<String>();
       for(Opportunity opp : [SELECT Id, Event_ID__c FROM Opportunity WHERE Event_ID__c = : oppEventIdList])
       {
           eventIdSet.add(opp.Event_ID__c);
       }
       
    //if(idAccountList.isEmpty()) return;
    
    //Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account WHERE Id IN :idAccountList]);
                   
    
    //Account[] AccNames=[select name from account where id in :idAccountList];
    //map<string,string> AcccountMap= new map<string,string>();
    //for(integer i=0;i<AccNames.size();i++){
        //AcccountMap.put(idAccountList[i],AccNames[i].name );
   
    
    for(Event event : eventToprocessList)
    {
    
        if(!eventIdSet.IsEmpty() && eventIdSet.contains(event.Id)) continue;
        
        //system.debug(accountMap.get(event.whatid));
        //Creating opppty
        opportunity opp = new opportunity();
            opp.Name = event.Subj_del__c + ' ' + '| RP |'+ ' ' + event.Seats__c + ' ' + 'Seats';
            //Name = 'Test oppp'+ 'Amount'+'(event.Id).Contact_Lookup__c',
            opp.CloseDate = Date.Today()+ 90;
            opp.Type = 'New Business';
            //Notes__c = Trigger.newMap.get(event.Id).Notes__c,
            //opp.Notes_del__c = Trigger.newMap.get(event.WhoI).Sample_Note__c;
                        //fill other mandatory fields comma seperated as shown above
            //opp.AccountId = event.WhatId;
            opp.AccountId = Trigger.newMap.get(event.Id).AccountId;
            //Contact_Lookup__c = Trigger.newMap.get(event.Id).Contact_Lookup__c,
            opp.StageName = 'Pre-Qualified';
            opp.Referring_SDR__c= event.OwnerId;
            opp.Contact_Name__c = event.Related_Contact_Name__c;
            opp.opportunity_Owner__c= event.Assigned_AE__c;
            opp.Notes_del__c = event.Post_Demo_Notes__c + event.Pre_Demo_Notes__c;
            opp.Pre_Demo_Notes__c = Trigger.newMap.get(event.Related_Contact_Name__c).Pre_Demo_Notes__c+''+event.Pre_Demo_Notes__c;  
            opp.Post_Demo_Notes__c = Trigger.newMap.get(event.Related_Contact_Name__c).Post_Demo_Notes__c+''+event.Post_Demo_Notes__c;
            opp.Amt__c= event.Amount__c;
            opp.Seat_Number__c= event.Seats__c;
            opp.LeadSource= event.Lead_Source__c;
            opp.New_Lead_Source__c= event.New_Lead_Source__c;
            
            //opp.LeadSource = Trigger.newMap.get(event.WhoId).Lead_Source__c;
            //opp.New_Lead_Source__c= Trigger.newMap.get(event.WhoId).New_Lead_Source__c;
            opp.Contact_Name__c = event.WhoId;
            opp.Event_ID__c = event.Id;
            //opp.Account_Name__c = Trigger.newMap.get(event.WhoId).Account;
        
         opportunities.add(opp);
    }
    system.debug('List of Records to be Created: '+opportunities);
    
    if(opportunities.size()>0)
    {
        insert opportunities;
    }
  }

Also can someone help me the code bulkification of the trigger.

Await your responses!

Thanks!!
Hi All,
Below is my Apex Code which I have created to auotmate Lead Conversion to Account and Contact:

Public class AutoConvertLeads
{
    @InvocableMethod //Used to invoke this Class in Process Builder
    public static void LeadAssign(List<Id> LeadIds)
    {
     map< id,id> mapAccount = new map<id,id>();
     {
       for(Account a : [SELECT id,Company_Name_Custom__c from Account])
        {
         mapAccount.put(a.Company_Name_Custom__c, a.id);
        }

        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(Lead currentlead: [SELECT Id,Company_Name_Custom__c from Lead where Id in:LeadIds ])
     {
         if( !mapAccount.isEmpty() && mapAccount.ContainsKey(currentlead.Company_Name_Custom__c) )
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.Id);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                Leadconvert.setAccountId(mapAccount.get(currentlead.Company_Name_Custom__c));
                MassLeadconvert.add(Leadconvert);
             
         }
         else
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.Id);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
         }
      }

        
        if (!MassLeadconvert.isEmpty())
        {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }   }    
}

The code is working fine but I have 1 problem with it:

The converted contact is always attaching to the Same account no matter which account name you put in the company for the lead conversion.

Below is my requirement:
" Our leads flow into Salesforce from Admin Panel/HubSpot. Custom Company Name is a common Lead field for both HubSpot and Salesforce. When the Lead is created by flowing into Salesforce, the standard Company field of Lead is blank or [not provided].

We also have a check box on the Lead named: Created in Panel.


What we want is to convert only those leads which have this Created in Admin Panel checkbox true. Also, on conversion, the value in the Custom Company Name should overwrite the Company of the Lead thereby replacing it as Account Name on the Converted Contact.

Then, if the Account already exists, it should only create a contact and attach to the existing Account.
"

Can anyone of you help me with tweaking the code to meet my above requirement.

Appreciate your help and prompt response.

Thanks!
TS
Hello all,

I have created an Apex Class to convert leads into Account and Contact and have also put the account duplication check. It is using Invocable method as it is being used in a PB. But my code is not compiling although I have all the custom fields available and have checked the FLS as well.

Below is the code:

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds){}
    public static map< id,id> mapAccount = new map<id,id>();
    {
    for(Account a : [select id from Account])
{
     mapAccount.put(a.id, a.id);
}

    
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds)
     {
         if(mapAccount.get(currentlead.Company_Name_Custom__c ) != NULL)
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                Leadconvert.setAccountId(mapAccount.get(currentlead.Company_Name_Custom__c ));
                MassLeadconvert.add(Leadconvert);
             
         }
         else
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
         }
      }

        
        if (!MassLeadconvert.isEmpty())
        {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }    
}

   Here is the screenshot of the errors:
User-added image
Can any one of you help me with the improved code.

My scenario is:
" Our leads flows from third party apps (like chartio/hubspot) to Salesforce. We have a check box which shows whether the Lead came from these apps or were created manually. We want to automate the Lead Conversion on the basis of this Checkbox(True: Convert; False: Don't convert). I have implemented this requirement using an Apex Class and PB. However, this resulted in Duplicate Account Creation and sometimes Contact created without Account. "

The Name of the Company maps to the Company Name Custom (API Name: Company_Name_Custom__c) when the Lead flows to Salesforce. But when converting lead, it is taking the default Lead Standard field: Company and thus resulting in duplicate and/or blank accounts. I have used the custom field in my logic but still getting an error.

As per our lead conversion process, a lead is converted to An Account (the name of the company) and  contact(name of the lead) for the first time. Then if we want to create a new contact for the existing account, we again create a new lead  and select the existing Account as company and convert that lead into contact and the contact gets attached to the Account.

Look forward for your suggestions/responses.
Thanks!
 
Hi All,
I have created a Test Class to deploy my Apex Class. My Apex class is invocble and is working fine in Sandbox. However, when I try to execute my Test Class, I get the below error:
Apex Test Result Detail 
Time Started7/3/2018 11:44 PM
ClassAutoConvertLeadsTest
Method NameAutoConvertLeads
Pass/FailFail
Error MessageSystem.DmlException: ConvertLead failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, valid leadId is required: []
Stack TraceClass.AutoConvertLeads.LeadAssign: line 17, column 1
Class.AutoConvertLeadsTest.AutoConvertLeads: line 26, column 1

Below is the code for my Apex Class ( This class is then used in a PB to convert leads) :
Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

And this is the code for my Test Class:
@isTest (seeAllData = true )
private class AutoConvertLeadsTest {

    static testMethod void AutoConvertLeads() {
            List<id> LeadIds=new List<id>();
            for(LeadStatus a : [select id from LeadStatus]){
                LeadIds.add(a.id);
            }
        AutoConvertLeads Obj = new AutoConvertLeads();
    AutoConvertLeads.LeadAssign(LeadIds);
            
        }

}

Not sure where am I going wrong or am I missing any steps?
Hello All,

I have created an Apex class with invocable method and using it in a Process builder to automate my lead convrsion. The code is working but I need help with 2 things:
1. My code is creating duplicate accounts. Can someone help with the de-duplication of the Account. Basically what I am looing for is that if there is already an account, the lead should only be converted to Contact and if there is no Account, then it should create both Account and Contact.
2. I need help with writing a Test Class so that I can deploy it to Production.

Do I need to make sure that both my Apex class and Test Class have a 75% code coverage or more.

Below is my Apex Class code:

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 100];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

Any quick help will be appreciated. Thanks in advance!
Hi All,

I have created a trigger to automate my opportunity creation from Event. The trigger is working fine but the related contact of the created opportunity doesn't get attached to it under Contact Role( Related Contact) but as per standard process, if an opportunity is created from the contact, the opportunity shows the related to Contact.

How can I achieve this above requirement by making the change in the below trigger code:

trigger EventTrigger on Event (after update)
{

    List<opportunity> opportunities = new List<opportunity>();
    List<Event> eventToprocessList = new List<Event>();
    String eventType;
    List<String> oppEventIdList = new List<String>();
    
    for(Event event :Trigger.new)
    {
        eventType = event.Event_Type__c;
                if(!event.Event_Type__c.containsIgnoreCase('Demo') || event.Demo_Status__c != 'Complete')continue;
    
        eventToprocessList.add(event);
        oppEventIdList.add(event.Id);
     }
   
       Set<String> eventIdSet = new Set<String>();
       for(Opportunity opp : [SELECT Id, Event_ID__c FROM Opportunity WHERE Event_ID__c = : oppEventIdList])
       {
           eventIdSet.add(opp.Event_ID__c);
       }

    for(Event event : eventToprocessList)
    {
    
        if(!eventIdSet.IsEmpty() && eventIdSet.contains(event.Id)) continue;
        
      
        //Creating opppty
        opportunity opp = new opportunity();
            opp.Name = event.Subj_del__c + ' ' + '| RP |'+ ' ' + event.Seats__c + ' ' + 'Seats';
            //Name = 'Test oppp'+ 'Amount'+'(event.Id).Contact_Lookup__c',
            opp.CloseDate = Date.Today()+ 90;
            opp.Type = 'New Business';
            //Notes__c = Trigger.newMap.get(event.Id).Notes__c,
             opp.Notes_del__c = event.Notes__c;
            //fill other mandatory fields comma seperated as shown above
            //opp.AccountId = event.WhatId;
            opp.AccountId = Trigger.newMap.get(event.Id).AccountId;
            //Contact_Lookup__c = Trigger.newMap.get(event.Id).Contact_Lookup__c,
            opp.StageName = 'Pre-Qualified';
            opp.Referring_SDR__c= event.OwnerId;
            opp.Contact_Name__c = event.Related_Contact_Name__c;
            opp.opportunity_Owner__c= event.Assigned_AE__c;
            opp.Amt__c= event.Amount__c;
            opp.Seat_Number__c= event.Seats__c;
            opp.LeadSource= event.Lead_Source__c;
            opp.New_Lead_Source__c= event.New_Lead_Source__c;
            //opp.LeadSource = Trigger.newMap.get(event.WhoId).Lead_Source__c;
            //opp.New_Lead_Source__c= Trigger.newMap.get(event.WhoId).New_Lead_Source__c;
            opp.Contact_Name__c = event.WhoId;
            opp.Event_ID__c = event.Id;
            //opp.Account_Name__c = Trigger.newMap.get(event.WhoId).Account;
        
         opportunities.add(opp);
    }
    system.debug('List of Records to be Created: '+opportunities);
    
    if(opportunities.size()>0)
    {
        insert opportunities;
    }
  }

Look forward for your responses. Thanks is advance!
Hi Developers,

I am looking to display the Last Modified Date when the Account Ownership changed (as displayed under Account History) on a field to use it in my trigger to calculate the difference between LastActivityDate and LastOwnershipChangedDate.

Here is my requirement:
I have a custom formula field: User Last Activity which calculates the number of days since last activity on the Account (this is calculated using the System field :LastActivityDate). Similarly, I want to calculate the number of days since last time the Account ownership changed. Below screenshot shows the Date that I want to capture and display on a field and then use this date to calculate the days on another formula field:

Scree shot showing the Date of Owner Ship change

Lets take User Last Activity as u and OwnershipLastChanged as v. Now, I want to change the ownership when:

If u>=v, then u else if u<v, then v. So, basically the account ownership should change only when either the Last User Activity >30 or Last Ownership Change <30 and if u>v then change on the basis of u else on the basis iof v.

Here is my trigger:

trigger Account_After_Update on Account (after update) {

map<id,id> accountOldOwnerid = new map<id,id>();

   list<account> updateaccount = new list<account>();

   

   if(trigger.isAfter && trigger.isUpdate){

for(account a :trigger.new){

    string oldownerid  = trigger.oldmap.get(a.id).OwnerId;

    string newownerid  = a.ownerid;

    if(oldownerid != newownerid){

accountOldOwnerid.put(a.id,oldownerid );

    }

}

map<id,User> oldowners = new map<id,User> ( [Select u.id ,u.IsActive From User u where u.id in : accountOldOwnerid.values()
                                             and u.isActive = true and u.id!= '00536000001hfleAAA']);

list<Account> accs = [ select OwnerId, ( select Id, CreatedDate, Field, CreatedBy.Name, OldValue, NewValue from AccountHistory where AccountId = '001W000000ZVss1IAD'  ) from account where id=:accountOldOwnerid.keyset()];

  for( Account acc : accs)
  {
     
  Id oldOwnerId =   accountOldOwnerid.get(acc.id);

  //if(oldowners.containsKey(oldOwnerId))  
  //{

    //for( Account ac :acc.tasks){

            //accs.OwnerId = oldOwnerId;
            //tasks.Id = oldOwnerId}

  }

    if(updateaccount.size()>0)
    {
     updateaccount.add(accs);
    }

     update updateaccount();

   }
}

Below is my class:
global class DailyAccountProcessor implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
            List<Account>listofAccount =
            [SELECT Id from Account where OwnerId != '00536000001hfleAAA' AND User_Last_Activity__c >30 AND of_Days_since_Last_Modification__c >30 LIMIT 200];
        
        List<Account>listofUpdatedAccount = new List<Account>();
        if(!listofAccount.isEmpty())
        {
            for(Account acc : listofAccount)
            {
                acc.OwnerId = '00536000001hfleAAA';
                listofUpdatedAccount.add(acc);
            }
                
                UPDATE listofUpdatedAccount;
        }
    }
}

Note: of_Days_since_Last_Modification__c calculates the number of days since last modified date (TODAY() - LastModifiedDate)

Any quick help/suggestions will be appreciated. Any other workarounds are also welcome.

Await your response guys.

Thanks!
Hi All,

I am looking to automatically change the account ownership to a default user when the last activity date by the current account owner exceeds 30 days.
I am using a default System feild : Last Activity Date but it gives the last activity of the Account user instead of the Account owner. Do I need a separate trigger to update this field and then use this field value in another trigger.

Can somebody help me with the trigger??

Thanks in advance!
Hello All,

I am looking for a functionality wherein I am creating an opportunity from the event. The condition is that the oppty will only be created when the Event-Type is Demo and the Status ( a custom picklist field on the Event) = Complete.
I have created a trigger to achieve this requirement. Below is the code:

trigger EventTrigger on Event (after update){

    List<Opportunity> opportunities = new List<Opportunity>();
    List<Id> idAccountList = new List<Id>();
    List<Event> eventToProcessList = new List<Event>();
    String eventType;
    
    for(Event event :Trigger.new) {

        eventType = event.Type;
        if(!eventType.containsIgnoreCase('demo') || eventType.Demo_Status__c != 'Completed') continue;

        if(event.WhatId.getSObjectType() != Account.SObjectType) continue;
        
        idAccountList.add(event.WhatId);
        eventToProcessList.add(event);
        
    }
    
    if(idAccountList.isEmpty()) return;
    
    Map<Id, Account> accountMap = [SELECT Id, Name FROM Account WHERE Id IN :idAccountList];
    
    for(Event event : eventToProcessList){
        
        Opportunity opp = new Opportunity(
            Name = accountMap.get(event.WhatId).Name + '|RP|' + event.Seats__c,
            //Name = 'Test Opp'+ 'Amount'+'(event.Id).Contact_Lookup__c',
            CloseDate = Date.Today()+ 90,
            Type = 'New Business',
            //Notes__c = Trigger.newMap.get(event.Id).Notes__c,
            Notes__c = event.Notes__c,
            //fill other mandatory fields comma seperated as shown above
            AccountId = event.WhatId,
            //Contact_Lookup__c = Trigger.newMap.get(event.Id).Contact_Lookup__c,
            StageName = 'Pre-Qualified',
            Referring_SDR__c= event.OwnerId,
            Contact_Name__c = event.Related_Contact_Name__c,
            Opportunity_Owner__c= event.Assigned_AE__c,
            Amt__c= event.Amount__c,
            Seat_Number__c= event.Seats__c,
            LeadSource= event.Lead_Source__c,
            New_Lead_Source__c= event.New_Lead_Source__c
         );
         opportunities.add(opp);
    }

    if(!opportunities.isEmpty()){
        insert opportunities;
    }
}

But I am getting the below compile error:
" Error: Compile Error: Variable does not exist: Demo_Status__c at line 11 column 63 "
Not sure why this is coming as the API name is correct as per my knowledge.

Also, additionally I am looking to map this event to the opportunity that gets created via trigger for this event on the basis of EventId/ActivityId so that we can create a report to track the number of events that got converted into opportunities.

Any quick help will be highly appreciated.  Thanks in advance!
Hello All,

I have custom picklist Status on the Event page layout and I am using one of its value to automate Oppty creation using a Trigger. So, when the Status=Complete, it creates an opportunity. Also, the event type = Demo. So the condition is that when my event is Demo(custom picklist value) and its Status is Complete, oppty gets created.
Below is the trigger:

trigger EventTrigger on Event (after update){
    List<Opportunity> opportunities = new List<Opportunity>();

    for(Event event :Trigger.new){
        if(event.Demo_Status__c == 'Complete'){
            Opportunity opp = new Opportunity
                Name = '| RP |' + event.Seats__c,
                //Name = 'Test Opp'+ 'Amount'+'(event.Id).Contact_Lookup__c',
                CloseDate = Date.Today()+ 90,
                Type = 'New Business',
                //Notes__c = Trigger.newMap.get(event.Id).Notes__c,
                Notes__c = event.Notes__c,
                
                //fill other mandatory fields comma seperated as shown above
                AccountId = Trigger.newMap.get(event.Id).AccountId,
                //Contact_Lookup__c = Trigger.newMap.get(event.Id).Contact_Lookup__c,
                StageName = 'Pre-Qualified',
                Referring_SDR__c= event.Assigned_AE__c,
                Contact_Name__c = event.Related_Contact_Name__c,
                Opportunity_Owner__c= event.Assigned_AE__c,
                Amt__c= event.Amount__c,
                Seat_Number__c= event.Seats__c,
                LeadSource= event.Lead_Source__c,
                New_Lead_Source__c= event.New_Lead_Source__c
            );
            opportunities.add(opp);
        }
    }

    if(!opportunities.isEmpty()){
        insert opportunities;
    }
}

Now my requirement is:
1. I want to display the Name of Oppty as:
Account Name | RP | X Demo

2. I want to automatically populate the Assigned To (its a standard Event Field) value from Event to the Referring SDR(Custom Lookup(User)) custom field on the Oppty when it gets created
Screen shot shwoing the Custom fields on the Event page with values
Field Name                                API Name
Assigned To(On Event)             Owner
Referring SDR(On Oppty)         Referring_SDR__c

3. I want to flow the DemoID (if availble) or the Activity ID/Event ID to the Opportunity when its gets automatically created.

Any inputs will be highly helpful.

Thanks!
Hi All,
Below is my Apex Code which I have created to auotmate Lead Conversion to Account and Contact:

Public class AutoConvertLeads
{
    @InvocableMethod //Used to invoke this Class in Process Builder
    public static void LeadAssign(List<Id> LeadIds)
    {
     map< id,id> mapAccount = new map<id,id>();
     {
       for(Account a : [SELECT id,Company_Name_Custom__c from Account])
        {
         mapAccount.put(a.Company_Name_Custom__c, a.id);
        }

        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(Lead currentlead: [SELECT Id,Company_Name_Custom__c from Lead where Id in:LeadIds ])
     {
         if( !mapAccount.isEmpty() && mapAccount.ContainsKey(currentlead.Company_Name_Custom__c) )
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.Id);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                Leadconvert.setAccountId(mapAccount.get(currentlead.Company_Name_Custom__c));
                MassLeadconvert.add(Leadconvert);
             
         }
         else
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.Id);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
         }
      }

        
        if (!MassLeadconvert.isEmpty())
        {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }   }    
}

The code is working fine but I have 1 problem with it:

The converted contact is always attaching to the Same account no matter which account name you put in the company for the lead conversion.

Below is my requirement:
" Our leads flow into Salesforce from Admin Panel/HubSpot. Custom Company Name is a common Lead field for both HubSpot and Salesforce. When the Lead is created by flowing into Salesforce, the standard Company field of Lead is blank or [not provided].

We also have a check box on the Lead named: Created in Panel.


What we want is to convert only those leads which have this Created in Admin Panel checkbox true. Also, on conversion, the value in the Custom Company Name should overwrite the Company of the Lead thereby replacing it as Account Name on the Converted Contact.

Then, if the Account already exists, it should only create a contact and attach to the existing Account.
"

Can anyone of you help me with tweaking the code to meet my above requirement.

Appreciate your help and prompt response.

Thanks!
TS
Hello all,

I have created an Apex Class to convert leads into Account and Contact and have also put the account duplication check. It is using Invocable method as it is being used in a PB. But my code is not compiling although I have all the custom fields available and have checked the FLS as well.

Below is the code:

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds){}
    public static map< id,id> mapAccount = new map<id,id>();
    {
    for(Account a : [select id from Account])
{
     mapAccount.put(a.id, a.id);
}

    
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds)
     {
         if(mapAccount.get(currentlead.Company_Name_Custom__c ) != NULL)
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                Leadconvert.setAccountId(mapAccount.get(currentlead.Company_Name_Custom__c ));
                MassLeadconvert.add(Leadconvert);
             
         }
         else
         {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
         }
      }

        
        if (!MassLeadconvert.isEmpty())
        {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }    
}

   Here is the screenshot of the errors:
User-added image
Can any one of you help me with the improved code.

My scenario is:
" Our leads flows from third party apps (like chartio/hubspot) to Salesforce. We have a check box which shows whether the Lead came from these apps or were created manually. We want to automate the Lead Conversion on the basis of this Checkbox(True: Convert; False: Don't convert). I have implemented this requirement using an Apex Class and PB. However, this resulted in Duplicate Account Creation and sometimes Contact created without Account. "

The Name of the Company maps to the Company Name Custom (API Name: Company_Name_Custom__c) when the Lead flows to Salesforce. But when converting lead, it is taking the default Lead Standard field: Company and thus resulting in duplicate and/or blank accounts. I have used the custom field in my logic but still getting an error.

As per our lead conversion process, a lead is converted to An Account (the name of the company) and  contact(name of the lead) for the first time. Then if we want to create a new contact for the existing account, we again create a new lead  and select the existing Account as company and convert that lead into contact and the contact gets attached to the Account.

Look forward for your suggestions/responses.
Thanks!
 
Hi All,
I have created a Test Class to deploy my Apex Class. My Apex class is invocble and is working fine in Sandbox. However, when I try to execute my Test Class, I get the below error:
Apex Test Result Detail 
Time Started7/3/2018 11:44 PM
ClassAutoConvertLeadsTest
Method NameAutoConvertLeads
Pass/FailFail
Error MessageSystem.DmlException: ConvertLead failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, valid leadId is required: []
Stack TraceClass.AutoConvertLeads.LeadAssign: line 17, column 1
Class.AutoConvertLeadsTest.AutoConvertLeads: line 26, column 1

Below is the code for my Apex Class ( This class is then used in a PB to convert leads) :
Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

And this is the code for my Test Class:
@isTest (seeAllData = true )
private class AutoConvertLeadsTest {

    static testMethod void AutoConvertLeads() {
            List<id> LeadIds=new List<id>();
            for(LeadStatus a : [select id from LeadStatus]){
                LeadIds.add(a.id);
            }
        AutoConvertLeads Obj = new AutoConvertLeads();
    AutoConvertLeads.LeadAssign(LeadIds);
            
        }

}

Not sure where am I going wrong or am I missing any steps?
Hello All,

I have created an Apex class with invocable method and using it in a Process builder to automate my lead convrsion. The code is working but I need help with 2 things:
1. My code is creating duplicate accounts. Can someone help with the de-duplication of the Account. Basically what I am looing for is that if there is already an account, the lead should only be converted to Contact and if there is no Account, then it should create both Account and Contact.
2. I need help with writing a Test Class so that I can deploy it to Production.

Do I need to make sure that both my Apex class and Test Class have a 75% code coverage or more.

Below is my Apex Class code:

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 100];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

Any quick help will be appreciated. Thanks in advance!