• Cola
  • NEWBIE
  • 60 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 19
    Replies
Hi,
I have created two Apex scheduler classes in Sandbox that run daily and update a field on contracts and tasks, respectively. These schedulers then trigger the respective Apex triggers. The trigger work in both Sandbox and Production. The scheduler classes work in Sandbox but not in production. I am not sure why this happens. Any suggestions? 
  • December 11, 2014
  • Like
  • 0

Hi, 

I've created a scheduled Apex class shown below: 

global class scheduleContractTriggers implements Schedulable {
    global void execute(SchedulableContext SC) {
        List <Contract> contracts = [SELECT OwnerId, Last_Scheduled_Run__c FROM Contract];         
        
        for(Contract c : contracts){
            if(c.OwnerId != null)
                c.Last_Scheduled_Run__c = Date.today();
        }
        update(contracts);
    }
}
That updates all Contracts and sets a custom field, Last Scheduled Run, to today's date. This scheduled class then triggers an "after update" trigger on Contracts seen below: 
trigger cloneExpiringContract on Contract (after insert, after update) { 
    List<Contract> contractsToClone = [SELECT Id, Status, Auto_Renew__c, EndDate FROM Contract];
    
    List<Contract> newContracts = new list<Contract>(); 
    
    for (Contract c : Trigger.new) {
        if ((c.Auto_Renew__c == TRUE) && (c.EndDate == Date.today())){ 
            Contract clonedContract = new Contract();
            //Contract Details
            clonedContract.Owner = c.Owner; 
            clonedContract.AccountID = c.AccountID;
            clonedContract.Opportunity_Name__c = c.Opportunity_Name__c;
            clonedContract.Status = 'Draft'; //have to save it as a draft first 
            clonedContract.Contract_Type__c = c.Contract_Type__c; 
            clonedContract.Co_Marketing_Opportunities__c = c.Co_Marketing_Opportunities__c; 
            clonedContract.Previous_Contract__c = c.Id; 
           	Date newStartDate = c.EndDate.addDays(1);
            clonedContract.StartDate = newStartDate;
            clonedContract.ContractTerm = c.ContractTerm;
            clonedContract.Auto_Renew__c = TRUE;
            
            //License Agreement
            clonedContract.MonthtoMonth__c = c.MonthtoMonth__c; 
            clonedContract.Comments_NDA__c = c.Comments_NDA__c; 
            
            //NDAs
            clonedContract.Type_Mutual_One_Side__c = c.Type_Mutual_One_Side__c;
            clonedContract.Duration__c = c.Duration__c;
            
            //Signature Information
            clonedContract.CustomerSigned = c.CustomerSigned; 
            clonedContract.CustomerSignedDate = c.CustomerSignedDate; 
            clonedContract.CustomerSignedTitle = c.CustomerSignedTitle;
            clonedContract.CompanySigned = c.CompanySigned;
            clonedContract.CompanySignedDate = c.CompanySignedDate;
            
            newContracts.add(clonedContract);
        }
    }
insert newContracts;
}
In Sandbox, the scheduled class was successfully updating the "Last Scheduled Run" field and firing the trigger when applicable. However, when I schedule the class in Production, although it says the scheduled run has succeeded, the "Last Scheduled Run" field is no longer getting populated and therefore the trigger is never fired. 

Any suggestions on why this would be or how to fix this are much appreciated. 
  • November 24, 2014
  • Like
  • 0
I'm wondering if there is anyway to create something like a "roll up summary" for attachments on a Contract? More specifically, I want to be able to verify that there is at least 1 attachment on the Contract when the Contract is activated. 

Any advice is appreciated. 
  • October 22, 2014
  • Like
  • 0
I currently have a trigger "UpdateInTouchLead" shown below: 
trigger UpdateInTouchLead on Task (after insert, after update) {
Set<String> whoIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whoIds.add(t.WhoId);
	}
	
   	List<Lead> leads = [SELECT Id, First_in_touch__c FROM Lead WHERE Id =: whoIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhoId, t);
    		}
    	}
	}
         
    for (Lead l : leads) {
  		if (taskMap.containsKey(l.Id)) {
  			System.debug('Activity Date: ' + taskMap.get(l.Id).ActivityDate); 
  			System.debug('First In Touch before: ' + l.First_in_touch__c); 
  			l.First_in_touch__c = taskMap.get(l.Id).ActivityDate;
  			System.debug('First In Touch after: ' + l.First_in_touch__c); 
			l.Status = 'In Touch';
			l.POC_Communications__c = 'Muted'; 
   		}
	}
	update leads;
}
This trigger runs whenever a Task in inserted or updated, but I would like to have this trigger also run once a day (at midnight). I have tried creating a scheduled class but I am receiving the folowing error:  "Invalid Type: UpdateInTouchLead". 

The schedulable class is shown below: 
global class scheduledUpdateInTouchLead implements Schedulable {
global static void scheduleMe()
  {
    scheduledUpdateInTouchLead msc = new scheduledUpdateInTouchLead();
    String sch = '0 00 00 * * ?'; // everyday at midnight
    String jobID = System.schedule('Scheduled Job', sch, msc);

  }

  global void execute(SchedulableContext sc)
  {
	UpdateInTouchLead u = new UpdateInTouchLead();
  }
}
Any advice on how to fix this is appreciated. 
  • October 22, 2014
  • Like
  • 0
