• Shawn Reichner 29
  • NEWBIE
  • 478 Points
  • Member since 2017

  • Chatter
    Feed
  • 11
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 35
    Questions
  • 148
    Replies
I have one checkbox field on account object and I want to create workflow rule where every time that checkbox values go from True to False then it will update one field which is date data type with on which date that checkbox goes from true to false and I do not want to update that date field when record is created it only fired when checkbox goes from true to false
What workflow rule do I run to populate a currency field with the value from another currency field on the same object (opp page)? 

Tried using TEXT () and VALUE () but kept getting errors.
Hi I am trying to figure out to how trigger works for updating checkbox on Case object when checkboxfield of other custom object is set to true ,Lets say I have a custom field Required__c on Destination object and I have a Criteria__c  field on Case object, whenever required__c is true I want to update the criteria__c on case object to true , can anyone please guide me on this 

Thanks in advance
  • November 03, 2017
  • Like
  • 0
Is there an easy way to find out how many records in a custom object have Notes and attachments in them?
I schedule a data export report, but that did not work. I'm working with Salesforce support.
Meanwhile, want to find out if there is a way to find out how many records have attachments.
 
Hello gurus,
I'm trying to be a better developer by writing the test code first.  I can't create all the needed test objects.  Account, Contact, Case are created and I can see the IDs in the debug log but get an error when creating the Asset.  What am I overlooking?

There is no other code created yet.
 
@IsTest(SeeAllData=True)

public class AssetUpdateTest {
    
    public static testmethod void testAssetLink()    {
        Account acc = createAccount(); 
        Contact con = createContact(acc); 
        Case cas = createCase(acc,con); 
        Asset ast = createAsset(acc,con,cas); 

        System.debug('**************************   Case ID: ' + cas.id); 
        System.debug('**************************   Case.Asset: ' + cas.AssetId);
        
    }
    
    public static Account createAccount(){
        Account theAccount = new Account(
            recordtypeid='01270000000Q7rQ', 
            name='Test Account', 
            Status__c='Client',
            Line_of_Business__c='CRS',
            phone='8005551212', 
            currencyisocode='USD'); 
        
        insert theAccount;
        return theAccount; 
    }    
    
    public static Contact createContact(Account theAccount){
        Contact theContact = new Contact(
            recordtypeid='01270000000Q7ra',
            email='tim.bouscal@audatex.com', 
            firstname='George', 
            lastname='Washington',
            accountid=theAccount.id);
        insert theContact;        
        return theContact; 
    }
    
    public static Case createCase(Account acc, Contact con){
        Case theCase = new Case(
            recordtypeid='01270000000Dy9u', 
            AccountId = acc.Id, 
            ContactId = con.Id,             
            
            Requestor__c=con.Id, 
            Reason='New Account Setup', 
            Reason_Detail__c='New - ADXE Shop 02',
            Status='New', 
            Origin='Sales Request', 
            Subject='AssetUpdateTest Sample BisOps Case', 
            Description='This is a sample case for testig the AssetUpdate class'
        ); 
        insert theCase; 
        return theCase;
    }    
    
    public static Asset createAsset(Account acc, Contact con, Case cas){
        System.debug('***** ***** ***** Account ID: ' + acc.id + '     Contact Id: ' + con.id + '     Case ID: '+ cas.Id); // all 3 values show in debug log
        Asset theAsset = new Asset(
            Name='Test Asset', 
            Account = acc, 
            Contact = con, 
            Case_Number__c = cas.CaseNumber, 
            Type__c='New', 
            Status='Purchased', 
            Description='This is a test asset for testing the AssetUpdate class'
        );
        insert theAsset; 
        return theAsset; 
    }
}

Error: 
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Every asset needs an account, a contact, or both.: [AccountId, ContactId]

Class.AssetUpdateTest.createAsset: line 69, column 1
Class.AssetUpdateTest.testAssetLink: line 9, column 1

 
Hello all,
I currently have the following logic in a workflow rule to determine when to send out an email alert:

AND ( 
RecordTypeId <> "012C0000000CCTo", 
ISCHANGED ( Requested_Dev_Date__c ), 

OR 
(ISPICKVAL (StageName , "6.5 Process with Signature" ), 
(ISPICKVAL (StageName , "6.3 Process without Signature" )) 
)))

I now have a need to test for more than one record type ID, while the rest of the logic would stay the same. How do I best accomplish this code? Is the right approach a CASE statement, or IF? How would this be structured?
 
Hi,

How do you "read" (in plane English) this piece of code?
List<OpportunityShare> oppShareList = [select Id, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId IN :opportunityIdList and RowCause = 'Team'];
My interpretation is...

Create a variable of the type List<OpportunityShare> which is called oppShareList and assign the following records to such list: all records (display the fields Id, OpportunityAccessLevel, etc...) FROM the table OpportunityShare WHERE ...????

I do not understand the code after the WHERE

Could someone explain?

Thank you very much.


 
Hi All,

I have a request from our business, to create a field on a custom object called Vehicle, A field that show the total values of the opportunities associated with the specific vehicle. Our in-house developer managed to do that, but with a schedule rule that runs only once/day, and the request is to show the total amount every time an amount in a opportunity is updated.

The developer created 2 different classes, one to make a sum of all values from all opportunities:
/* @date 29.09.2017 */
/* @description for update a summary field on vehicle level, which sums up the opportunity amount of the related opportunities*/
global class Opportunity_Amount_Update implements Database.Batchable<sObject>  {

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT ID FROM Vehicle__c ' );
    }
    
    global decimal STTO = 0;

    global void execute(Database.BatchableContext bc, List<Vehicle__c> scope){
        // process each batch of records
        Set<Vehicle__c> Veh = new Set<Vehicle__c>();
        List<Vehicle__c> Veh1 = new List<Vehicle__c>();
        List<Opportunity> OPP = [Select Id, GH_Vehicle__c, Amount from Opportunity WHERE GH_Vehicle__c <>'']; 
          for (Vehicle__c VEx : scope) {    
            for (Opportunity Opps1 : OPP ) {
                 if(Opps1.GH_Vehicle__c == VEx.id) {
                     STTO = STTO + Opps1.Amount;
                 }
            }
            VEx.Opportunity_amount__c = STTO;
            Veh.add(VEx);
            STTO = 0;
         }
        Veh1.addall(Veh);
        update Veh1;
    }    

    global void finish(Database.BatchableContext bc){
    }    
}

And another one as a scheduler:
global class Opportunity_Amount_Update_scheduler implements Schedulable {
    global void execute(SchedulableContext ctx) {
        Opportunity_Amount_Update OA = new Opportunity_Amount_Update();
        DataBase.executeBatch(OA);
    }
}

Ans as I mentionated abowe, we need the first class (Opportunity_Amount_Update) to run every time the value of an opportunity changes.
Can you please help me with this, if it can be made like that?

Thank You
Calin B
I'm VERY new to Apex (literally all coding) and am trying to figure out how to update the Priority to High on an activity after it has become overdue by 10 days.

The Priority field update is the only thing that I need to happen and I cannot figure out what I'm missing.  My alerts are both on line 3; unexpected token ':' and unexpected syntax: 'mismatched input':' expecting Semicolon.
User-added image

Being pointed in the right direction would be greatly appreciated!

Hi

I am using this app from the app exchange (https://appexchange.salesforce.com/listingDetail?listingId=a0N300000016cbDEAQ) to ensure that a contact role is added to an opportunity when a certain stage is selected on the opportunity. This works perfectly when updating an existing opportunity but I dont want it to apply when creating new opportunities.

I thought I could just add NOT(IsNew()) to the custom field, but it gives an error of IsNew can't be used in this type of formula.

Any ideas of how I can exclude this trigger from firing when creating a new opportunity would be appreciated?

Custom Field

IF( 
DATEVALUE( CreatedDate ) >= DATE(2017,09,28), 
CASE( 
StageName, 
"Stage to be Required 1",1, 
"Define",1, 
"Meeting / Proposal",1, 
"Negotiation",1, 
"Verbal Agreement/Contract",1, 
"Closed Won",1, 
0 
), 
0	
)
 


 

Apex Class

//This is provided as a sample to require a contact on opportunities it is provided without warranty and support. 

trigger opportunity_contact_required on Opportunity (before insert, before update) {

    //map to keep track of the contact_required = 1
    Map<String, Opportunity> oppy_contact = new Map<String, Opportunity>();

    //Trigger.new is an array of opportunities 
    //and adds any that have Contact_Required = 1 to the oppy_contact Map
    for (Integer i = 0; i < Trigger.new.size(); i++) {
        System.debug('*****Required? ' + Trigger.new[i].contact_required__c);
        if  (Trigger.new[i].contact_required__c == 1) {
            oppy_contact.put(Trigger.new[i].id,Trigger.new[i]);
        }
    }

    //map to keep track of the opportunity contact roles
    map<Id, OpportunityContactRole> oppycontactroles = new map<Id, OpportunityContactRole>();

    //select OpportunityContactRoles for the opportunities with contact role required 

    List<OpportunityContactRole> roles = [select OpportunityId, IsPrimary from OpportunityContactRole
        where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId
        in :oppy_contact.keySet())];


    for (OpportunityContactRole ocr : roles) {
        //puts the contact roles in the map with the Opportunity ID as the key
        oppycontactroles.put(ocr.OpportunityId,ocr);
    }

    // Loop through the opportunities and check if they exists in the contact roles map or contact role isn't required    
    for (Opportunity oppy : system.trigger.new) {
        //system.debug('List oppy Id - '+oppy.id);
        if  (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id))
        {
            oppy.addError('No Primary Contact has been added to the opportunity. Please go to the Contact Roles and select a primary contact.');       
        }
    } //for    
 }

Apex Test Class
 
public class test_opportunity_contact_required {


// test to ensure an opportunity can be added

public static testMethod void testoppyrequired0()
    {
        //create oppty 
        List<Opportunity> oppy = new List<Opportunity>();
                                    
        //add 10 opportunites without a contact, and with the condition contact required = 0
        
        for (Integer i = 0; i < 10; i++) {
            oppy.add(new Opportunity(Name='nick_test'+i,StageName='Perception Analysis',CloseDate=System.Today()));
        }
        insert oppy;
        
        map<Id, Opportunity> oppy_map = new map<Id, Opportunity>();
        
        for (Integer i = 0;i<10;++i){
            oppy_map.put(oppy[i].Id,oppy[i]);
        } //for
        
        System.assert([SELECT count() FROM Opportunity WHERE Id IN :oppy_map.keySet()] == 10);   
    } //testoppyrequired = 0
    
    
    //test to go from a not required value to a required value

public static testMethod void testoppyrequired1()
    {   
            //create oppty 
            List<Opportunity> oppy2 = new List<Opportunity>();
                                        
            //add 10 opportunites without a contact, and with the condition contact required = 0       
            for (Integer i = 0; i < 10; i++) {
                oppy2.add(new Opportunity(Name='nick_test'+i,StageName='Qualification',CloseDate=System.Today()));
            }
            
            insert oppy2;
            
            for (Integer i = 0; i < 10; i++) {
                
          	  oppy2[i].StageName='Negotiation/Review';
            
            }

			Test.startTest();

			try {
			
			    update oppy2;
			    
			    Opportunity sampleTest = [Select Id, Contact_Required__c From Opportunity where Id = :oppy2[0].id];
			    
			    System.debug('*****SAMPLE' + sampleTest);
			    
			    System.assert(false, 'This update should have failed.');
			
			} catch(System.DmlException e) {
			
			    System.assert(e.getMessage().contains('No Primary Contact Exists.'));
			
			}

    		Test.stopTest();
       
 
    } //testoppyrequired = 1



public static testMethod void testoppyrequired1woprimary()
    {   
            //create oppty 
            List<Opportunity> oppy = new List<Opportunity>();
                                        
            //add 10 opportunites 
                    
            for (Integer i = 0; i < 10; i++) {
                oppy.add(new Opportunity(Name='nick_test'+i,StageName='Qualification',CloseDate=System.Today()));
            }
            
            insert oppy;
            
            //add 10 contacts
            
            List<Contact> c = new List<Contact>();
                                        
    
            for (Integer i = 0; i < 10; i++) {
                c.add(new Contact(LastName='nick_test'+i));
            }

            insert c;

            for (Integer i = 0; i < 10; i++) {
                
            oppy[i].StageName='Negotiation/Review';
            
            }

            //add 10 opporunity contact roles associated to the opportunities and contacts above
            
            List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
            
            for (Integer i = 0; i < 10; i++) {
                ocr.add(new OpportunityContactRole(Role='Business User',OpportunityId=oppy[i].id,ContactId=c[i].id));
            }
            
            insert ocr;
            
boolean caughtException = false;


Test.startTest();

try {

    update oppy;

} catch(System.DmlException e) {

    System.assert(e.getMessage().contains('No Primary Contact Exists.'));

    caughtException = true;

}

    Test.stopTest();

    System.assert(caughtException);         
 
    } //testoppyrequired = 1


public static testMethod void testoppyrequired1primary()
    {   
            //create oppty 
            List<Opportunity> oppy = new List<Opportunity>();
                                        
            //add 10 opportunites 
                    
            for (Integer i = 0; i < 10; i++) {
                oppy.add(new Opportunity(Name='nick_test'+i,StageName='Qualification',CloseDate=System.Today()));
            }
            
            insert oppy;
            
            map<Id, Opportunity> oppy_map = new map<Id, Opportunity>();
            
            for (Integer i = 0;i<10;++i){
                oppy_map.put(oppy[i].Id,oppy[i]);
            } //for
            
            //add 10 contacts
            
            List<Contact> c = new List<Contact>();
                                        
    
            for (Integer i = 0; i < 10; i++) {
                c.add(new Contact(LastName='nick_test'+i));
            }

            insert c;

            //add 10 opporunity contact roles associated to the opportunities and contacts above
            
            List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
            
            for (Integer i = 0; i < 10; i++) {
                ocr.add(new OpportunityContactRole(Role='Business User',OpportunityId=oppy[i].id,ContactId=c[i].id,IsPrimary=True));
            }
            
            insert ocr;
            
            for (Integer i = 0; i < 10; i++) {
                
            oppy[i].StageName='Negotiation/Review';
            
            }

			try {
			
			    update oppy;
			    
			        System.assert([SELECT count() FROM Opportunity
			            WHERE Id IN :oppy_map.keySet()] == 10);
			
			} catch(System.DmlException e) {
			
			    System.assert(false);
			
			}   
 
    } //testoppyrequired = 1 and primary contact = true

} //test class





 
Hello Awesome Devs!