Hi Guys,

We are going to be switching our contracts in SFDC to be auto-renewing, so every year, right before the contract expires, we want to auto-generate an identical contract with all the same info but updated start and end dates. I'm assuming this is possible via a trigger?

Thanks!
  • October 06, 2014
  • Like
  • 0

Hi, 

I'm trying to create a trigger that checks a lead's email domain when it is created. If this email domain matches an exisiting account domain, then the lead owner gets set to that corresponding account owner. However, I am getting the following error: 

Apex trigger AssignNewLeadToAccount caused an unexpected exception, contact your administrator: AssignNewLeadToAccount: execution of BeforeInsert caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: Trigger.AssignNewLeadToAccount: line 21, column 1

Here is the trigger code: 

trigger AssignNewLeadToAccount on Lead (before insert)  {

	public list<Lead> LeadsToUpdate = new List<Lead>();

	Map<string,Id> DomainAccountMap = new Map<string,Id>();
    
    for (Account a :[SELECT ownerID, Email_domain__c FROM Account WHERE Email_domain__c != null]) {
		DomainAccountMap.put(a.email_domain__c, a.ownerId);
    }

    for(Lead l : Trigger.new) {
        ID owner = DomainAccountMap.get(l.Email_domain__c);
        if(owner != null) { 
            Lead lead = new Lead(Id=l.Id, OwnerID = owner); 
            LeadsToUpdate.add(lead);
            l.Skip_Lead_Assignment__c = true; 
        }  
    }
    
    if(LeadsToUpdate.size() > 0){
        update LeadsToUpdate;
    }
}
Any help is appreciated. Cheers
  • October 01, 2014
  • Like
  • 0
Hi,

I currently have a trigger that checks if a new lead has the same email domain as an existing account. If it does, then the lead owner is assigned to the account owner. I have tested the trigger by itself and it seems to work as required. Here is the trigger for reference: 

trigger AssignNewLeadToAccount on Lead (after insert)  {

	public list<Lead> LeadsToUpdate = new List<Lead>();

	Map<string,Id> DomainAccountMap = new Map<string,Id>();
    for (Account a :[SELECT ownerID, Email_domain__c FROM Account WHERE Email_domain__c != null]) {
		DomainAccountMap.put(a.email_domain__c, a.ownerId);
    }

    for(integer i=0; i < trigger.new.size();i++) {
        ID owner = DomainAccountMap.get(trigger.new[i].Email_domain__c);
        if(owner != null) {
            LeadsToUpdate.add(new Lead(Id=trigger.new[i].Id, Ownerid = owner));
        }  
    }
    
    if(leadstoupdate.size() > 0){
        update LeadsToUpdate;
    }
}

However, I have existing lead assignment rules that seem to be overriding this trigger. What is the easiest way to have the trigger take priority over the lead assignment rule when the lead email domain is equal to an existing account email domain? 
  • September 22, 2014
  • Like
  • 0
Hi, 

I'm trying to create a trigger that updates a contact's related opportunity location fields (City, State/Province, Country) based on the contact's location fields. This should only udpate the opportunity's location fields when the fields are previously blank. The code I have so far is below, but it doesn't seem to be working. 

trigger updateOppLocation on Contact (after insert) {
    
    List<OpportunityContactRole> contactRoles = [SELECT OpportunityId,ContactId
                                                 FROM OpportunityContactRole
                                                 WHERE ContactId IN : Trigger.new];
    
    if(contactRoles.size()>0) {
        Map<Id,Id> conOpp_map = new Map<Id,Id>();
        
        for(OpportunityContactRole cr : contactRoles) {
            conOpp_map.put(cr.ContactId,cr.OpportunityId);
        }
        
        List<Opportunity> opp_list = new List<Opportunity>([SELECT Id 
                                                       FROM Opportunity
                                                       WHERE Id IN : conOpp_map.values()]);
        
        for(Contact c : Trigger.new) {
            if(conOpp_map.containsKey(c.Id)) {
                for (Opportunity o : opp_list) {
                    if (o.City__c == null && o.State_Province__c == null && o.Country__c == null) {
                    	o.City__c = c.MailingCity;
                    	o.State_Province__c = c.MailingState;
                        o.Country__c = c.MailingCountry; 
                    }
                }
            }
        } 
   	update opp_list;
    } 
}

Any advice on how to get this to work is appreciated. 
  • September 10, 2014
  • Like
  • 0
Hi,