Recently moved to Lightning and was used to dealign with attachments, but now trying to clone a record to have its files also associated to the new cloned version of the record as well as staying associated with the initial starting record. 

I am calling the class via a process that is called when a checkbox is marked true. 

Right now the error I get is very vauge and I am not sure what I need to refactor.  Error =  An Apex error occurred: System.UnexpectedException: null

Can someone take a look at my code below and let me know how I can can applomplish this feat?...

Thank you in advance for your help!
 
public class cloneTicketWithRelated {

    @InvocableMethod
    public static void cloneRecords(List<Ticket__c> ticketIds){
      
        List<Ticket__c> ticketsToProcess = ticketIds;
 	    List<Ticket__c> cloneList = ticketsToProcess.deepClone();
        
        List<Ticket__c> clonedTickets = new List<Ticket__c>();
       
        for(Ticket__c t : cloneList){
            clonedTickets.add(t);
        }
        
        if(clonedTickets.size()>0){
            insert clonedTickets;
        }
   }    
}

 
Hello awesome Developers! 

I have the following Trigger and then Trigger Handler to pass of the processing work to the class for more efficiency than multiple triggers per object.  Now on single record inserts, updates or deletes the code works just fine and as designed.  When I use Data Loader to attempt to Bulk test more than a single record I get the following error. 

System.QueryException: List has more than 1 row for assignment to SObject
The logs show it starts from line 58 on the Trigger and calls a specific Method in the class. 

I have tested and all methods give this same error but wanted to provide as many details in order to get some great help on this one.  Can you help, and save the day!  It woudl greatly be appreciated.  

I added tons of comments to help walk through the process of what is needed, thank you so much in advance for any suggestions and or insight you may be able to give this beginner'ish developer.

Here is my trigger code:
 
trigger ContactTriggerMaster on Contact (after insert, after update, after delete, after undelete) {

    //Begin Insert Processing
    if(trigger.isAfter){
        
    	if(trigger.isInsert && !trigger.IsUpdate){
            
       		ContactHandlerMaster.afterInsert(trigger.new);
            
        //End of Insert Processing
        //Start of Update Processing
    	}else if(trigger.isUpdate && !trigger.isInsert){
            
            //Create Lists, Maps and Variables
            //List(new) and Map(old) of Contacts for Person Score Code
            List<Contact> newcons = new List<Contact>();
            Map<ID,Contact> oldCons = new Map<ID,Contact>();
            
            //List(new) and Map(old) of Contacts for Stage Progression Code 
            List<Contact> newConsStage = new List<Contact>();
            Map<ID,Contact> oldConsStage = new Map<ID,Contact>();
            
            //List(new) and Map(old) of Contacts for Meeting Set Code
           // List<Contact> newMeetDate = new List<Contact>();
           // Map<ID,Contact> oldMeetDate = new Map<ID,Contact>();
            
            //List(new) and Map(old) of Contacts for Meeting Kept Code
            //List<Contact> newMeetSet = new List<Contact>();
           // Map<ID,Contact> oldMeetSet = new Map<ID,Contact>();
            
            //Iterate over incoming Trigger Records
            for(integer i=0;i<trigger.new.size();i++){
                
                //If Person Score Has Changed on Contact add Trigger.new to List and Trigger.oldMap to Map
                if(trigger.new[i].Person_Score__c != trigger.old[i].Person_Score__c){
              		newCons.addAll(trigger.new);
                    oldCons.putAll(trigger.old);
                    
				//If Contract Stage Has Changed on Contact add Trigger.new to List and Trigger.oldMap to Map
                }else if(trigger.new[i].Contact_Status__c != trigger.old[i].Contact_Status__c){
                    newConsStage.addAll(trigger.new);
                    oldConsStage.putAll(trigger.old);
                
                //If Meeting Chedule For Date Has Changed on Contact add Trigger.new to List and Trigger.oldMap to Map
                }//else if(trigger.new[i].Meeting_Scheduled_For__c != trigger.old[i].Meeting_Scheduled_For__c){
                  //  newMeetDate.addAll(trigger.new);
                  //  oldMeetDate.putAll(trigger.old);
                    
                //If Meeting Kept Checkbox Has Changed on Contact add Trigger.new to List and Trigger.oldMap to Map
               // }else if(trigger.new[i].Meeting_Kept__c != trigger.old[i].Meeting_Kept__c){
               //     newMeetSet.addAll(trigger.new);
               //     oldMeetSet.putAll(trigger.old);
              //  }
            }
            
            //Do null checks of List and Map and then Pass the non null List and Map to Handler Class
            if(newCons!=null || oldCons!=null){
                ContactHandlerMaster.afterPersonUpdate(newCons, oldCons);
            }
            if(newConsStage!=null || oldConsStage!=null){
                ContactHandlerMaster.afterStageUpdate(newConsStage, oldConsStage);
            }
          //  if(newMeetDate!=null || oldMeetDate!=null){
           //     ContactHandlerMaster.afterMeetingUpdate(newMeetDate, oldMeetDate);
           // }
           // If(newMeetSet !=null || oldMeetSet!=null){
           //     ContactHandlerMaster.afterMeetingUpdate(newMeetSet, oldMeetSet);
           // }//End of Update Processing
            
         // Begin Delete Processing
    	}else if(trigger.isDelete){
       		ContactHandlerMaster.afterDelete(trigger.oldMap);
    	}
            
    }else if(trigger.isBefore){
        
    }
    
}

And here is my Trigger Handler Class Code:
 
public class ContactHandlerMaster {

    public static void afterInsert(List<Contact> newRecords){
     	//Start Insert Code
     	
     	//Create Set to hold Acct Ids to process
        Set<ID> acctIds = new Set<ID>();
        //Null Check for incoming list
        if(newRecords!=null){
        //Loop through the incoming list of Contacts
        for(Contact cons : newRecords){
            //Add Acct Ids to acctIds set
            acctIds.add(cons.AccountId);
        }//End of FOR Loop
        }//End of Null Check
        //Create Maps to hold Contacts and Accounts to use for Rollup of Person Score
        Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([SELECT Id ,AccountId, 
                                                                     Person_Score__c FROM Contact 
                                                                     WHERE AccountId IN :acctIds FOR UPDATE]);
		Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Account_Score__c 
                                                               FROM Account WHERE Id IN :acctIds FOR UPDATE]);
        //Loop through the Contact Children of the Accounts in acctsToUpdate Map to SUM all Person Scores into totalValue variable
        for (Account acct : acctsToUpdate.values()) {
			Decimal totalValue = 0;
				for (Contact con : contactsForAccounts.values()) {
    				if (con.AccountId == acct.Id && con.Person_Score__c != NULL) {
        				totalValue += con.Person_Score__c; 
    				}
				}//End of For Loop
        //Set the Account Score to use the value of the SUMMED Person Score in TotalValue Variable
		acct.Account_Score__c = totalValue;
		}
        //Null Check for Update DML
		if(acctsToUpdate.values().size() > 0) {
    		update acctsToUpdate.values();
		}
    }
    
    //Start Update Method
    public static void afterPersonUpdate(List<Contact> newRecords,Map<ID,Contact> oldMap){
        
        //Start Variable Collection to use for Update Methods defined below
        //List of Contacts with new version of records
        List<Contact> consRcv = newRecords;
        system.debug('consRcv Size is - '+consRcv.size()+'IDs are - '+consRcv);
        //Initite List and Map to hold new and old values of the incoming records
        List<Contact> newRecordsUpdate = new List<Contact>();
        Map<ID,Contact> oldMapUpdate = new Map<ID,Contact>();
        //Initiate Decimal variables to hold new and old Person Score Data
        Decimal NewScore;
        Decimal OldScore;
        //Null check on consRvc List
        if(consRcv!=null){ 
            system.debug('newConRecord List Size Is - '+newRecords.size());
        //Loop through the consRcv List
        for(Contact c : consRcv){
              //Add new version of record to List newRecordsUpdate
              newRecordsUpdate.add(c);
            system.debug('newConRecordsUpdate Size After ran through For Loop is - '+newRecordsUpdate.size());
              //Make NewScore variable the value of the Person Score of the incoming record
              NewScore = c.Person_Score__c;
            system.debug('NewScore is - '+NewScore);
            }
        }
        system.debug('Con Record Update List Size is - '+newRecordsUpdate.size());
        //Null check on oldMap Map
        if(oldMap.Values()!=null){
            system.debug('ConoldMap Size is - '+oldMap.Size());
        //Loop through oldMap values and add to oldMapUpdate Map as set oldScore variable to old Person Score version
        for(Contact cold : oldMap.Values()){
              oldMapUpdate.put(cold.Id,OldMap.Values());
              OldScore = cold.Person_Score__c;
        }
        }
        system.debug('ConoldMapUpdate Size is - '+oldMapUpdate.size());
        
        //Enter into Update Person Score Rollup Code
        //Checking to ensure old person score and new person score has changed
        if(NewScore != OldScore){
        //Create Set to hold Acct Ids to Process
        Set<ID> acctIds = new Set<ID>();
        //Null check on consRcv List
        if(consRcv!=null){
        //Loop through consRcv List and add Acct Ids to acctIds Set for processing
        for(Contact cons : consRcv){
            acctIds.add(cons.AccountId);
        }
        }
        //Create Maps to hold Conacts and Accounts for processing
        Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([SELECT Id ,AccountId, 
                                                                     Person_Score__c FROM Contact 
                                                                     WHERE AccountId IN :acctIds FOR UPDATE]);
		Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Account_Score__c 
                                                               FROM Account WHERE Id IN :acctIds FOR UPDATE]);
            
        //Loop through the Contact Children of the Accounts in acctsToUpdate Map to SUM all Person Scores into totalValue variable
        for (Account acct : acctsToUpdate.values()) {
			Decimal totalValue = 0;
				for (Contact con : contactsForAccounts.values()) {
    				if (con.AccountId == acct.Id && con.Person_Score__c != NULL) {
        				totalValue += con.Person_Score__c; 
    				}
				}
        //Make account score the value of thr SUMMED totalValue variable
		acct.Account_Score__c = totalValue;
		}
        //Null check on acctsToUpdate Map before attempt to update Map
		if(acctsToUpdate.values().size() > 0) {
    		update acctsToUpdate.values();
		}
        } // End of Person Score Rollup Code
    }//End of afterPersonUpdate Method
    
       //Begin Stage Progression Code
       public static void afterStageUpdate(List<Contact> newRecords,Map<ID,Contact> oldMap){
        
        //Create Lists and Variables to use for processing
        //List to Hold New Version of incoming Contacts to process
        List<Contact> consRcv = newRecords;
        system.debug('consRcv Size is - '+consRcv.size()+'IDs are - '+consRcv);
        //List and Map to hold post looped records for processing
        List<Contact> newRecordsUpdate = new List<Contact>();
        Map<ID,Contact> oldMapUpdate = new Map<ID,Contact>();
        //String Variables to hold old and new Contact Stage Values
        String NewStage;
        String OldStage;
        
        //Null check on consRcv List  
        if(consRcv!=null){ 
            system.debug('newConRecord List Size Is - '+newRecords.size());
        //Loop through consRcv List and add records to newRecordsUpdate List
        for(Contact c : consRcv){
              newRecordsUpdate.add(c);
            system.debug('newConRecordsUpdate Size After ran through For Loop is - '+newRecordsUpdate.size());
              //Set NewStage variable to the New version of the Contact Stage value
              NewStage = c.Contact_Status__c;
            system.debug('NewStage is - '+NewStage);
            }//End of For Loop
        }//End of Null Check
        system.debug('Con Record Update List Size is - '+newRecordsUpdate.size());
        
        //Null check on oldMap
        if(oldMap.Values()!=null){
            system.debug('ConoldMap Size is - '+oldMap.Size());
        //Loop through oldMap Values to add records to oldMapUpdate Map
        for(Contact cold : oldMap.Values()){
              oldMapUpdate.put(cold.Id,OldMap.Values());
              //Set OldStage to the old version of the Contact Stage value
              OldStage = cold.Contact_Status__c;
        }
        }
        system.debug('ConoldMapUpdate Size is - '+oldMapUpdate.size()); 
        //Start of Contact Stage Progression Code
        //If NewStage value does not equal to OldStage value and update happened and should continue process
        if(NewStage != OldStage){
            //Create list to hold acct Ids for processing
            List<Account> accts = new List<Account>();
            //Null check on newRecords List of incoming records
        	if(newRecords!=null){
                //Loop through newContact Incoming List and perfrom logic
        		for(Contact cons : newRecords){
                    //Contact Stage Equals Assigned Logic
                    if(cons.Contact_Status__c == 'Assigned' && cons.Account_Stage__c == 'Ready'){
                        //If True create List of Accounts that belong to Contact being processed
                    	List<Account> accounts = [SELECT ID,Account_Stage__c FROM Account WHERE ID =: cons.AccountId FOR UPDATE];
                        //Loop through list of Accounts captured and set Account Stage to Assigned and add to accts List
                        for(Account a : accounts){
                    	a.Account_Stage__c = 'Assigned';
                        accts.add(a);
                        }//Contact Stage Equals Working Logic
                    }else if(cons.Contact_Status__c == 'Working' &&
                            (cons.Account_Stage__c == 'Ready' || cons.Account_Stage__c == 'Assigned')){
                                //If True create List of Accounts that belong to Contact being processed
                                List<Account> accounts = [SELECT ID,Account_Stage__c FROM Account WHERE ID =: cons.AccountId FOR UPDATE];
                                //Loop through list of Accounts captured and set Account Stage to Working and add to accts List
                                for(Account a : accounts){
                    			a.Account_Stage__c = 'Working';
            					accts.add(a);
                                }//Contact Stage Equal to Follow Up Logic
                    }else if(cons.Contact_Status__c == 'Follow-Up' &&
                            (cons.Account_Stage__c == 'Ready' || cons.Account_Stage__c == 'Assigned' || cons.Account_Stage__c == 'Working')){
                                //If true create List of Accounts that belong to Contact being processed
                                List<Account> accounts = [SELECT ID,Account_Stage__c FROM Account WHERE ID =: cons.AccountId FOR UPDATE];
                                //Loop through list of Accounts captured and set Account Stage to Follow Up and add to accts List
                                for(Account a : accounts){
                    			a.Account_Stage__c = 'Follow Up';
            					accts.add(a);
                                }//Contact Stage Equal to Active Opportunity Logic
                    }else if(cons.Contact_Status__c == 'Active Opportunity' &&
                            (cons.Account_Stage__c == 'Ready' || cons.Account_Stage__c == 'Assigned' || 
                             cons.Account_Stage__c == 'Working' || cons.Account_Stage__c == 'Follow Up')){
                                //If true create List of Accounts that belong to Contact being processed
                                List<Account> accounts = [SELECT ID,Account_Stage__c FROM Account WHERE ID =: cons.AccountId FOR UPDATE];
                                 //Loop through list of Accounts captured and set Account Stage to Active Opportunity and add to accts List
                                 for(Account a : accounts){
                    			a.Account_Stage__c = 'Active Opportunity';
            					accts.add(a);
                                 }//Contact Stage Equal to Closed Won Logic
                    }else if(cons.Contact_Status__c == 'Closed Won' &&
                            (cons.Account_Stage__c == 'Ready' || cons.Account_Stage__c == 'Assigned' || 
                             cons.Account_Stage__c == 'Working' || cons.Account_Stage__c == 'Follow Up' ||
                             cons.Account_Stage__c == 'Active Opportunity')){
                                //If true create List of Accounts that belong to Contact being processed
                                List<Account> accounts = [SELECT ID,Account_Stage__c FROM Account WHERE ID =: cons.AccountId FOR UPDATE];
                                //Loop through list of Accounts captured and set Account Stage to Closed Won and add to accts List
                                for(Account a : accounts){
                    			a.Account_Stage__c = 'Closed Won';
            					accts.add(a);
                                }
                    }
        		}
        	}//Null check on accts List size and Do Update DML
            if(accts.size()>0){
           		update accts; 
            }
        }
    }//End of afterStageUpdate Method
    
    //Begin Meeting Scheduled For Date Being Changed Method
    /*public static void afterMeetingUpdate(List<Contact> newRecords,Map<ID,Contact> oldMap){
        
        //Create Variables to use for Processing
        //List of incoming Contacts in thier new version
        List<Contact> consRcvMeet = newRecords;
        system.debug('consRcvMeet Size is - '+consRcvMeet.size()+'IDs are - '+consRcvMeet);
        //Create List and Map to hold new version and old version of incoming records
        List<Contact> newRecordsUpdate = new List<Contact>();
        Map<ID,Contact> oldMapUpdate = new Map<ID,Contact>();
        //create variables to hold old and new versions of the Meeting Scheduled For field
        Date NewMeeting;
        Date OldMeeting;
        //create variables to hold old and new versions of the Meeting Kept Field
        Boolean NewSet;
        Boolean OldSet;
        
        //Null Check on consRcvMeet List of incoming records
        if(consRcvMeet!=null){ 
            system.debug('newConRecord List Size Is - '+newRecords.size());
        //Loop though consRcvMeet records and add to newRecordsUpdate List
        for(Contact c : consRcvMeet){
              newRecordsUpdate.add(c);
            system.debug('newConRecordsUpdate Size After ran through For Loop is - '+newRecordsUpdate.size());
              //Set NewMeeting and NewSet variables to the new versions of both
              NewMeeting = c.Meeting_Scheduled_For__c;
              NewSet = c.Meeting_Kept__c;
            system.debug('NewMeeting is - '+NewMeeting);
            }//End of For Loop
        }//End of Null Check
        system.debug('Con Record Update List Size is - '+newRecordsUpdate.size());
        
        //Null check on oldMap of old versions of incoming records
        if(oldMap.Values()!=null){
            system.debug('ConoldMap Size is - '+oldMap.Size());
        //Loop through oldMap Values to insert old version of incoming records into the oldMapUpdate Map for processing
        for(Contact cold : oldMap.Values()){
              oldMapUpdate.put(cold.Id,OldMap.Values());
              //Set OldMeeting and OldMap variables to the old versions of Meeting Scheduled For and Meetign Kept values
              OldMeeting = cold.Meeting_Scheduled_For__c;
              OldSet = cold.Meeting_Kept__c;
        }
        }
        system.debug('ConoldMapUpdate Size is - '+oldMapUpdate.size());
        
        //Check to verify new Meeting Scheduled For value is different than Old Meeting Scheduled For Value
        if(NewMeeting != OldMeeting){
            //If true create list to hold accounts to process
            List<Account> accts = new List<Account>();
            //Loop through the incoming Contact Records
            for(Contact conMeetDate : newRecords){
                Account meetDateUpdate = [SELECT ID,Meeting_Scheduled_For__c FROM Account WHERE ID =: conMeetDate.AccountId FOR UPDATE];
                meetDateUpdate.Meeting_Scheduled_For__c = conMeetDate.Meeting_Scheduled_For__c;
                accts.add(meetDateUpdate);    
            }//Update accts and perform DML
            update accts;
            //Can Now Process if Meeting Kept checkbox has changed
        }else if(NewSet != OldSet){
          //If true create List to hold Acct Ids for processing
          List<Account> accts = new List<Account>();
            //Loop through incoming Contacts to update Account and add to acct List
            for(Contact conMeetDate : newRecords){
                Account meetDateUpdate = [SELECT ID,Meeting_Kept__c FROM Account WHERE ID =: conMeetDate.AccountId FOR UPDATE];
                meetDateUpdate.Meeting_Kept__c = conMeetDate.Meeting_Kept__c;
                accts.add(meetDateUpdate);
                }//End of For Loop
            //Update accts List and perform DML
            update accts;
        }
        }*/ //ENd of Meeting Code 
 		 // End of Update Meeting Method
    
    public static void afterDelete(Map<ID,Contact> oldMap){
        //Start After Delete Code
        //Start Person Score Rollup Subtract Code
        //Create a Set to hold Acct Ids to process
        Set<ID> acctIds = new Set<ID>();
        //Null check on oldMap version of deleted record
        if(oldMap!=null){
        //Loop through incoming deleted contacts and add thier acct Ids to acctIds set
        for(Contact cons : oldMap.Values()){
            acctIds.add(cons.AccountId);
        }
        }
        //Create Maps to hold Contact and Account records for processing 
        Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([SELECT Id ,AccountId, 
                                                                     Person_Score__c FROM Contact 
                                                                     WHERE AccountId IN :acctIds FOR UPDATE]);
		Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Account_Score__c 
                                                               FROM Account WHERE Id IN :acctIds FOR UPDATE]);
        //Loop through Accts to update Map and then Contacts for Accounts Map to SUM Cons Person Score
        for (Account acct : acctsToUpdate.values()) {
			Decimal totalValue = 0;
				for (Contact con : contactsForAccounts.values()) {
    				if (con.AccountId == acct.Id && con.Person_Score__c != NULL) {
        				totalValue += con.Person_Score__c; 
    				}//End of if logic
				}//End of For Loop
        //Update accts to now have SUMMED totalValue for Total Account Score
		acct.Account_Score__c = totalValue;
		}
        //Null check on acctsToUpdate Map and if not do DML
		if(acctsToUpdate.values().size() > 0) {
    		update acctsToUpdate.values();
		}
    }
    
}

 

Hello Awesome Devs,

I am having an issue where I have a trigger that rolls up data from contacts to an account.  This was working fine with no issues until we added a managed package app that is constantly checking and cleaning records with firmographic data.  Looks liek the Batch APex job on this app runs every three minutes or so.  With that said, I am getting 3 different errors which look to be related, one for UNABLE_TO_LOCK_ROW, Record Currently Unavilable and ENTITY_FAILED_IFLASTMODIFIED_ON_UPDATE, not on every time this trigger is called, but it is happenign multiple times each day. 

I have added a catch block to attempt to retry processing the record multiple times if this error is caught, but I am unsure of how to test these catch blocks in a test class to get my code coverage up to 75% or greater. 

Can anyone please take a few and look over the followign trigger and test class that I have so far, and make any recommendations on how to test for those catch blocks?

Thank you so very much for any help you can provide,
 

Shawn


Trigger Code - 

 

trigger PersonScoreRollup on Contact (after delete, after insert, after undelete, after update) {

Contact[] cons;
if (Trigger.isDelete) 
    cons = Trigger.old;
else
    cons = Trigger.new;

Set<ID> acctIds = new Set<ID>();
for (Contact con : cons) {
   acctIds.add(con.AccountId);
}

Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([SELECT Id ,AccountId, Person_Score__c FROM Contact WHERE AccountId IN :acctIds FOR UPDATE]);

Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Account_Score__c FROM Account WHERE Id IN :acctIds FOR UPDATE]);