I'm trying to create a trigger that runs when a contact is created and updates the related Opportunity's location (City__c, State_Province__c, Country__c) (if the Opportunity's location is not populated yet) based on the contact's location. I have the following code but am getting errors: 

trigger updateOppLocation on Contact (after insert) {
    
    List<OpportunityContactRole> contactRoles = [SELECT OpportunityId,ContactId
                                                 FROM OpportunityContactRole
                                                 WHERE ContactId IN : Trigger.new];
    
    if(contactRoles.size()>0) {
        Map<Id,Id> conOpp_map = new Map<Id,Id>();
        
        for(OpportunityContactRole cr : contactRoles) {
            conOpp_map.put(cr.ContactId,cr.OpportunityId);
        }
        
        Map<Id,Opportunity> opp_map = new Map<ID,Opportunity>([SELECT Id 
                                                       FROM Opportunity
                                                       WHERE Id IN : conOpp_map.values()]);
        
        for(Contact c : Trigger.new) {
            if(conOpp_map.containsKey(c.Id)) {
                for (Opportunity o : opp_map) {
                   if (o.City__c == null && o.State_Province__c == null && o.Country__c == null) {
                      o.City__c = c.MailingCity;
                      o.State_Province__c = c.MailingState;
                      o.Country__c = c.MailingCountry;
                }
            }
        }
   	update opp_map;
    } 
}
The error I am receiving is: 
Loop must iterate over a collection type: MAP<Id,Opportunity>;

I am not sure if this is the best way to go about doing this, any help is appreciated. 
  • September 08, 2014
  • Like
  • 0
Hi,

I'm trying to build a workflow rule on an Account level that runs whenever a Account field goes from being checked (1) to unchecked (0). When this happens I want to check another Account field and then 90 days later uncheck that same field.

All the formulas I've tried to use so far can only work with the evaluation criteria is set to "created, and every time it’s edited", which unfortunately does not allow time-dependant workflow actions.

Is there any workaround for this?
  • August 13, 2014
  • Like
  • 0
Hi, 
I have developed and tested the following trigger in sandbox and am trying to deploy it live. 

trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    
    boolean isCustomer = false; 
	List<Account> acctToUpdate = new List<Account>();
    List<Opportunity> opps = new List<Opportunity>(); 
    
	Set<Id> associatedAccId = new Set<Id>() ;
    for (Opportunity opp : Trigger.new) {
        if (!(associatedAccId.contains(opp.AccountId))) { 
            associatedAccId.add(opp.AccountId) ;
        }
    }
	
	opps = [SELECT Id, AccountId, Probability, Account.Type FROM Opportunity WHERE AccountId IN : associatedAccId];
    
	for (Opportunity opp : opps) {
            if (opp.Probability == 100) {   
				opp.Account.Type  = 'Customer';
                isCustomer = true; 
			}
           else if (!(isCustomer)) {
                opp.Account.Type = 'Prospect';
			}
        if (acctToUpdate.isEmpty()) {
        	acctToUpdate.add(opp.Account);
        }
    }
    update acctToUpdate;
}

However, I am unable to get the test class working. This is what I have so far but there is an error when I try inserting the opportunity.

Error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Please make sure an opportunity product is added before switching the opportunity to a closed

@isTest
public class TestUpdateAccountIfOpp {
    static testMethod void testUpdateAccount() {
        Account a = new Account(Name='testAccount', 
                                Email_Domain__c='test', 
                                Company_Short__c='tst', 
                                Product__c='Semantria', 
                                Industry='Other', 
                                Type='Prospect');
        insert a; 
        
        Product2 prod = new Product2(Name = 'Laptop X200', 
                                     Family = 'Hardware');
        insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry(
            Pricebook2Id = pricebookId, Product2Id = prod.Id,
            UnitPrice = 10000, IsActive = true);
        insert standardPrice;
        
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        PricebookEntry customPrice = new PricebookEntry(
            Pricebook2Id = customPB.Id, Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert customPrice;
        
        
        Opportunity opp = new Opportunity(Name='Test', 
                                          Account = a, 
                                          Product__c='Semantria',
                                          NextStep='test',
                                          Marketing_Channel__c='Email',
                                          PriceBook2 = customPB,
                                          Product2 = prod,
                                          City__c='test', 
                                          State_Province__c='test', 
                                          CloseDate = System.today(),
                                          Country__c='test', 
                                          AccountId=a.Id, 
                                          StageName='Closed Won - One Time', 
                                          Probability=100);
       
       insert opp; 
        
       System.assertEquals('Customer', a.Type);
    }
}
Any suggestions on how to fix this are much appreciated! 

  • August 12, 2014
  • Like
  • 0

I'm currently trying to create a trigger that runs whenever an Opportunity is created or updated. The trigger needs to check all the other Opportunities related to the Account of the Opportunity being updated. It should check to see if any of the Opportunities have a StageName equal to 'Closed Won - One Time' or 'Closed Won - Recurring' and if so, it should update the account Type to 'Customer'. If none of the Opportunities are closed won, the Account Type should be 'Prospect'.

This is the code I have but I'm not sure if I'm querying the right things: 

trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    List<Account> accts = new List<Account>();
    List<Opportunity> opps = new List<Opportunity>(); 
    
    for (Opportunity opp : Trigger.new) {
        accts = [SELECT Id, Name, Type FROM Account WHERE Id =: opp.AccountId LIMIT 1]; 
        opps = [SELECT Id, AccountId, StageName, Account.Type FROM Opportunity WHERE AccountId =: opp.AccountId];
    }

    for (Account a : accts) {
        for (Opportunity o : opps) {
            if (o.StageName == 'Closed Won - One Time' || o.StageName == 'Closed Won - Recurring' || o.StageName == 'Customer Reseller') {
                if (a == null) {
                    a = new Account(Id = o.AccountId, name='TestingName');
                }
                a.Type = 'Customer'; 
            } else {
                a.Type = 'Prospect';
            }
        }
    }
    update accts;
}
Any help is much appreciated.

Cheers
  • August 12, 2014
  • Like
  • 0
I'm currently trying to create a trigger that runs whenever an Opportunity is created or updated. The trigger needs to check all the other Opportunities related to the Account of the Opportunity being updated. It should check to see if any of the Opportunities have a StageName equal to 'Closed Won - One Time' or 'Closed Won - Recurring' and if so, it should update the account Type to 'Customer'. If none of the Opportunities are closed won, the Account Type should be 'Prospect'. 

This is the code I currently have but it doesn't seem to work. I'm not exactly sure how to check all the related opportunitites. 

trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    Map<Id, Account> accounts = new Map<Id, Account>();
    for (Opportunity opp : Trigger.new) {
        Account a = accounts.get(opp.AccountId);
        if (opp.StageName == 'Closed Won - One Time' || opp.StageName == 'Closed Won - Recurring') {
            if (a == null) {
                a = new Account(Id = opp.AccountId);
                accounts.put(opp.AccountId, a);
            }
            a.Type = 'Customer'; 
        } else {
            a.Type = 'Prospect';
        }
    }
    if (!accounts.isEmpty()) {
        update accounts.values();
    }
}