for (Account acct : acctsToUpdate.values()) {
Set<Id> conIds = new Set<Id>();
Decimal totalValue = 0;
for (Contact con : contactsForAccounts.values()) {
    if (con.AccountId == acct.Id && con.Person_Score__c != NULL) {
        totalValue += con.Person_Score__c; 
    }
}
acct.Account_Score__c = totalValue;
}
if(acctsToUpdate.values().size() > 0) {
    try{
     update acctsToUpdate.values();   
    }catch(Exception e1){
        if(e1.getMessage().contains('UNABLE_TO_LOCK_ROW') || e1.getMessage().contains('Record Currently Unavailable') || e1.getMessage().contains('ENTITY_FAILED_IFLASTMODIFIED_ON_UPDATE')){
            try{
                update acctsToUpdate.values();
            }catch(Exception e2){
                if(e2.getMessage().contains('UNABLE_TO_LOCK_ROW') || e1.getMessage().contains('Record Currently Unavailable') || e1.getMessage().contains('ENTITY_FAILED_IFLASTMODIFIED_ON_UPDATE')){
                    try{
                        update acctsToUpdate.values();
                    }catch(Exception e3){
                                                        
                    }
                 }
             }
         }
     }
}
}

Test Class Code -
 
@isTest
public class PersonScoreRollupTest {

    public static testmethod void tm1() {
        
        Account a1 = new Account();
        a1.Name = 'Test Account';
        a1.BillingStreet = '123 Anywhere Street';
        a1.BillingCity = 'Dallas';
        a1.BillingState = 'Texas';
        a1.BillingPostalCode = '75034';
        a1.Solution__c = 'HIPAA';
        a1.Channel__c = 'SMB';
        insert a1;
        
        
        Contact c1 = new Contact();
        c1.FirstName = 'Test';
        c1.LastName = 'tester';
        c1.AccountId = a1.Id;
        c1.Contact_Status__c = 'New';
        c1.LeadSource = 'LivePerson';
        c1.Referrer_Code__c = 'Test code';
        c1.Email = 'shawn.reichner@armor.com';
        c1.CurrencyIsoCode = 'USD';
        c1.Phone = '5709998888';
        c1.Person_Score__c = 30;
        insert c1;
        
        Contact c2 = new Contact();
        c2.FirstName = 'Test';
        c2.LastName = 'tester';
        c2.AccountId = a1.Id;
        c2.Contact_Status__c = 'New';
        c2.LeadSource = 'LivePerson';
        c2.Referrer_Code__c = 'Test code';
        c2.Email = 'shawn.reichner@armor.com';
        c2.CurrencyIsoCode = 'USD';
        c2.Phone = '5709998887';
        c2.Person_Score__c = 25;
        insert c2;
        
        
    }
    
    
}

​​​​​​​
Hello Awesome Devs!

I have the following VF Page and Controller.  The VF Page will have a dropdown of territories, and when that dropdown has a value selected, then I woudl like to render the PageBlockSections to show the correct SOQL query on Accounts to bring back the list of records from the controller.

It seems as if any choice in the dropdown calls the Else statement in my controller and always shows those records, and does not change upon selecting a new value, it always stays as the else records.  

Can anyone help me get over the finish line here on this project to conditionally render the proper set of records on the VF page Blocks based on the selection of the drop down territory list on the VF page?

Thank you so much for any help you can provide! 

Shawn

VF Page - 
<apex:page controller="ABMController" showHeader="true" >
    <apex:form id="form">
        <h1></h1><br/>
        <apex:pageMessages />
        <apex:pageBlock mode="inlineEdit" id="Block1" >
        	<apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="SAVE"/>
            </apex:pageBlockButtons>
            
            <span id="idSpan">
            <apex:pageBlockSection title="ABM Assignment Tool" columns="1" id="Details">
           		<apex:selectList value="{!TerritoryID}" size="1">
            		<apex:actionSupport event="onchange" reRender="wrapper1,wrapper2"/>
            		<apex:selectOptions value="{!schedules}"/>
        		</apex:selectList>
            </apex:pageBlockSection>
            </span>
            
            <apex:outputPanel layout="none" id="wrapper1">
            <apex:pageBlockSection title="Assigned Accounts" collapsible="false" columns="5" rendered="{!TerritoryID != null}">
            	<apex:pageBlockTable value="{!accts}" var="a" border="1">
                    <apex:column headervalue="Account Name">
                        <apex:outputLink value="/{!a.Id}">{!a.name}</apex:outputLink>
                    </apex:column>
                    <apex:column headerValue="Owner Name">
                        <apex:inputField value="{!a.ownerId}"/>
                    </apex:column>
                    <apex:column value="{!a.Armor_Territory__c}"/>
                    <apex:column value="{!a.Status__c}"/>
                    <apex:column value="{!a.Average_TAM_Score__c}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            </apex:outputPanel>
        
        
        <apex:outputPanel layout="None" id="wrapper2">
            <apex:pageBlockSection title="Un-Assigned Accounts" collapsible="false" columns="5" rendered="{!TerritoryID != null}" >
            	<apex:pageBlockTable value="{!unassigned}" var="a" border="1">
                    <apex:column headervalue="Account Name">
                        <apex:outputLink value="/{!a.Id}">{!a.name}</apex:outputLink>
                    </apex:column>
                    <apex:column headerValue="Owner Name">
                        <apex:inputField value="{!a.ownerId}"/>
                    </apex:column>
                    <apex:column value="{!a.Armor_Territory__c}"/>
                    <apex:column value="{!a.Status__c}"/>
                    <apex:column value="{!a.Average_TAM_Score__c}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            </apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller - 
 
public class ABMController {

    public SelectOption[] getSchedules() {
        return new SelectOption[] {new SelectOption('Value1', '--Select a Territory--'),
            new SelectOption('Value2', 'Northwest'), new SelectOption('Value3', 'Southwest'), new SelectOption('Value4', 'Upper South Central')};
    }
    
    public String TerritoryID {get; set;}
    public List<Account> accts {get; set;}
    public List<Account> unassigned {get; set;}
    User sapi = [SELECT Id,Name FROM User WHERE FirstName = 'SalesStaff' LIMIT 1];
    String TerrName = TerritoryID;
    
    public ABMController(){
        
        if(TerrName == 'Value2'){
            accts = new List<Account>();
            unassigned = new List<Account>();
            accts = [SELECT ID, NAME, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northwest' AND OwnerId !=: sapi.Id ORDER BY OwnerId ASC LIMIT 40];
            unassigned = [SELECT ID, NAME, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northwest' AND OwnerId =: sapi.Id AND Status__c = 'Not Active' ORDER BY Average_TAM_Score__c DESC LIMIT 10];
        } else If(TerrName == 'Value3') {
            accts = new List<Account>();
            unassigned = new List<Account>();
            accts = [SELECT ID, NAME, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southwest' AND OwnerId !=: sapi.Id ORDER BY OwnerId ASC LIMIT 40];
            unassigned = [SELECT ID, NAME, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southwest' AND OwnerId =: sapi.Id AND Status__c = 'Not Active' ORDER BY Average_TAM_Score__c DESC LIMIT 10];
        } else {
            accts = new List<Account>();
            unassigned = new List<Account>();
            accts = [SELECT ID, NAME, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper South Central' AND OwnerId !=: sapi.Id ORDER BY OwnerId ASC LIMIT 40];
            unassigned = [SELECT ID, NAME, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper South Central' AND OwnerId =: sapi.Id AND Status__c = 'Not Active' ORDER BY Average_TAM_Score__c DESC LIMIT 10];
        }
        
        
    }
    
    
    
    public PageReference showAccounts() {
        system.debug('EXECUTED');
        return null;
    }
    
    public PageReference save(){
        update accts;
        update unassigned;
        PageReference congratsPage = Page.ABMPage;
  		congratsPage.setRedirect(true);
  		return congratsPage;
        
    }

    
}

 
Hello,

Can anyone help with this issue I am seeing?  I had to reply a few times to get all of the code in the thread, so it may have seems as if someone was helping, but I have no responses and need help if anyone would be so kind! :)  Thank you all

https://developer.salesforce.com/forums/ForumsMain?id=9062I000000g3Z3QAI
Hello Devs!  I have the followign extension controller for a VF page that has multiple page blocks displaying a list of Accounts and I would like to show 10 records at a time in each page block and have pagination to move through pages 10 records at a time when more than 10 records are present.  The code below seems to work all excpet for I had to place a limit on the SOQL statements or else I got the Exceeds collection of 1000 records governer limit.  So to get around that to test other parts of the code I placed the LIMT on the SOQL's.  Now for the page blocks that have more than 10 records all of the records are shown in the page block, so all 40 are showing instead on only ten.  But the page number is correct in showing page 1 of 4, and the next and end buttons are pressable but do no actions.   What can I do to edit my code to make the needed pagination work while also not hitting the exceeds 1000 records VF limit?

Thank you all for your help! The code is large, so I will have to add as a reply to this post. 

Shawn
Hello awesome Devs!

I have the following Vf Page, Extension Controller and Test Class that I am attempting to get into Production.  The VF page and controller acts as it should and does the job awesomly, however I get the following error when attempting to run the test class....How can I get past this and resolve?

Thank you all in advance for any help you can provide,

Shawn


Extension Class -
 
public with sharing class ABMDashboardController {

    public List<Account> acc{get;set;}
    public List<Account> acc2{get;set;}
    public List<Account> acc3{get;set;}
    public List<Account> acc4{get;set;}
    public List<Account> acc5{get;set;}
    public List<Account> acc6{get;set;}
    public List<Account> acc7{get;set;}
    public List<Account> acc8{get;set;}
    public List<Account> acc9{get;set;}
    public List<Account> acc10{get;set;}
    public List<Account> acc11{get;set;}
    public List<Account> acc12{get;set;}
    public List<Account> acc13{get;set;}
    public List<Account> acc14{get;set;}
    public List<Account> acc15{get;set;}
    public List<Account> acc16{get;set;}
    public List<Account> acc17{get;set;}
    public List<Account> acc18{get;set;}
    public List<Account> acc19{get;set;}
    public List<Account> acc20{get;set;}
    public List<Account> acc21{get;set;}
    public List<Account> acc22{get;set;}
    public List<Account> acc23{get;set;}
    public List<Account> acc24{get;set;}
    public List<Account> acc25{get;set;}
    public List<Account> acc26{get;set;}
    public List<Account> acc27{get;set;}
    public List<Account> acc28{get;set;}
    public List<Account> acc29{get;set;}
    public List<Account> acc30{get;set;}
    public List<Account> acc31{get;set;}
    public List<Account> acc32{get;set;}
    public List<Account> acc33{get;set;}
    public List<Account> acc34{get;set;}
    public List<Account> acc35{get;set;}
    public List<Account> acc36{get;set;}
    public List<Account> acc37{get;set;}
    public List<Account> acc38{get;set;}
    
    public ABMDashboardController(APexPages.StandardSetController controller1)
    {
        controller1.setPageSize(40);
        acc = new List<Account>();
        acc = [SELECT Id, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northwest' AND Status__c = 'Active'];
        acc2 = new List<Account>();
        acc2 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northwest' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc3 = new List<Account>();
        acc3 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southwest' AND Status__c = 'Active'];
        acc4 = new List<Account>();
        acc4 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southwest' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc5 = new List<Account>();
        acc5 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper South Central' AND Status__c = 'Active'];
        acc6 = new List<Account>();
        acc6 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper South Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc7 = new List<Account>();
        acc7 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower South Central' AND Status__c = 'Active'];
        acc8 = new List<Account>();
        acc8 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower South Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc9 = new List<Account>();
        acc9 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper North Central' AND Status__c = 'Active'];
        acc10 = new List<Account>();
        acc10 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper North Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc11 = new List<Account>();
        acc11 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower North Central' AND Status__c = 'Active'];
        acc12 = new List<Account>();
        acc12 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower North Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc13 = new List<Account>();
        acc13 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Mid Atlantic' AND Status__c = 'Active'];
        acc14 = new List<Account>();
        acc14 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Mid Atlantic' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc15 = new List<Account>();
        acc15 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southeast' AND Status__c = 'Active'];
        acc16 = new List<Account>();
        acc16 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southeast' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc17 = new List<Account>();
        acc17 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Florida' AND Status__c = 'Active'];
        acc18 = new List<Account>();
        acc18 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Florida' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc19 = new List<Account>();
        acc19 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'NYNJ' AND Status__c = 'Active'];
        acc20 = new List<Account>();
        acc20 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'NYNJ' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc21 = new List<Account>();
        acc21 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northeast' AND Status__c = 'Active'];
        acc22 = new List<Account>();
        acc22 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northeast' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc23 = new List<Account>();
        acc23 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'MIOH' AND Status__c = 'Active'];
        acc24 = new List<Account>();
        acc24 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'MIOH' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc25 = new List<Account>();
        acc25 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'HI,AK,PR' AND Status__c = 'Active'];
        acc26 = new List<Account>();
        acc26 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'HI,AK,PR' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc27 = new List<Account>();
        acc27 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada East' AND Status__c = 'Active'];
        acc28 = new List<Account>();
        acc28 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada East' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc29 = new List<Account>();
        acc29 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada West' AND Status__c = 'Active'];
        acc30 = new List<Account>();
        acc30 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada West' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc31 = new List<Account>();
        acc31 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'APAC' AND Status__c = 'Active'];
        acc32 = new List<Account>();
        acc32 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'APAC' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc33 = new List<Account>();
        acc33 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'EMEA' AND Status__c = 'Active'];
        acc34 = new List<Account>();
        acc34 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'EMEA' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc35 = new List<Account>();
        acc35 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Latin America' AND Status__c = 'Active'];
        acc36 = new List<Account>();
        acc36 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Latin America' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc37 = new List<Account>();
        acc37 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'South America' AND Status__c = 'Active'];
        acc38 = new List<Account>();
        acc38 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'South America' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
    }
    
    public PageReference save(){
        update acc;
        return null;
    }
    
    
    
}

And finally the test class, where the error is being reported when ran...
 
@isTest(SeeAllData = True)
public class ABMDashboardControllerTest {

    
    static testMethod void tm1() {
        
        Integer Score = 50;
        
        List<Account> accts = new List<Account>();
        
        Account a1 = new Account();
        a1.Name = 'Test 1';
        a1.Armor_Territory__c = 'Northwest';
        a1.Anywhere_Score__c = Score;
        a1.Complete_Score__c = Score;
        a1.Territory_Bypass__c = True;
        accts.add(a1);
        
        Account a2 = new Account();
        a2.Name = 'Test 2';
        a2.Armor_Territory__c = 'Northwest';
        a2.Anywhere_Score__c = Score;
        a2.Complete_Score__c = Score;
        a2.Territory_Bypass__c = True;
        accts.add(a2);
        insert accts;
        
       Test.startTest();
        Test.setCurrentPage(Page.ABMDashboard);
        ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(accts);
        stdSetController.setSelected(accts);
        ABMDashboardController ext = new ABMDashboardController(stdSetController);
        ext.save();
        Test.stopTest();
    }
    
    
}

The error that is returned is as follows - 

Error: System.VisualforceException: Modified rows exist in the records collection!

Stack Trace: External entry point
Class.ABMDashboardControllerTest.tm1: line 32, column 1
Hello awesome Devs, 

I have the following scheduled class that has been running fine but all of a sudden I am now getting an Apex Time Out error when this runs each morning.  After doing some research it looks like this class although is being scheduled it is still running syncronously and hittong the goveror limits. How can I update the followign code to be both Schedulable and Batchable to try and get arounf the timing issue?

Thanks for any advise or reworkign of my code that you can help out with,


Shawn

Trigger Code:
 
global class AMPCurrentAmountBatching Implements Schedulable {

    global void execute(SchedulableContext sc){
        AMPCurrentAmountBatching();
    }
    @future
    static public void AMPCurrentAmountBatching(){
        
       List<Opportunity> opps = new List<Opportunity>();
       Set<String> mySet = new Set<String>();
       Integer recordCount = [SELECT Count() FROM Zuora__Subscription__c WHERE OpportunityId__c != null AND LastModifiedDate = LAST_N_DAYS:60];
       Integer sizeBlock = recordCount/2000 + (math.mod(recordCount,2000)!=0?1:0);
        
        For(Integer i=0;i<sizeBlock;i++){
        For(AggregateResult objar : [SELECT OpportunityId__c Oid, SUM(Total_Booking_Amount__c) Amt
                                    FROM Zuora__Subscription__c WHERE OpportunityId__c !=null AND LastModifiedDate = LAST_N_DAYS:60
                                    AND OpportunityId__c NOT IN:mySet GROUP BY OpportunityId__c LIMIT 2000])
        {
        
        Decimal d = (Decimal)objar.get('Amt');
        
            Opportunity Opp = new Opportunity();
            Opp.Id = (Id)objar.get('Oid');
            Opp.Current_Value__c = (Decimal)objar.get('Amt');
            opps.add(Opp); 
            mySet.add(Opp.Id);
        }
        }
        
        If(opps.size()>0){
           update opps;
        }
        
        
    }
    
    
}

 
Awesome Devs!

I have the followign trigger that will fire upon a lead creation to auto convert the lead.  That is working like a charm, however the issue I am running into is doing a search for an existing account to append the Contact and Opportunity to that is created via the lead conversion. 

I have some logic built in that looks like it is not working to locate an existing account based on the Lead Company field, but my code is still creating a new account each time a lead is automaticlaly converted.  

Can anyone help with getting my code to properly append the lead to the existing account if one exists, and create a new one if one is not found?

Here is the trigger code:
 
Trigger AutoConverter on Lead (after insert) {
     LeadStatus convertStatus = [
          select MasterLabel
          from LeadStatus
          where IsConverted = true
          limit 1
     ];
     List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
	 MAP<Id,Account> AccountSearch = new MAP<Id,Account>([SELECT ID, Name FROM Account]);
    
     for (Lead lead: Trigger.new) {
          if (!lead.isConverted && lead.Company != null) {
              
              If(AccountSearch.equals(Lead.Company)){
               Account Acct = AccountSearch.get(Lead.Company);
               ID AcctId = Acct.Id;
               Database.LeadConvert lc = new Database.LeadConvert();
               String oppName = lead.Company+Lead.CreatedDate;
               
               lc.setLeadId(lead.Id);
               lc.setOpportunityName(oppName);
               lc.setConvertedStatus(convertStatus.MasterLabel);
               lc.setAccountId(AcctId);
               
               leadConverts.add(lc);
              }
              Else{
                  Database.LeadConvert lc = new Database.LeadConvert();
               String oppName = lead.Name;
               
               lc.setLeadId(lead.Id);
               lc.setOpportunityName(oppName);
               lc.setConvertedStatus(convertStatus.MasterLabel);
               
               leadConverts.add(lc);
              }
          }
     }

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

 
Hello awesome Devs!

I have the following Apex class that is ran eaxch morning to perfrom an aggregate results to compile all child records that are associated with a certain opportunity and sum up thier currency values from a formula field called Total Bookings Amount.  Then the class will grab that sum and place the total summed amount into a custom field on the Opportunity called Current Value.  

The issue is if the child record is in GBP currrency the aggregate results class will treat it as USD as that is our ORG's company currency and the value is off by the conversion amount.  

So for more context:
Child Record A - Total Booking Amount = 10 USD
Chile Record B - Total Booking Amount = 14.55 USD
Total Summed amoutn for both Child Records = 24.55 USd - Converted to 18.00 GBP on record. 

When Class runs it takes the GBP total listed above converted back into USD and populates this amount on the Parent Opportunity on the Current Value field so it shows a total of 24.55 GBP (really it is the USD rate, but since the Opportunity is in GBP it shows as GBP although it is not correct), however the conversion does not happen when this Current Value is populated although the amount standard field is converted to the proper amount which shows 18.00 GBP as the Amount. 

Hope this makes sense, but ultimately I am tryign to have the class convert the summed amount before populating on the parent Opportunity if the currencyIsoCode is GBP. 

Any thoughts????

Clas Code - 
 
global class AMPCurrentAmountBatching Implements Schedulable {

    global void execute(SchedulableContext sc){
        AMPCurrentAmountBatching();
    }
    @future
    static public void AMPCurrentAmountBatching(){
        
       List<Opportunity> opps = new List<Opportunity>();       
        
        For(AggregateResult objar : [SELECT OpportunityId__c Oid, SUM(Total_Booking_Amount__c) Amt
                                    FROM Zuora__Subscription__c WHERE OpportunityId__c !=null AND LastModifiedDate = LAST_N_DAYS:60
                                    GROUP BY OpportunityId__c])
        {
        
        Decimal d = (Decimal)objar.get('Amt');
        
            Opportunity Opp = new Opportunity();
            Opp.Id = (Id)objar.get('Oid');
            Opp.Current_Value__c = (Decimal)objar.get('Amt');
            opps.add(Opp); 
        }
        
        If(opps.size()>0){
           update opps;
        }
        
        
    }
    
    
}

 
Hello awesome devs! 

I have the following class which I woudl like to batch on in a nightly running batch.  This class is to Aggregate some subscription records and group by a String field which will contain the 18 digit ID number from an Opportunity record that the subscriptions make up.  I am then summing the total amoutn from those subscriptions in the aggregate results method so I am left with an amouny for each grouping of subscriptions grouped by the ID number.  

I then want to use that SUM amount to update a field on the Opportunity that is related to the group of subscriptions.  What is happening with my code below is when I run the class, all subscriptions are being summed for every opportunity.  Meaning any opportunity I go to now has the same SUM value which is the value of all Subscriptions in our database with an Opp ID populated and it seems like it is not grouping. 

What did I do wrong, or what should I try as I am stumped.....

Thank you in advance for any help you can provide,

Shawn
 
global class AMPCurrentAmountBatching Implements Schedulable {

    global void execute(SchedulableContext sc){
        AMPCurrentAmountBatching();
    }
    
    public void AMPCurrentAmountBatching(){
        
       List<Opportunity> opps = new List<Opportunity>();
        
       Id idOpp;
       Decimal amt;
       Set<ID> setIdOpp = new Set<ID>();
       Map<Id,Opportunity> mapOpp = new Map<Id,Opportunity>();
       List<AggregateResult> AR = new List<AggregateResult>();
       
        
        For(AggregateResult objar : [SELECT OpportunityId__c, SUM(Total_Booking_Amount__c)
                                    FROM Zuora__Subscription__c WHERE OpportunityId__c !=null
                                    GROUP BY ROLLUP(OpportunityId__c)])
        {
            AR.add(objar);
            setIdOpp.add((ID)objar.get('OpportunityId__c'));  
        }
        
        If(!setIdOpp.isEmpty()){
           // mapOpp = new Map<Id,Opportunity>([SELECT ID, Current_Value__c FROM Opportunity WHERE Id IN: setIdOpp]);
           opps = [SELECT ID, Current_Value__c FROM Opportunity WHERE Id IN: setIdOpp];
        }
        
        For(AggregateResult objar : AR){
            idOpp = (Id)objar.get('OpportunityId__c');
            amt = (Double)objar.get('expr0');
          
        }
        If(opps.size()>0){
        For(Opportunity o : opps){
            o.Current_Value__c = amt;
        }
        }
        
        update opps;
        
    }
    
    
}

 
Hello,

I have the following schedulable class that I want to set up to run on the last day of every month to update a currency field to match another currency field on the same object.  This is done to be able to track monthly reductions and or growth to the currency field being targeted in a report. 

However when I run this class in any sandbox it works just fine, but now when I deployed to production i get the System,LimitExecption: Apex CPU time limt exceeded error for line 13 of my class. 

Any idea why this woudl trigger this error and any ideas on how to resolve?

Thank you so much in advance fo rany help you can provide!

Class code:
 
global class NightlyStartingCMRRUpdate Implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        UpdateStartingCMRR();
    }
      
    public void UpdateStartingCMRR()
    {
        List<Zuora__CustomerAccount__c> updates = new List<Zuora__CustomerAccount__c>();
        
        For(Zuora__CustomerAccount__c CA : [SELECT ID, Zuora__MRR__c, Starting_CMRR__c FROM Zuora__CustomerAccount__c WHERE Zuora__MRR__c != null]){
                CA.Starting_CMRR__c = CA.Zuora__MRR__c;
                updates.add(CA);
        }
        
        If(updates.size()>0){
            update updates;
        }
        
    }
}

 
Hello Devs,

I have the followign code that is using the Aggregate Results method to batch up records to create one Opportunity record for each Account and Status of the record being Aggregated.  My question is I now have a need to take each one of the records that is being Aggregated and create a record for each of the Aggregated records in a new custom object.  I have th eobject and needed fields created but I am unsure how to use those records that are being aggregated to create a record in the custom object for each aggregated record, I can only get the aggregated results to create one record, btu again I need a record create din the new custom object for each of the records being used in the aggregate result and not the aggregated result itself.  