Any suggestions are appreciated! 
  • August 08, 2014
  • Like
  • 0
I'm trying to deploy a workflow rule with a change set from my Sandbox to Production and I get the following error:

Code Coverage Failure
Your organization's code coverage is 74%. You need at least 75% coverage to complete this deployment.

I checked around online and found that people recommended running all tests in Developer Console in my production environment to see which test class is failing and when I do that I see that the overall code coverage is 75%.

Any idea on what I can do to have to deployment succeed?

Thanks,
Marc
  • August 06, 2014
  • Like
  • 0
I've created a trigger on a Task to update a custom Opportunity field (Last_Contact_Date__c). The field gets updated based on the most recent task Activity Date. The trigger is seen below and works as desired: 
trigger UpdateOppLastContactDate on Task (after insert, after update) {
  
  Set<String> whatIDs = new Set<String>();
  
    for (Task t : Trigger.new) {
      whatIDs.add(t.whatID);
  }
  
     List<Opportunity> opps = [SELECT Id, Last_Contact_Date__c FROM Opportunity WHERE Id =: whatIDs];
    
     Map<String, Task> taskMap = new Map<String, Task>();
  
    for (Task t : Trigger.new){
      if (!(t.Type.equals('Eloqua Activity'))) {
        if (t.Status.equals('Completed')) {
          taskMap.put(t.whatID, t);
        }
      }
      
  }
         
    for (Opportunity o : opps) {
      if (taskMap.containsKey(o.Id)) {
        o.Last_Contact_Date__c = taskMap.get(o.Id).ActivityDate;
      }
  }
  update opps;
}

However, then I tried to modify this trigger to also update a custom Accounts variable (In_Touch_Date__c) but I cannot get it to function properly. 

Here is the modified code: 

trigger UpdateOppLastContactDate on Task (after insert, after update) {
	
	Set<String> whatIDs = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whatIDs.add(t.whatID);
	}
	
   	List<Opportunity> opps = [SELECT Id, Last_Contact_Date__c FROM Opportunity WHERE Id =: whatIDs];
   	
   	Map<Id, Account> accts = new Map<Id, Account>();
   	   
   	Map<String, Task> taskMap = new Map<String, Task>();

    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.whatID, t);
    		}
    	}
  		
	}
    
    for (Opportunity o : opps) {
  		if (taskMap.containsKey(o.Id)) {
    		o.Last_Contact_Date__c = taskMap.get(o.Id).ActivityDate;
    		Account a = accts.get(o.AccountId);
    		if (a.In_Touch_Date__c != null) {
    			if (taskMap.get(o.Id).ActivityDate.daysBetween(a.In_Touch_Date__c) < 0) {
    				a.In_Touch_Date__c = taskMap.get(o.Id).ActivityDate;
    			}
    		}
  		}
	}
	update opps;
}
I've bolded the updated code, any advice on why this doesn't work is much apprecaited. 
  • July 28, 2014
  • Like
  • 0

I've created a trigger on a task to udpate a custom Account field (In_Touch_Date__c). Although the trigger compiles, it does not seem to be working properly. What I am trying to do is have the Account In_Touch_Date__c field update to the most recent Activity Date of the Account. I have successfully created similar triggers on the Contact and Opportunity levels. 

Here is the current trigger code:

trigger UpdateInTouchAccount on Task (after insert, after update) {
	Set<String> whatIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whatIds.add(t.WhatId);
	}
	
   	List<Account> acct = [SELECT Id, In_Touch_Date__c FROM Account WHERE Id =: whatIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhatId, t);
    		}
    	}	
	}
         
    for (Account a : acct) {
  		if (taskMap.containsKey(a.Id)) {
    		a.In_Touch_Date__c = taskMap.get(a.Id).ActivityDate;
  		}
	}
	update acct;
}

 

  • July 23, 2014
  • Like
  • 0