Can anyone help me understand how to tap into those records being aggregated before the aggregate for loop to achieve this need? 

Thank you so much for any help you can provide,

Shawn

Apex Class code: 
 
global class CreateUpgradeDowngradeOpportunities Implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        CreateOpportunities();
    }
      
    public void CreateOpportunities()
    {
        //Variable & List Declarations
        
        Date Today = Date.Today();
        Date d1 = Today.addDays(-1);
        List<Opportunity> lstOpp = new List<Opportunity>();
        Opportunity objOpp;
        Id idRecTypeDowngrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Downgrade').getRecordTypeId();
        Id idRecTypeUpgrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Upgrade').getRecordTypeId();
        User FH = [Select ID FROM User WHERE FirstName = 'Firehost' LIMIT 1];
        User API = [Select ID FROM User WHERE Alias = 'api' LIMIT 1];
        Map<Id, Account> mapAcc = new Map<Id, Account>();
        Id idAcc;
        String strStatus;
        String pline;
        Decimal amt;
        Set<Id> setIdAcc = new Set<Id>();
        List<AggregateResult> lstAR = new List<AggregateResult>();
        String ZID;
        
        // collect sum by account and status and product line
        for(AggregateResult objAR : [SELECT Zuora__Account__c , Zuora__Status__c,Product_Line__c, SUM(Total_Booking_Amount__c) 
                                    FROM Zuora__Subscription__c 
                                    WHERE Zuora__Status__c IN ('Cancelled', 'Active')
                                        AND Zuora__Account__c != NULL
                                        AND ((Zuora__ServiceActivationDate__c = YESTERDAY AND OpportunityId__c = null AND (Migrated__c = 'False' OR Migrated__c = null)) OR Zuora__TermEndDate__c = YESTERDAY)
                                       // AND Migrated__c = 'False'
                                     AND SameDayDeactivation__c = False
                                     AND isAcctDiscount__c = False
                                    GROUP BY ROLLUP(Zuora__Account__c, Zuora__Status__c, Product_Line__c)])
        {
            lstAR.add(objAR);
            setIdAcc.add((Id)objAR.get('Zuora__Account__c'));
        } // End of Aggregate For Loop
        
        // collect account infos
        if(!setIdAcc.isEmpty())
        {
            mapAcc = new Map<Id, Account>([SELECT Id, Name, OwnerId, Service_Lead__c FROM Account WHERE Id IN: setIdAcc]);   
        }
        
        // create opps
        for(AggregateResult objAR : lstAR)
        {
            idAcc = (Id)objAR.get('Zuora__Account__c');
            strStatus = (String)objAR.get('Zuora__Status__c');
            amt = (Double)objAR.get('expr0');
            pline = (String)objAR.get('Product_Line__c');
            
            if(strStatus == 'Cancelled' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Complete')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeDowngrade;
                objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Downgrade';
                objOpp.Amount = amt * -1;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Cancelled';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'COMPLETE';
                objOpp.Armor_Anywhere_Location__c = 'None';
               // objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);
                
            }
            else if(strStatus == 'Cancelled' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Anywhere')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeDowngrade;
                objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Non Opportunity';
                objOpp.Amount = amt * -1;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Cancelled';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'CORE';
                objOpp.Armor_Anywhere_Location__c = 'Other';
                objOpp.Armor_Anywhere_Other_Location__c = 'Other';
               // objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);    
            } 
            else if(strStatus == 'Cancelled' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Complete')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeDowngrade;
                objOpp.OwnerId = FH.Id;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Downgrade';
                objOpp.Amount = amt * -1;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Cancelled';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'COMPLETE';
                objOpp.Armor_Anywhere_Location__c = 'None';
               // objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);    
            }
            else if(strStatus == 'Cancelled' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Anywhere')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeDowngrade;
                objOpp.OwnerId = FH.Id;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Non Opportunity';
                objOpp.Amount = amt * -1;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Cancelled';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'CORE';
                objOpp.Armor_Anywhere_Location__c = 'Other';
                objOpp.Armor_Anywhere_Other_Location__c = 'Other';
               // objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);    
            }
            
            else if(strStatus == 'Active' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Complete')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeUpgrade;
                objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Existing Business';
                objOpp.Amount = amt;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Closed Won';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'COMPLETE';
                objOpp.Armor_Anywhere_Location__c = 'None';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
               // objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);
            }
            
            else if(strStatus == 'Active' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Anywhere')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeUpgrade;
                objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Non Opportunity';
                objOpp.Amount = amt;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Closed Won';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'CORE';
                objOpp.Armor_Anywhere_Location__c = 'Other';
                objOpp.Armor_Anywhere_Other_Location__c = 'Other';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
               // objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);
            }
            else if(strStatus == 'Active' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Complete')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeUpgrade;
                objOpp.OwnerId = FH.Id;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Existing Business';
                objOpp.Amount = amt;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Closed Won';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'COMPLETE';
                objOpp.Armor_Anywhere_Location__c = 'None';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
              //  objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);
            }
            
            else if(strStatus == 'Active' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c) && pline == 'Anywhere')
            {
                objOpp = new Opportunity();
                objOpp.RecordTypeId = idRecTypeUpgrade;
                objOpp.OwnerId = FH.Id;
                objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
                objOpp.AccountId = mapAcc.get(idAcc).Id;
                objOpp.Opportunity_Source__c = 'Portal';
                objOpp.Type = 'Non Opportunity';
                objOpp.Amount = amt;
                objOpp.CloseDate = d1;
                objOpp.StageName = 'Closed Won';
                objOpp.Armor_Product_Category__c = 'Armor | '+pline;
                objOpp.Armor_Product__c = 'CORE';
                objOpp.Armor_Anywhere_Location__c = 'Other';
                objOpp.Armor_Anywhere_Other_Location__c = 'Other';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
              //  objOpp.ZuoraId__c = ZID;
                objOpp.Solution__c = 'General Security';
                objOpp.Auto_Bookings__c = true;
                objOpp.CreatedById = API.Id;
                lstOpp.add(objOpp);
            }
        } // END of FOR Loop

        if(!lstOpp.isEmpty())
        {
            insert lstOpp;
        }
    } // End of CreateOpportunities Method 
} // End of Class

 
Hello Awesome Devs,

I have the followign Trigger that has ben working without error, but now that I have an need to update all of our Account records in our Org, I am hitting SOQL 101 errors a plenty.  Anyone have any thoughts on how to bulkify this code even more to stop these errors? 

Thank you for any help you are able to provide.....

Shawn

Trigger code - 
trigger SetAccountActiveOnContactRecord on Account (after insert, after update) {

    
    List<Contact> consToUpdate = new List<Contact>();
    set<id> accIds = new set<id>();
    For(Account a : Trigger.new){
        If(a.Status__c == 'Active'){
           accIds.add(a.id);
        }
    }
  
   List<Contact> consToAdd = [SELECT ID, Account_Active__c, AMP_Notification_Types__c, Contact_Types__c FROM Contact WHERE AccountId = : accIds  AND Account_Active__c != True AND 
                                       (AMP_Notification_Types__c INCLUDES('Technical','Billing','Account') OR Contact_Types__c INCLUDES('Technical'))];
            
            If(consToAdd.size()>0){
            For(Contact c : consToAdd){
                
                c.Account_Active__c = True;
                consToUpdate.add(c);
            
            }
            }
    
    if(consToUpdate.size()>0){
        update consToUpdate;
    }
    
    
}

 
Hello Devs, I have the following Trigger and Class that was working fine until this morning when I received the following error of Too Many future calls: 51. 

Any idea how to alleviate gettign this error?  Here is my trigger and class code....thank you all for any help you can provide....

Trigger:
 
trigger DeleteExtraBookingsTrigger on Opportunity (after insert) {

    For(Opportunity opps : Trigger.new){
        If(opps.Auto_Bookings__c == True){
            
            
        DeleteExtraBookingsClass.deleteRecords(Trigger.newMap.keySet());    
            
        }
    }
    
    
}

Class code:
 
public class DeleteExtraBookingsClass {

    @future
    public static void deleteRecords(Set<ID> oppIdsToDelete){
        List<Opportunity> opp = [SELECT ID, Armor_Product_Category__c From Opportunity WHERE ID IN : oppIdsToDelete AND Auto_Bookings__c = True
                                AND (Armor_Product_Category__c = null or Armor_Product_Category__c = 'Armor | null')];
        
        If(opp.size()>0){
        delete opp;
        database.emptyRecycleBin(opp);
        }
    }
    
}

Hello awesome devs! 

Need some help here as I am at a loss why the following Trigger is not setting values on all records but it setting a value on some of the records when doing a mass insert r or update.  When you go to a single record and perform an update the trigger always fires correctly.  

What is trying to be achieved:  

When a record on Object A is created or updated and it includes a SKU in a field called SKU__c .
Then trigger is called on Object A to find a Product from our standard Product2 object that have the same value in the ProductCode field as the SKU__c fiel don Object A.  
When found, a field (Product_Line__c) on Object A should be populated with the value form the found Product2 record and its Product_Line__c field. 

Again this works when updating records one by one, but anythign in mass, will only update a few records.  (Latest example: out of 1097 records in a mass update, only roughly 40 records got updated, the rest have nothign populated in the Product_Line__c field on Object A.

Can anyone look over my code, and help me out? :)

Thank you so much all,

Shawn

Trigger Code:
 
trigger PopulateProductLineOnCharge on Zuora__SubscriptionProductCharge__c (before insert, before update) {

    
    List<Zuora__SubscriptionProductCharge__c> spcToUpdate = new List<Zuora__SubscriptionProductCharge__c>();
    String pLineText = '';
    String SkuText = '';
    Product2 P;
    
    
    For(Zuora__SubscriptionProductCharge__c s : Trigger.new){
        If(s.Product_Line__c == null && s.SKU__c != null){
            SkuText = s.SKU__c;
        }
    }
    
    If(SkuText != null){
    P = [SELECT Id, Product_Line__c, ProductCode FROM Product2 WHERE ProductCode = : SkuText LIMIT 1];
    
    For(Zuora__SubscriptionProductCharge__c s2 : Trigger.New){
        If(SkuText.contains(s2.SKU__c)){
            s2.Product_Line__c = p.Product_Line__c;
            spcToUpdate.add(s2);
        }
        }
    }
 
}

 
Hello awesome devs! 

I have the followign trigger which works as intended, however when I do a mass upload or mass edit on more than 10 Lead records, I always get the "Apex CPU Time Limit Exceeded" error.  Can anyone tell me how to resolve this error in my code as if my users do a mass update of more than 10 lead records to assume ownership it throws this error and any other time an insert or update of more than 10 Lead records at a time. 

Thanks so much for any help you can provide,

Shawn

Trigger code:
 
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(ts.WhoId!=null && ts.whatId == null)
    {
        If(string.valueOf(ts.WhoId).startsWith('00Q'))
        {
        lid.add(ts.Whoid);
    }
    }
    }
    If(lid.size()>0){
    Map <id,Task > tmap = new Map <id, Task>([select id, Whoid from Task where Whoid in:lid]);
    Map <id, Lead> lmap = new Map <id, Lead>([select id,Count_Activity__c from lead where id in:lid ]);
    
        If(lmap.size()>0){
       List<Lead> llist = [SELECT Id, Count_Activity__c FROM Lead WHERE ID IN:lmap.values()]; 
    for(lead l : lmap.values())
    {
        set<id> tids = new set <id>();
        for(Task tt : tmap.values())
        {
           if(tt.WhoId== l.Id)
            tids.add(tt.id);
        }
        if(l.Count_Activity__c!=tids.size())
        l.Count_Activity__c=tids.size();
        
              tlist = [select id, Whoid from task where whoid in:lid ];
        for(lead le :llist)
        {
            for(Task te:tlist)
            {
                if(tlist.size()>0)
                le.Count_Activity__c = tlist.size();
            }
        }
        
        
    }
    If(lmap.size()>0){
    update lmap.values();
    }
    }
    }
    }
}

 
Hello awesome devs!

I am attempting to create a VF page with 4 fields for user inputting.  2 of these fields are Date fields which when filled in like MM/DD/YYY when I press the search button to call my custom controller the date in the field populated has its format changed to Tue Dec 26 00:00:00 GMT 2017 and doesnt seem to be being applied in the search itself as all records are returned and not ones just for the date entered. 

Can someone help me with gettign the format to stay as I think this is the cause of the date field not being used in the search criteria. 

Please see my VF Page and controller code below. 

Thank you very much for any help you can provide,

Shawn

VF Page Code - 
 
<apex:page controller="SubSearchController">
    
    <apex:form>
    	<apex:pageBlock id="pb">
        	<apex:pageBlockButtons>
                <apex:commandButton action="{!searchRecords}" value="Search" rerender="pb"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="2">
                <apex:outputLabel value="Account Id" />
                <apex:inputText value="{!AccId}"/>
                <apex:outputLabel value="Status" />
                <apex:inputText value="{!SubStatus}"/>
                <apex:outputLabel value="Service Activation date" />
                <apex:inputText value="{!SAD}"/>
                <apex:outputLabel value="Term End Date" />
                <apex:inputText value="{!TermEnd}"/>
            </apex:pageBlockSection>
            <apex:pageBlockTable var="record" value="{!records}" id="pbTable">
                <apex:column value="{!record.Name}" />
                <apex:column value="{!record.Zuora__Status__c}" />
                <apex:column value="{!record.Zuora__ServiceActivationDate__c}" />
                <apex:column value="{!record.Zuora__TermEndDate__c}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
    
</apex:page>

Controller Code -

public class SubSearchController {

    public String AccId {get;set;}
    public String SubStatus {get;set;}
    public Date SAD {get;set;}
    public Date sadDate = Date.valueOf(SAD);
    public Date TermEnd {get;set;}
    public Date TermDate = Date.valueOf(TermEnd);
    
    public List<Zuora__Subscription__c> records {get; private set;}
    
    public SubSearchController(){
        records = new List<Zuora__Subscription__c>();   
    }
    
    public PageReference searchRecords() {
        
        records = [SELECT Zuora__Account__c, Zuora__Status__c, Zuora__ServiceActivationDate__c, Zuora__TermEndDate__c, OpportunityId__c, Total_Booking_Amount__c, Id, Name
                  FROM Zuora__Subscription__c WHERE Zuora__Account__c = : AccId AND Zuora__Status__c = : SubStatus AND (Zuora__ServiceActivationDate__c = : sadDate OR Zuora__TermEndDate__c = :TermDate)];
        return null;
        
    }
    
}

 
Hello awesome developers...I am not sure why I am gettign SOQL 101 Errors on the following trigger.  

Can anyone give some advice on what to try to ensure we are not gettign this error. 

What I am tring to do is if an account goes to an active state after an update, it should go and grab all contacts that meet some criteria and update a field on all of the contact records. 

Any help would be greatly appreciated...

Thanks in advance,

Shawn

Trigger code - 
 
trigger SetAccountActiveOnContactRecord on Account (after insert, after update) {

    
    List<Contact> consToUpdate = new List<Contact>();
    
    For(Account a : Trigger.new){
        If(a.Status__c == 'Active'){
            List<Contact> consToAdd = [SELECT ID, Account_Active__c, AMP_Notification_Types__c, Contact_Types__c FROM Contact WHERE AccountId = : a.Id AND Account_Active__c != True AND 
                                       (AMP_Notification_Types__c INCLUDES('Technical','Billing','Account') OR Contact_Types__c INCLUDES('Technical')) LIMIT 100];
            
            If(consToAdd.size()>0){
            For(Contact c : consToAdd){
                
                c.Account_Active__c = True;
                consToUpdate.add(c);
            
            }
            }
        }
    }
    
    if(consToUpdate.size()>0){
        update consToUpdate;
    }
    
    
}

 
Hello Awesome Devs!!!

I have the following Scheduled Class, and test class, and I am only able to get the code coverage on this class to 70 percent.  Looks like the issue is in my IF , ELSE IF statements, as the Null check always tests out, but if I am stating that the field is not null/blank then the code aftere that doe snot get covered.  

Can anyone help me figure out what is going on here and help to get this above the acceptable coverage limit?

Appreciate any help you can provide,

Shawn

Class - 
 
global class CreateUpgradeDowngradeOpportunities Implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        CreateOpportunities();
    }
      
    public void CreateOpportunities()
    {
        //Variable & List Declarations
        
        Date Today = Date.Today();
        Date d1 = Today.addDays(-1);
		List<Opportunity> lstOpp = new List<Opportunity>();
		Opportunity objOpp;
		Id idRecTypeDowngrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Downgrade').getRecordTypeId();
		Id idRecTypeUpgrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Upgrade').getRecordTypeId();
        User FH = [Select ID FROM User WHERE FirstName = 'Firehost' LIMIT 1];
		Map<Id, Account> mapAcc = new Map<Id, Account>();
		Id idAcc;
		String strStatus;
		Decimal amt;
		Set<Id> setIdAcc = new Set<Id>();
		List<AggregateResult> lstAR = new List<AggregateResult>();
		
		// collect sum by account
		for(AggregateResult objAR : [SELECT Zuora__Account__c , Zuora__Status__c, SUM(Zuora__MRR__C) 
									FROM Zuora__Subscription__c 
									WHERE Zuora__Status__c IN ('Cancelled', 'Active')
										AND Zuora__Account__c != NULL
										AND (Zuora__TermStartDate__c = YESTERDAY OR Zuora__TermEndDate__c = YESTERDAY)
                                     // Add additional Criteria here..
									GROUP BY ROLLUP(Zuora__Account__c, Zuora__Status__c)])
		{
			lstAR.add(objAR);
			setIdAcc.add((Id)objAR.get('Zuora__Account__c'));
		} // End of Aggregate For Loop
		
		// collect account infos
		if(!setIdAcc.isEmpty())
		{
			mapAcc = new Map<Id, Account>([SELECT Id, Name, OwnerId, Service_Lead__c FROM Account WHERE Id IN: setIdAcc]);   
		}
		
		// create opps
		for(AggregateResult objAR : lstAR)
		{
			idAcc = (Id)objAR.get('Zuora__Account__c');
			strStatus = (String)objAR.get('Zuora__Status__c');
			amt = (Decimal)objAR.get('expr0');
            
			if(strStatus == 'Cancelled' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeDowngrade;
				objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Downgrade';
				objOpp.Amount = amt * -1;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Cancelled';    
				lstOpp.add(objOpp);    
			}
            else if(strStatus == 'Cancelled' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeDowngrade;
				objOpp.OwnerId = FH.Id;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Downgrade';
				objOpp.Amount = amt * -1;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Cancelled';    
				lstOpp.add(objOpp);    
			}
			else if(strStatus == 'Active' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeUpgrade;
				objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Existing Business';
				objOpp.Amount = amt;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Closed Won';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
				lstOpp.add(objOpp);
			}
            else if(strStatus == 'Active' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeUpgrade;
				objOpp.OwnerId = FH.Id;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Existing Business';
				objOpp.Amount = amt;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Closed Won';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
				lstOpp.add(objOpp);
			}
		} // END of FOR Loop

		if(!lstOpp.isEmpty())
		{
			insert lstOpp;
		}
    } // End of CreateOpportunities Method 
} // End of Class

Test Class -
 
@isTest(SeeAllData = True)
public class CreateUpgradeDowngradeOpportunitiesTest {

    List<Zuora__Subscription__c> subs = new List<Zuora__Subscription__c>();
    
    
    private static testMethod void tm1(){
        
    	Date Today = Date.Today();
    	Date d1 = Today.addDays(-1);
        User u = [SELECT ID FROM USER WHERE FirstName = 'FireHost' LIMIT 1];
        
        Account a = New Account();
        a.Name = 'Test Account';
        a.Status__c = 'Active';
        insert a;
        
        Account a2 = New Account();
        a2.Name = 'Test Account 2';
        a.Status__c = 'Active';
        a.Service_Lead__c = u.Id;
        insert a2;
        
        Zuora__Subscription__c s = new Zuora__Subscription__c();
        s.Zuora__Account__c = a.Id;
        s.Zuora__Status__c = 'Active';
        s.Zuora__MRR__c = 100;
        s.Zuora__TermStartDate__c = d1;
        insert s;
        
        Zuora__Subscription__c s2 = new Zuora__Subscription__c();
        s2.Zuora__Account__c = a.Id;
        s2.Zuora__Status__c = 'Cancelled';
        s2.Zuora__MRR__c = 100;
        s2.Zuora__TermStartDate__c = d1;
        insert s2;
        
        Zuora__Subscription__c s3 = new Zuora__Subscription__c();
        s3.Zuora__Account__c = a2.Id;
        s3.Zuora__Status__c = 'Active';
        s3.Zuora__MRR__c = 100;
        s3.Zuora__TermStartDate__c = d1;
        insert s3;
        
        Zuora__Subscription__c s4 = new Zuora__Subscription__c();
        s4.Zuora__Account__c = a2.Id;
        s4.Zuora__Status__c = 'Cancelled';
        s4.Zuora__MRR__c = 100;
        s4.Zuora__TermStartDate__c = d1;
        insert s4;


        String CRON_EXP = '0 0 0 15 3 ? *';
        

		String jobId = System.schedule('ScheduleApexClassTest',  CRON_EXP, new CreateUpgradeDowngradeOpportunities());
		CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
		System.assertEquals(CRON_EXP, ct.CronExpression);
		System.assertEquals(0, ct.TimesTriggered);

    }
    
}

Hello Awesome Devs,

I am having an issue where I have a trigger that rolls up data from contacts to an account.  This was working fine with no issues until we added a managed package app that is constantly checking and cleaning records with firmographic data.  Looks liek the Batch APex job on this app runs every three minutes or so.  With that said, I am getting 3 different errors which look to be related, one for UNABLE_TO_LOCK_ROW, Record Currently Unavilable and ENTITY_FAILED_IFLASTMODIFIED_ON_UPDATE, not on every time this trigger is called, but it is happenign multiple times each day. 

I have added a catch block to attempt to retry processing the record multiple times if this error is caught, but I am unsure of how to test these catch blocks in a test class to get my code coverage up to 75% or greater. 

Can anyone please take a few and look over the followign trigger and test class that I have so far, and make any recommendations on how to test for those catch blocks?

Thank you so very much for any help you can provide,
 

Shawn


Trigger Code - 

 

trigger PersonScoreRollup on Contact (after delete, after insert, after undelete, after update) {

Contact[] cons;
if (Trigger.isDelete) 
    cons = Trigger.old;
else
    cons = Trigger.new;

Set<ID> acctIds = new Set<ID>();
for (Contact con : cons) {
   acctIds.add(con.AccountId);
}

Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([SELECT Id ,AccountId, Person_Score__c FROM Contact WHERE AccountId IN :acctIds FOR UPDATE]);

Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Account_Score__c FROM Account WHERE Id IN :acctIds FOR UPDATE]);

for (Account acct : acctsToUpdate.values()) {
Set<Id> conIds = new Set<Id>();
Decimal totalValue = 0;
for (Contact con : contactsForAccounts.values()) {
    if (con.AccountId == acct.Id && con.Person_Score__c != NULL) {
        totalValue += con.Person_Score__c; 
    }
}
acct.Account_Score__c = totalValue;
}
if(acctsToUpdate.values().size() > 0) {
    try{
     update acctsToUpdate.values();   
    }catch(Exception e1){
        if(e1.getMessage().contains('UNABLE_TO_LOCK_ROW') || e1.getMessage().contains('Record Currently Unavailable') || e1.getMessage().contains('ENTITY_FAILED_IFLASTMODIFIED_ON_UPDATE')){
            try{
                update acctsToUpdate.values();
            }catch(Exception e2){
                if(e2.getMessage().contains('UNABLE_TO_LOCK_ROW') || e1.getMessage().contains('Record Currently Unavailable') || e1.getMessage().contains('ENTITY_FAILED_IFLASTMODIFIED_ON_UPDATE')){
                    try{
                        update acctsToUpdate.values();
                    }catch(Exception e3){
                                                        
                    }
                 }
             }
         }
     }
}
}

Test Class Code -
 
@isTest
public class PersonScoreRollupTest {