I'm trying to create a trigger that will update a custom Account field called "In Touch Date" based on the Activity History of the account. I want the "In Touch Date" to always be the most recent date any contact in that account has been in touch. I was able to sucessfully create this trigger on a Contact level so that a Contact field also called "In Touch Date" will update based on the most recent Activity Date (code seen below). I am trying to figure out the easiest way to replicate this trigger on an Account level.

The working trigger on the Contact level is here: 
trigger UpdateInTouchDate on Task (after insert, after update) {
	Set<String> whoIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whoIds.add(t.WhoId);
	}
	
   	List<Contact> cons = [SELECT Id, In_Touch_Date__c FROM Contact WHERE Id =: whoIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhoId, t);
    		}
    	}
  		
	}
         
    for (Contact c : cons) {
  		if (taskMap.containsKey(c.Id)) {
    		c.In_Touch_Date__c = taskMap.get(c.Id).ActivityDate;
    		c.POC_Communications__c = 'Muted';
  		}
	}
	update cons;

}

Any suggestions on how to replicate this on an Account level would be much appreciated.
  • July 22, 2014
  • Like
  • 0
We created two triggers (one for leads and one for contacts) that populate a lead/contact field with the date of a task that is associated with that lead/contact. The trigger works just fine with contacts, however with leads we have the following issue:

Task is created with an ActivityDate of 5/20/2014 and the trigger sets the date on the lead level as TODAY (ex. 5/30/2014).

This is the code (bold part is where the error is occuring):

trigger UpdateInTouchLead on Task (after insert, after update) {
Set<String> whoIds = new Set<String>();

    for (Task t : Trigger.new) {
    whoIds.add(t.WhoId);
}

    List<Lead> leads = [SELECT Id, First_in_touch__c FROM Lead WHERE Id =: whoIds];
   
    Map<String, Task> taskMap = new Map<String, Task>();

    for (Task t : Trigger.new){
     if (!(t.Type.equals('Eloqua Activity'))) {
      if (t.Status.equals('Completed')) {
       taskMap.put(t.WhoId, t);
      }
     }
}
        
    for (Lead l : leads) {
    if (taskMap.containsKey(l.Id)) {
      l.First_in_touch__c = taskMap.get(l.Id).ActivityDate;
   l.Status = 'In Touch';
   l.POC_Communications__c = 'Muted';
    }
}
update leads;

}


Any idea on why this isn't working as desired?
  • May 30, 2014
  • Like
  • 0
Hi, I've created a trigger on a task that I want to use to update a custom contact field. I found documentation on how to create the trigger (http://salesforce.stackexchange.com/questions/23055/trigger-to-update-custom-field-from-another-custom-field-on-a-separate-object). However, When I run the test class I get an Assertion Failed Error: System.AssertException: Assertion Failed: Expected: 2014-05-29 00:00:00, Actual:
null
.

I am unsure of where my error lies and hoping someone can help.

Trigger Code:

trigger UpdateInTouchDate on Task (after insert, after update) {
Set<String> whoIds = new Set<String>();

    for (Task t : Trigger.new) {
         whoIds.add(t.WhoId);
    }

    List<Contact> cons = [SELECT Id, In_Touch_Date__c FROM Contact WHERE Id =: whoIds];
   
    Map<String, Task> taskMap = new Map<String, Task>();

    for (Task t : Trigger.new){
        taskMap.put(t.WhoId, t);
    }
        
    for (Contact c : cons) {
    if (taskMap.containsKey(c.Id)) {
         c.In_Touch_Date__c = taskMap.get(c.Id).ActivityDate;
    }
}
update cons;


Trigger Test Class: 

@isTest
private class TestUpdateTouchDate {

static testMethod void testUpdateInTouch() {
 
  Contact c = new Contact(FirstName = 'Test', LastName = 'Test');
  insert c;
 
  Date d = Date.newInstance(2014, 5, 29);
  Task t = new Task(ActivityDate = d);
  System.debug('Date before updating in touch date: ' + t.ActivityDate );
  insert t;
 
  List<Task> task = [SELECT ActivityDate FROM Task WHERE Id =:t.Id];
 
  if (task.size() > 0) {
       t = task.get(0);
  }
 
      System.debug('Price after trigger fired: ' + t.ActivityDate);
 
     System.assertEquals(t.ActivityDate, c.In_Touch_Date__c); 
   }
}

  • May 29, 2014
  • Like
  • 0

Hi, 

I've created a scheduled Apex class shown below: 

global class scheduleContractTriggers implements Schedulable {
    global void execute(SchedulableContext SC) {
        List <Contract> contracts = [SELECT OwnerId, Last_Scheduled_Run__c FROM Contract];         
        
        for(Contract c : contracts){
            if(c.OwnerId != null)
                c.Last_Scheduled_Run__c = Date.today();
        }
        update(contracts);
    }
}
That updates all Contracts and sets a custom field, Last Scheduled Run, to today's date. This scheduled class then triggers an "after update" trigger on Contracts seen below: 
trigger cloneExpiringContract on Contract (after insert, after update) { 
    List<Contract> contractsToClone = [SELECT Id, Status, Auto_Renew__c, EndDate FROM Contract];
    
    List<Contract> newContracts = new list<Contract>(); 
    
    for (Contract c : Trigger.new) {
        if ((c.Auto_Renew__c == TRUE) && (c.EndDate == Date.today())){ 
            Contract clonedContract = new Contract();
            //Contract Details
            clonedContract.Owner = c.Owner; 
            clonedContract.AccountID = c.AccountID;
            clonedContract.Opportunity_Name__c = c.Opportunity_Name__c;
            clonedContract.Status = 'Draft'; //have to save it as a draft first 
            clonedContract.Contract_Type__c = c.Contract_Type__c; 
            clonedContract.Co_Marketing_Opportunities__c = c.Co_Marketing_Opportunities__c; 
            clonedContract.Previous_Contract__c = c.Id; 
           	Date newStartDate = c.EndDate.addDays(1);
            clonedContract.StartDate = newStartDate;
            clonedContract.ContractTerm = c.ContractTerm;
            clonedContract.Auto_Renew__c = TRUE;
            
            //License Agreement
            clonedContract.MonthtoMonth__c = c.MonthtoMonth__c; 
            clonedContract.Comments_NDA__c = c.Comments_NDA__c; 
            
            //NDAs
            clonedContract.Type_Mutual_One_Side__c = c.Type_Mutual_One_Side__c;
            clonedContract.Duration__c = c.Duration__c;
            
            //Signature Information
            clonedContract.CustomerSigned = c.CustomerSigned; 
            clonedContract.CustomerSignedDate = c.CustomerSignedDate; 
            clonedContract.CustomerSignedTitle = c.CustomerSignedTitle;
            clonedContract.CompanySigned = c.CompanySigned;
            clonedContract.CompanySignedDate = c.CompanySignedDate;
            
            newContracts.add(clonedContract);
        }
    }
insert newContracts;
}
In Sandbox, the scheduled class was successfully updating the "Last Scheduled Run" field and firing the trigger when applicable. However, when I schedule the class in Production, although it says the scheduled run has succeeded, the "Last Scheduled Run" field is no longer getting populated and therefore the trigger is never fired. 

Any suggestions on why this would be or how to fix this are much appreciated. 
  • November 24, 2014
  • Like
  • 0
I currently have a trigger "UpdateInTouchLead" shown below: 
trigger UpdateInTouchLead on Task (after insert, after update) {
Set<String> whoIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whoIds.add(t.WhoId);
	}
	
   	List<Lead> leads = [SELECT Id, First_in_touch__c FROM Lead WHERE Id =: whoIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhoId, t);
    		}
    	}
	}
         
    for (Lead l : leads) {
  		if (taskMap.containsKey(l.Id)) {
  			System.debug('Activity Date: ' + taskMap.get(l.Id).ActivityDate); 
  			System.debug('First In Touch before: ' + l.First_in_touch__c); 
  			l.First_in_touch__c = taskMap.get(l.Id).ActivityDate;
  			System.debug('First In Touch after: ' + l.First_in_touch__c); 
			l.Status = 'In Touch';
			l.POC_Communications__c = 'Muted'; 
   		}
	}
	update leads;
}
This trigger runs whenever a Task in inserted or updated, but I would like to have this trigger also run once a day (at midnight). I have tried creating a scheduled class but I am receiving the folowing error:  "Invalid Type: UpdateInTouchLead". 

The schedulable class is shown below: 
global class scheduledUpdateInTouchLead implements Schedulable {
global static void scheduleMe()
  {
    scheduledUpdateInTouchLead msc = new scheduledUpdateInTouchLead();
    String sch = '0 00 00 * * ?'; // everyday at midnight
    String jobID = System.schedule('Scheduled Job', sch, msc);

  }

  global void execute(SchedulableContext sc)
  {
	UpdateInTouchLead u = new UpdateInTouchLead();
  }
}
Any advice on how to fix this is appreciated. 
  • October 22, 2014
  • Like
  • 0
Hi, 

I'm trying to create a trigger that updates a contact's related opportunity location fields (City, State/Province, Country) based on the contact's location fields. This should only udpate the opportunity's location fields when the fields are previously blank. The code I have so far is below, but it doesn't seem to be working. 

trigger updateOppLocation on Contact (after insert) {
    
    List<OpportunityContactRole> contactRoles = [SELECT OpportunityId,ContactId
                                                 FROM OpportunityContactRole
                                                 WHERE ContactId IN : Trigger.new];
    
    if(contactRoles.size()>0) {
        Map<Id,Id> conOpp_map = new Map<Id,Id>();
        
        for(OpportunityContactRole cr : contactRoles) {
            conOpp_map.put(cr.ContactId,cr.OpportunityId);
        }
        
        List<Opportunity> opp_list = new List<Opportunity>([SELECT Id 
                                                       FROM Opportunity
                                                       WHERE Id IN : conOpp_map.values()]);
        
        for(Contact c : Trigger.new) {
            if(conOpp_map.containsKey(c.Id)) {
                for (Opportunity o : opp_list) {
                    if (o.City__c == null && o.State_Province__c == null && o.Country__c == null) {
                    	o.City__c = c.MailingCity;
                    	o.State_Province__c = c.MailingState;
                        o.Country__c = c.MailingCountry; 
                    }
                }
            }
        } 
   	update opp_list;
    } 
}

Any advice on how to get this to work is appreciated. 
  • September 10, 2014
  • Like
  • 0

I'm currently trying to create a trigger that runs whenever an Opportunity is created or updated. The trigger needs to check all the other Opportunities related to the Account of the Opportunity being updated. It should check to see if any of the Opportunities have a StageName equal to 'Closed Won - One Time' or 'Closed Won - Recurring' and if so, it should update the account Type to 'Customer'. If none of the Opportunities are closed won, the Account Type should be 'Prospect'.

This is the code I have but I'm not sure if I'm querying the right things: 

trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    List<Account> accts = new List<Account>();
    List<Opportunity> opps = new List<Opportunity>(); 
    
    for (Opportunity opp : Trigger.new) {
        accts = [SELECT Id, Name, Type FROM Account WHERE Id =: opp.AccountId LIMIT 1]; 
        opps = [SELECT Id, AccountId, StageName, Account.Type FROM Opportunity WHERE AccountId =: opp.AccountId];
    }

    for (Account a : accts) {
        for (Opportunity o : opps) {
            if (o.StageName == 'Closed Won - One Time' || o.StageName == 'Closed Won - Recurring' || o.StageName == 'Customer Reseller') {
                if (a == null) {
                    a = new Account(Id = o.AccountId, name='TestingName');
                }
                a.Type = 'Customer'; 
            } else {
                a.Type = 'Prospect';
            }
        }
    }
    update accts;
}
Any help is much appreciated.

Cheers
  • August 12, 2014
  • Like
  • 0
I'm currently trying to create a trigger that runs whenever an Opportunity is created or updated. The trigger needs to check all the other Opportunities related to the Account of the Opportunity being updated. It should check to see if any of the Opportunities have a StageName equal to 'Closed Won - One Time' or 'Closed Won - Recurring' and if so, it should update the account Type to 'Customer'. If none of the Opportunities are closed won, the Account Type should be 'Prospect'. 

This is the code I currently have but it doesn't seem to work. I'm not exactly sure how to check all the related opportunitites. 

trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    Map<Id, Account> accounts = new Map<Id, Account>();
    for (Opportunity opp : Trigger.new) {
        Account a = accounts.get(opp.AccountId);
        if (opp.StageName == 'Closed Won - One Time' || opp.StageName == 'Closed Won - Recurring') {
            if (a == null) {
                a = new Account(Id = opp.AccountId);
                accounts.put(opp.AccountId, a);
            }
            a.Type = 'Customer'; 
        } else {
            a.Type = 'Prospect';
        }
    }
    if (!accounts.isEmpty()) {
        update accounts.values();
    }
}

Any suggestions are appreciated! 
  • August 08, 2014
  • Like
  • 0
I've created a trigger on a Task to update a custom Opportunity field (Last_Contact_Date__c). The field gets updated based on the most recent task Activity Date. The trigger is seen below and works as desired: 
trigger UpdateOppLastContactDate on Task (after insert, after update) {
  
  Set<String> whatIDs = new Set<String>();
  
    for (Task t : Trigger.new) {
      whatIDs.add(t.whatID);
  }
  
     List<Opportunity> opps = [SELECT Id, Last_Contact_Date__c FROM Opportunity WHERE Id =: whatIDs];
    
     Map<String, Task> taskMap = new Map<String, Task>();
  
    for (Task t : Trigger.new){
      if (!(t.Type.equals('Eloqua Activity'))) {
        if (t.Status.equals('Completed')) {
          taskMap.put(t.whatID, t);
        }
      }
      
  }
         
    for (Opportunity o : opps) {
      if (taskMap.containsKey(o.Id)) {
        o.Last_Contact_Date__c = taskMap.get(o.Id).ActivityDate;
      }
  }
  update opps;
}

However, then I tried to modify this trigger to also update a custom Accounts variable (In_Touch_Date__c) but I cannot get it to function properly. 

Here is the modified code: 

trigger UpdateOppLastContactDate on Task (after insert, after update) {
	
	Set<String> whatIDs = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whatIDs.add(t.whatID);
	}
	
   	List<Opportunity> opps = [SELECT Id, Last_Contact_Date__c FROM Opportunity WHERE Id =: whatIDs];
   	
   	Map<Id, Account> accts = new Map<Id, Account>();
   	   
   	Map<String, Task> taskMap = new Map<String, Task>();

    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.whatID, t);
    		}
    	}
  		
	}
    
    for (Opportunity o : opps) {
  		if (taskMap.containsKey(o.Id)) {
    		o.Last_Contact_Date__c = taskMap.get(o.Id).ActivityDate;
    		Account a = accts.get(o.AccountId);
    		if (a.In_Touch_Date__c != null) {
    			if (taskMap.get(o.Id).ActivityDate.daysBetween(a.In_Touch_Date__c) < 0) {
    				a.In_Touch_Date__c = taskMap.get(o.Id).ActivityDate;
    			}
    		}
  		}
	}
	update opps;
}
I've bolded the updated code, any advice on why this doesn't work is much apprecaited. 
  • July 28, 2014
  • Like
  • 0