    public static testmethod void tm1() {
        
        Account a1 = new Account();
        a1.Name = 'Test Account';
        a1.BillingStreet = '123 Anywhere Street';
        a1.BillingCity = 'Dallas';
        a1.BillingState = 'Texas';
        a1.BillingPostalCode = '75034';
        a1.Solution__c = 'HIPAA';
        a1.Channel__c = 'SMB';
        insert a1;
        
        
        Contact c1 = new Contact();
        c1.FirstName = 'Test';
        c1.LastName = 'tester';
        c1.AccountId = a1.Id;
        c1.Contact_Status__c = 'New';
        c1.LeadSource = 'LivePerson';
        c1.Referrer_Code__c = 'Test code';
        c1.Email = 'shawn.reichner@armor.com';
        c1.CurrencyIsoCode = 'USD';
        c1.Phone = '5709998888';
        c1.Person_Score__c = 30;
        insert c1;
        
        Contact c2 = new Contact();
        c2.FirstName = 'Test';
        c2.LastName = 'tester';
        c2.AccountId = a1.Id;
        c2.Contact_Status__c = 'New';
        c2.LeadSource = 'LivePerson';
        c2.Referrer_Code__c = 'Test code';
        c2.Email = 'shawn.reichner@armor.com';
        c2.CurrencyIsoCode = 'USD';
        c2.Phone = '5709998887';
        c2.Person_Score__c = 25;
        insert c2;
        
        
    }
    
    
}

​​​​​​​
Hello Devs!  I have the followign extension controller for a VF page that has multiple page blocks displaying a list of Accounts and I would like to show 10 records at a time in each page block and have pagination to move through pages 10 records at a time when more than 10 records are present.  The code below seems to work all excpet for I had to place a limit on the SOQL statements or else I got the Exceeds collection of 1000 records governer limit.  So to get around that to test other parts of the code I placed the LIMT on the SOQL's.  Now for the page blocks that have more than 10 records all of the records are shown in the page block, so all 40 are showing instead on only ten.  But the page number is correct in showing page 1 of 4, and the next and end buttons are pressable but do no actions.   What can I do to edit my code to make the needed pagination work while also not hitting the exceeds 1000 records VF limit?

Thank you all for your help! The code is large, so I will have to add as a reply to this post. 

Shawn
Hello awesome Devs!

I have the following Vf Page, Extension Controller and Test Class that I am attempting to get into Production.  The VF page and controller acts as it should and does the job awesomly, however I get the following error when attempting to run the test class....How can I get past this and resolve?

Thank you all in advance for any help you can provide,

Shawn


Extension Class -
 
public with sharing class ABMDashboardController {

    public List<Account> acc{get;set;}
    public List<Account> acc2{get;set;}
    public List<Account> acc3{get;set;}
    public List<Account> acc4{get;set;}
    public List<Account> acc5{get;set;}
    public List<Account> acc6{get;set;}
    public List<Account> acc7{get;set;}
    public List<Account> acc8{get;set;}
    public List<Account> acc9{get;set;}
    public List<Account> acc10{get;set;}
    public List<Account> acc11{get;set;}
    public List<Account> acc12{get;set;}
    public List<Account> acc13{get;set;}
    public List<Account> acc14{get;set;}
    public List<Account> acc15{get;set;}
    public List<Account> acc16{get;set;}
    public List<Account> acc17{get;set;}
    public List<Account> acc18{get;set;}
    public List<Account> acc19{get;set;}
    public List<Account> acc20{get;set;}
    public List<Account> acc21{get;set;}
    public List<Account> acc22{get;set;}
    public List<Account> acc23{get;set;}
    public List<Account> acc24{get;set;}
    public List<Account> acc25{get;set;}
    public List<Account> acc26{get;set;}
    public List<Account> acc27{get;set;}
    public List<Account> acc28{get;set;}
    public List<Account> acc29{get;set;}
    public List<Account> acc30{get;set;}
    public List<Account> acc31{get;set;}
    public List<Account> acc32{get;set;}
    public List<Account> acc33{get;set;}
    public List<Account> acc34{get;set;}
    public List<Account> acc35{get;set;}
    public List<Account> acc36{get;set;}
    public List<Account> acc37{get;set;}
    public List<Account> acc38{get;set;}
    
    public ABMDashboardController(APexPages.StandardSetController controller1)
    {
        controller1.setPageSize(40);
        acc = new List<Account>();
        acc = [SELECT Id, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northwest' AND Status__c = 'Active'];
        acc2 = new List<Account>();
        acc2 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northwest' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc3 = new List<Account>();
        acc3 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southwest' AND Status__c = 'Active'];
        acc4 = new List<Account>();
        acc4 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southwest' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc5 = new List<Account>();
        acc5 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper South Central' AND Status__c = 'Active'];
        acc6 = new List<Account>();
        acc6 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper South Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc7 = new List<Account>();
        acc7 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower South Central' AND Status__c = 'Active'];
        acc8 = new List<Account>();
        acc8 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower South Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc9 = new List<Account>();
        acc9 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper North Central' AND Status__c = 'Active'];
        acc10 = new List<Account>();
        acc10 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Upper North Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc11 = new List<Account>();
        acc11 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower North Central' AND Status__c = 'Active'];
        acc12 = new List<Account>();
        acc12 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Lower North Central' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc13 = new List<Account>();
        acc13 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Mid Atlantic' AND Status__c = 'Active'];
        acc14 = new List<Account>();
        acc14 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Mid Atlantic' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc15 = new List<Account>();
        acc15 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southeast' AND Status__c = 'Active'];
        acc16 = new List<Account>();
        acc16 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Southeast' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc17 = new List<Account>();
        acc17 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Florida' AND Status__c = 'Active'];
        acc18 = new List<Account>();
        acc18 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Florida' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc19 = new List<Account>();
        acc19 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'NYNJ' AND Status__c = 'Active'];
        acc20 = new List<Account>();
        acc20 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'NYNJ' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc21 = new List<Account>();
        acc21 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northeast' AND Status__c = 'Active'];
        acc22 = new List<Account>();
        acc22 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Northeast' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc23 = new List<Account>();
        acc23 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'MIOH' AND Status__c = 'Active'];
        acc24 = new List<Account>();
        acc24 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'MIOH' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc25 = new List<Account>();
        acc25 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'HI,AK,PR' AND Status__c = 'Active'];
        acc26 = new List<Account>();
        acc26 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'HI,AK,PR' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc27 = new List<Account>();
        acc27 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada East' AND Status__c = 'Active'];
        acc28 = new List<Account>();
        acc28 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada East' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc29 = new List<Account>();
        acc29 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada West' AND Status__c = 'Active'];
        acc30 = new List<Account>();
        acc30 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Canada West' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc31 = new List<Account>();
        acc31 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'APAC' AND Status__c = 'Active'];
        acc32 = new List<Account>();
        acc32 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'APAC' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc33 = new List<Account>();
        acc33 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'EMEA' AND Status__c = 'Active'];
        acc34 = new List<Account>();
        acc34 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'EMEA' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc35 = new List<Account>();
        acc35 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Latin America' AND Status__c = 'Active'];
        acc36 = new List<Account>();
        acc36 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'Latin America' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
        acc37 = new List<Account>();
        acc37 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'South America' AND Status__c = 'Active'];
        acc38 = new List<Account>();
        acc38 = [SELECT ID, Name, OwnerId, Armor_Territory__c, Status__c,Average_TAM_Score__c FROM Account WHERE Armor_Territory__c = 'South America' AND Status__c != 'Active' ORDER BY Average_TAM_Score__c DESC];
    }
    
    public PageReference save(){
        update acc;
        return null;
    }
    
    
    
}

And finally the test class, where the error is being reported when ran...
 
@isTest(SeeAllData = True)
public class ABMDashboardControllerTest {

    
    static testMethod void tm1() {
        
        Integer Score = 50;
        
        List<Account> accts = new List<Account>();
        
        Account a1 = new Account();
        a1.Name = 'Test 1';
        a1.Armor_Territory__c = 'Northwest';
        a1.Anywhere_Score__c = Score;
        a1.Complete_Score__c = Score;
        a1.Territory_Bypass__c = True;
        accts.add(a1);
        
        Account a2 = new Account();
        a2.Name = 'Test 2';
        a2.Armor_Territory__c = 'Northwest';
        a2.Anywhere_Score__c = Score;
        a2.Complete_Score__c = Score;
        a2.Territory_Bypass__c = True;
        accts.add(a2);
        insert accts;
        
       Test.startTest();
        Test.setCurrentPage(Page.ABMDashboard);
        ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(accts);
        stdSetController.setSelected(accts);
        ABMDashboardController ext = new ABMDashboardController(stdSetController);
        ext.save();
        Test.stopTest();
    }
    
    
}

The error that is returned is as follows - 

Error: System.VisualforceException: Modified rows exist in the records collection!

Stack Trace: External entry point
Class.ABMDashboardControllerTest.tm1: line 32, column 1
I want to restrict sales users from accepting new leads under they ownership when there are old leads in a queue

How can this be done? Please, help!
Hello awesome Devs, 

I have the following scheduled class that has been running fine but all of a sudden I am now getting an Apex Time Out error when this runs each morning.  After doing some research it looks like this class although is being scheduled it is still running syncronously and hittong the goveror limits. How can I update the followign code to be both Schedulable and Batchable to try and get arounf the timing issue?

Thanks for any advise or reworkign of my code that you can help out with,


Shawn

Trigger Code:
 
global class AMPCurrentAmountBatching Implements Schedulable {

    global void execute(SchedulableContext sc){
        AMPCurrentAmountBatching();
    }
    @future
    static public void AMPCurrentAmountBatching(){
        
       List<Opportunity> opps = new List<Opportunity>();
       Set<String> mySet = new Set<String>();
       Integer recordCount = [SELECT Count() FROM Zuora__Subscription__c WHERE OpportunityId__c != null AND LastModifiedDate = LAST_N_DAYS:60];
       Integer sizeBlock = recordCount/2000 + (math.mod(recordCount,2000)!=0?1:0);
        
        For(Integer i=0;i<sizeBlock;i++){
        For(AggregateResult objar : [SELECT OpportunityId__c Oid, SUM(Total_Booking_Amount__c) Amt
                                    FROM Zuora__Subscription__c WHERE OpportunityId__c !=null AND LastModifiedDate = LAST_N_DAYS:60
                                    AND OpportunityId__c NOT IN:mySet GROUP BY OpportunityId__c LIMIT 2000])
        {
        
        Decimal d = (Decimal)objar.get('Amt');
        
            Opportunity Opp = new Opportunity();
            Opp.Id = (Id)objar.get('Oid');
            Opp.Current_Value__c = (Decimal)objar.get('Amt');
            opps.add(Opp); 
            mySet.add(Opp.Id);
        }
        }
        
        If(opps.size()>0){
           update opps;
        }
        
        
    }
    
    
}

 
Awesome Devs!

I have the followign trigger that will fire upon a lead creation to auto convert the lead.  That is working like a charm, however the issue I am running into is doing a search for an existing account to append the Contact and Opportunity to that is created via the lead conversion. 

I have some logic built in that looks like it is not working to locate an existing account based on the Lead Company field, but my code is still creating a new account each time a lead is automaticlaly converted.  

Can anyone help with getting my code to properly append the lead to the existing account if one exists, and create a new one if one is not found?

Here is the trigger code:
 
Trigger AutoConverter on Lead (after insert) {
     LeadStatus convertStatus = [
          select MasterLabel
          from LeadStatus
          where IsConverted = true
          limit 1
     ];
     List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
	 MAP<Id,Account> AccountSearch = new MAP<Id,Account>([SELECT ID, Name FROM Account]);
    
     for (Lead lead: Trigger.new) {
          if (!lead.isConverted && lead.Company != null) {
              
              If(AccountSearch.equals(Lead.Company)){
               Account Acct = AccountSearch.get(Lead.Company);
               ID AcctId = Acct.Id;
               Database.LeadConvert lc = new Database.LeadConvert();
               String oppName = lead.Company+Lead.CreatedDate;
               
               lc.setLeadId(lead.Id);
               lc.setOpportunityName(oppName);
               lc.setConvertedStatus(convertStatus.MasterLabel);
               lc.setAccountId(AcctId);
               
               leadConverts.add(lc);
              }
              Else{
                  Database.LeadConvert lc = new Database.LeadConvert();
               String oppName = lead.Name;
               
               lc.setLeadId(lead.Id);
               lc.setOpportunityName(oppName);
               lc.setConvertedStatus(convertStatus.MasterLabel);
               
               leadConverts.add(lc);
              }
          }
     }

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

 
I have one checkbox field on account object and I want to create workflow rule where every time that checkbox values go from True to False then it will update one field which is date data type with on which date that checkbox goes from true to false and I do not want to update that date field when record is created it only fired when checkbox goes from true to false