I've created a trigger on a task to udpate a custom Account field (In_Touch_Date__c). Although the trigger compiles, it does not seem to be working properly. What I am trying to do is have the Account In_Touch_Date__c field update to the most recent Activity Date of the Account. I have successfully created similar triggers on the Contact and Opportunity levels. 

Here is the current trigger code:

trigger UpdateInTouchAccount on Task (after insert, after update) {
	Set<String> whatIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whatIds.add(t.WhatId);
	}
	
   	List<Account> acct = [SELECT Id, In_Touch_Date__c FROM Account WHERE Id =: whatIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhatId, t);
    		}
    	}	
	}
         
    for (Account a : acct) {
  		if (taskMap.containsKey(a.Id)) {
    		a.In_Touch_Date__c = taskMap.get(a.Id).ActivityDate;
  		}
	}
	update acct;
}

 

  • July 23, 2014
  • Like
  • 0
I'm trying to create a trigger that will update a custom Account field called "In Touch Date" based on the Activity History of the account. I want the "In Touch Date" to always be the most recent date any contact in that account has been in touch. I was able to sucessfully create this trigger on a Contact level so that a Contact field also called "In Touch Date" will update based on the most recent Activity Date (code seen below). I am trying to figure out the easiest way to replicate this trigger on an Account level.

The working trigger on the Contact level is here: 
trigger UpdateInTouchDate on Task (after insert, after update) {
	Set<String> whoIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whoIds.add(t.WhoId);
	}
	
   	List<Contact> cons = [SELECT Id, In_Touch_Date__c FROM Contact WHERE Id =: whoIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhoId, t);
    		}
    	}
  		
	}
         
    for (Contact c : cons) {
  		if (taskMap.containsKey(c.Id)) {
    		c.In_Touch_Date__c = taskMap.get(c.Id).ActivityDate;
    		c.POC_Communications__c = 'Muted';
  		}
	}
	update cons;

}

Any suggestions on how to replicate this on an Account level would be much appreciated.
  • July 22, 2014
  • Like
  • 0
We created two triggers (one for leads and one for contacts) that populate a lead/contact field with the date of a task that is associated with that lead/contact. The trigger works just fine with contacts, however with leads we have the following issue:

Task is created with an ActivityDate of 5/20/2014 and the trigger sets the date on the lead level as TODAY (ex. 5/30/2014).

This is the code (bold part is where the error is occuring):

trigger UpdateInTouchLead on Task (after insert, after update) {
Set<String> whoIds = new Set<String>();

    for (Task t : Trigger.new) {
    whoIds.add(t.WhoId);
}

    List<Lead> leads = [SELECT Id, First_in_touch__c FROM Lead WHERE Id =: whoIds];
   
    Map<String, Task> taskMap = new Map<String, Task>();

    for (Task t : Trigger.new){
     if (!(t.Type.equals('Eloqua Activity'))) {
      if (t.Status.equals('Completed')) {
       taskMap.put(t.WhoId, t);
      }
     }
}
        
    for (Lead l : leads) {
    if (taskMap.containsKey(l.Id)) {
      l.First_in_touch__c = taskMap.get(l.Id).ActivityDate;
   l.Status = 'In Touch';
   l.POC_Communications__c = 'Muted';
    }
}
update leads;

}


Any idea on why this isn't working as desired?
  • May 30, 2014
  • Like
  • 0
Hi, I've created a trigger on a task that I want to use to update a custom contact field. I found documentation on how to create the trigger (http://salesforce.stackexchange.com/questions/23055/trigger-to-update-custom-field-from-another-custom-field-on-a-separate-object). However, When I run the test class I get an Assertion Failed Error: System.AssertException: Assertion Failed: Expected: 2014-05-29 00:00:00, Actual:
null
.

I am unsure of where my error lies and hoping someone can help.

Trigger Code:

trigger UpdateInTouchDate on Task (after insert, after update) {
Set<String> whoIds = new Set<String>();

    for (Task t : Trigger.new) {
         whoIds.add(t.WhoId);
    }

    List<Contact> cons = [SELECT Id, In_Touch_Date__c FROM Contact WHERE Id =: whoIds];
   
    Map<String, Task> taskMap = new Map<String, Task>();

    for (Task t : Trigger.new){
        taskMap.put(t.WhoId, t);
    }
        
    for (Contact c : cons) {
    if (taskMap.containsKey(c.Id)) {
         c.In_Touch_Date__c = taskMap.get(c.Id).ActivityDate;
    }
}
update cons;


Trigger Test Class: 

@isTest
private class TestUpdateTouchDate {

static testMethod void testUpdateInTouch() {
 
  Contact c = new Contact(FirstName = 'Test', LastName = 'Test');
  insert c;
 
  Date d = Date.newInstance(2014, 5, 29);
  Task t = new Task(ActivityDate = d);
  System.debug('Date before updating in touch date: ' + t.ActivityDate );
  insert t;
 
  List<Task> task = [SELECT ActivityDate FROM Task WHERE Id =:t.Id];
 
  if (task.size() > 0) {
       t = task.get(0);
  }
 
      System.debug('Price after trigger fired: ' + t.ActivityDate);
 
     System.assertEquals(t.ActivityDate, c.In_Touch_Date__c); 
   }
}

  • May 29, 2014
  • Like
  • 0