• Mike DeMille
  • NEWBIE
  • 75 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 24
    Replies
I've got a trigger on contact to update an account field with the count of child contacts meeting a certain criteria.  My trigger works upon testing, but my test class is giving me some huge errors.  FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, BuyingCenterCount: execution of AfterInsert

Here is my Trigger:

trigger BuyingCenterCount on Contact (after insert, after update, after delete, after undelete) {
   
   
 
    List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;

  
    Set<Id> acctIds = new Set<Id>();
   
    for (Contact c : contacts) {
     
        if (c.AccountId != null) {
            acctIds.add(c.AccountId);
        }
    }
   
    List<Account> acctsToRollup = new List<Account>();
    
    
    for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                               FROM Contact 
                               WHERE AccountId in: acctIds 
                               AND OP_Buying_Center__c = True
                               GROUP BY AccountId]){
        Account a = new Account();
        a.Id = (Id) ar.get('AcctId'); 
        a.Number_of_OP_BC_Contacts__c = (Integer) ar.get('ContactCount');
        acctsToRollup.add(a);
    }
    
    
    update acctsToRollup;

}





Here is my test class - I've simplified it to only try and insert an account and contact for now but still getting the same error. 

@isTest
private class BuyingCenterCountTest {
    
    @isTest static void BuyingCenterCount() {
        
        Account t = New Account();
        t.Name = 'Tester';
        t.BillingCountry = 'UK';
        t.Website = 'www.creep.gov';
        
        insert t;
        
        Contact c = New Contact();
        c.LastName = 'Terry';
        c.OP_Buying_Center__c = True;
        c.AccountId = t.Id;
      
        insert c;
    }

}



Does anyone have experience with these errors? 
I'm trying to write a trigger on task that when a new task is created, two fields on the opportunity are updated (opportunity 'Last Sales Activity' = task.createdDate, and opportunity 'Last Sales Activity Type = task.Type

How can I point it to the opportunity fields? Do I have to query for parent data first?  This is what I have:

trigger updateOpportunityActivityFieldsFromTask on Task (before insert) {
    
    for(task t:trigger.new) {
        if(t.whatid != null && t.whatid.getsobjecttype() == opportunity.sobjecttype) {
            t.WhatId.Last_Sales_Activity__c=t.CreatedDate;
            t.whatid.Last_Sales_Activity_Type__c=t.Type;
        }
    }
   
}
I don't know if this can be done, but I'm trying to get a count of tasks and events related to either an account or contact under an account.  

I was hoping something like: 

SELECT Id 
   FROM Account
       (SELECT COUNT(Id) 
           FROM  TASK)

I'm basically trying to see how many tasks and events are related to an account (through account or account contacts).  My query doesn't recognize 'TASK' in this query, plus I am missing many other things like how to query for events also.  

Can anyone help point me in the right direction? I'm just running this from workbench
I have the following Apex Class that I'm going to schedule to run on a daily basis:

/******************************************************************************
Name          :  BatchToUpdateAccountMarketo
Created Date  :  11/14/2017
Description   :  Batch class to update the Accounts Number_Of_Marketing_Engagements__c, 

******************************************************************************/
global class BatchToUpdateAccountMarketo implements Database.Batchable<sObject>{
   
  public static final String MarketoOwnerId = '005d0000004tpATAAY';
   
  global String queryStr;
   
  global Database.QueryLocator start(Database.BatchableContext BC){
           return Database.getQueryLocator(queryStr);
  }

  global void execute(Database.BatchableContext BC, List<Account> acctLst){
    
    //Map of original Data
    Map<Id, Account> acctMap = new Map<Id, Account>([Select Id, Number_Of_Marketing_Engagements__c
                        From Account Where Id IN: acctLst]);
                        
    Map<Id, Account> acctMapToUpdate = new Map<Id, Account>();
      Id acctId;
      List<Account> acctToUpdateLst = new List<Account>();
    Date Last90Days = Date.Today() - 90;
      
      for(Task tsk : [Select Id, CreatedDate, WhatId, AccountId
                      From Task
                      Where CreatedDate = Last_90_Days
                      AND (WhatId IN :acctLst
                      OR AccountId IN :acctLst)
                      AND (NOT Subject LIKE '%Bounce%')
                      AND (NOT Subject LIKE '%Unsubscribe%')
                      AND (NOT Subject LIKE '%Acquired%')
                      AND (NOT Subject LIKE '%Contact Purchased%')
                      AND (NOT Subject LIKE '%[Outreach][Email][Out]%')
                      AND (NOT Subject LIKE '%Email: >>%')
                      AND Owner.Id = :MarketoOwnerId]){
        
        acctId = (tsk.AccountId != null) ? tsk.AccountId : tsk.WhatId;
        
        if(!acctMapToUpdate.containsKey(acctId)){
          acctMapToUpdate.put(acctId, new Account(Id = acctId, Number_Of_Marketing_Engagements__c = 0));
        }
        
        if(tsk.CreatedDate >= Last90Days){
          acctMapToUpdate.get(acctId).Number_Of_Marketing_Engagements__c++;
        }else{
          acctMapToUpdate.get(acctId).Number_Of_Marketing_Engagements__c++;
        }
      }
      
      for(Event evt : [Select Id, CreatedDate, WhatId, AccountId
                      From Event
                      Where CreatedDate = Last_90_Days
                      AND (WhatId IN :acctLst
                      OR AccountId IN :acctLst)
                      AND (NOT Subject LIKE '%Bounce%')
                      AND (NOT Subject LIKE '%Unsubscribe%')
                      AND (NOT Subject LIKE '%Acquired%')
                      AND (NOT Subject LIKE '%Contact Purchased%')
                      AND (NOT Subject LIKE '%[Outreach][Email][Out]%')
                      AND (NOT Subject LIKE '%Email: >>%')
                      AND Owner.Id = :MarketoOwnerId]){
        
        acctId = (evt.AccountId != null) ? evt.AccountId : evt.WhatId;
        
        if(!acctMapToUpdate.containsKey(acctId)){
          acctMapToUpdate.put(acctId, new Account(Id = acctId, Number_Of_Marketing_Engagements__c = 0));
        }
        
        if(evt.CreatedDate >= Last90Days){
          acctMapToUpdate.get(acctId).Number_Of_Marketing_Engagements__c++;
        }else{
          acctMapToUpdate.get(acctId).Number_Of_Marketing_Engagements__c++;
        }
      }
      
      for(Account acct : acctMapToUpdate.values()){
        
          //update Number of Marketing Engagements This Month 
          if(acct.Number_Of_Marketing_Engagements__c != acctMap.get(acct.Id).Number_Of_Marketing_Engagements__c){
            
            //Update account only if value changes
            acctToUpdateLst.add(acct);  
              
          }
      }
      
    //update acctToUpdateLst
    if(acctToUpdateLst.size() > 0){
        if(!Test.isRunningTest()){
          update acctToUpdateLst;          
        }
    }
  }

  global void finish(Database.BatchableContext BC){

  }
}


I'm only getting 55% code coverage with the following test class:  

/******************************************************************************
Name          :  BatchToUpdateAccountMarketoTest
Created Date  :  11/14/2017
Description   :  Test Class for BatchToUpdateAccountMarketo
******************************************************************************/
@isTest
private class BatchToUpdateAccountMarketoTest {

  //For batch class BatchToUpdateAccount
  static testMethod void PopulateAccountDataTest() {
    
    User Marketo;
   
  
    
    for(User usr : [Select Id
                    From User
                    Where User.Id = '005d0000004tpATAAY'
                    AND LastName != null
                    AND IsActive = true
                    limit 1]){
      Marketo = usr;
    }
    
    
    if(Marketo != null){
      
      System.runAs(Marketo){
      
      Account testAcc = new Account(website = 'http://www.cnn.com', Name = 'test1', BillingCountry = 'US', BillingState = 'CA', BillingPostalCode = '65432',
                        OP_Named_Account__c = 'Test_OP_Named_Account__c', Company_Type__c = 'Brand');
      insert testAcc;
      
      List<Task> tskLst = new List<Task>();
      List<Event> evtLst = new List<Event>();
      
      tskLst.add(new Task(Subject = 'Test subject This Month', WhatId = testAcc.Id, ActivityDate = Date.today()));
      tskLst.add(new Task(Subject = 'Test subject Last Month', WhatId = testAcc.Id, ActivityDate = Date.today()));
      insert tskLst;
      
      evtLst.add(new Event(Subject = 'TEST EVT_THIS_MONTH # ', WhatId = testAcc.Id, DurationInMinutes = 60, ActivityDateTime = DateTime.now()));
      evtLst.add(new Event(Subject = 'TEST EVT_Last_MONTH # ', WhatId = testAcc.Id, DurationInMinutes = 60, ActivityDateTime = DateTime.now()));
      insert evtLst;
    
      Test.setCreatedDate(tskLst.get(1).Id, Date.today().addMonths(-1));
      Test.setCreatedDate(evtLst.get(1).Id, Date.today().addMonths(-1));
      }
    }
    
    Test.startTest();
    BatchToUpdateAccountMarketo AccountBatchObject = new BatchToUpdateAccountMarketo();
    AccountBatchObject.queryStr = 'Select Id from Account limit 1';
    Database.executebatch(AccountBatchObject, 100);
    Test.stopTest();
  }
  
  }

Can anyone help me figure out how to get coverage on this?  I'm a beginner and have confused myself!
from a variable myContact I'm trying to reference a user lookup field ID on that contact's account.  The field name is Inside_Sales_Rep_Lookup__c.

I'm trying myContact.Account.Inside_Sales_Rep_Lookup__c.UserID.

I need help getting this right. 
I have a simple trigger that updates a field.  My test class is not passing, however gives 80% coverage on the trigger.  

Here is the trigger:

trigger Update_MQL on Lead (before insert, before update) {
for (Lead myLead : Trigger.new)
{
    if (myLead.MQL_Date__c == null && (myLead.Status =='MQL (Marketing Qualified Lead)' || myLead.Status == 'SAL (Sales Accepted Lead)'))
    {myLead.MQL_Date__c = system.today();
    }else { myLead.MQL_Date__c = myLead.MQL_Date__c;
    }
     }
     
}


Here is the test class:

@isTest 
public class TestUpdate_MQL {
    static testMethod void insertNewLead() {
    
    Lead newLead = new Lead();
    
    newLead.FirstName = 'Mike';
    newLead.LastName = 'DeMille';
    newLead.Status = 'MQL (Marketing Qualified lead)';
    newLead.LeadSource = 'Advertisment';
    
    insert newLead;
    
 
       System.assertEquals(system.today(), newLead.MQL_Date__c);
    
    }
    
    }


What needs to be fixed?
This is a simple field update trigger and I need help getting it bulkified.  I appreciate any help.

trigger Update_MQL on Lead (before insert, before update) {
for (Lead myLead : Trigger.new)
{
    if (myLead.MQL_Date__c == null && (myLead.Status =='MQL (Marketing Qualified Lead)' || myLead.Status == 'SAL (Sales Accepted Lead)'))
    {myLead.MQL_Date__c = system.today();
    }else { myLead.MQL_Date__c = myLead.MQL_Date__c;
    }
     }
     
}
I have an external ID field I want to use to match SFDC accounts with accounts in another application.  I would like to push in data weekly or even more often from the 3rd party application to our SFDC org and was wondering how to set this up.  

Do I need to create a connected App in SFDC, or just find api keys?  It would be very helpful to get pointed in the right direction!

Thanks
Hi, 

I could use some help getting started creating a trigger to do the following:

On accounts object, I want to summarize accounts passing the following filters into an account field (num_of_customers)

type = customer
ARR > 0

I simply want the total number of accounts that fall under that criteria to display on the accounts object in the 'num_of_customers' field.  Anyone willing to help?
Hi,

I'm a very beginner developer and I really need some help and ideas here on how to write an apex trigger that will change the opportunity stage from stage A to stage B 90 days from the time the opportunity was put into stage A if the opportunity stage has not already been changed.  I know I'm asking a lot here, but help would greatly be appreciated.  I'm looking for general ideas on how to do it as well as some help with the code.  

I don't believe this can be done with process builder or any other point and click features, right?
I have gotten some help and patched together a trigger that seems to work well.  My knowledge of test classes is basically nothing so I would really appreciate the help and would see it as a great opportunity for me to learn.  

Here is my trigger:


trigger dleadstatus2 on Lead (before insert, before update){

    List<Task> sentemails = new List<Task>();

    Set<String> leadRating = new set<String>{'D1', 'D2', 'D3', 'D4'};

     sentemails = [SELECT Id, whoid, Subject FROM Task WHERE whoid IN: Trigger.new];

  for (Task Email: sentemails) {

        if(leadRating.contains(trigger.newmap.get(Email.whoid).Eloqua_Lead_Rating__c) && Email.Subject.contains('Message Sent:')) {

            trigger.newmap.get(Email.whoid).Status = 'Contacted';

}
}


Here is what I have for a test class.  It covers 57%

@isTest
public class Testdleadstatus2 {

    static testMethod void testLeads(){
    
    Lead l = new Lead();
    l.FirstName = 'Michael';
    l.LastName = 'Burns';
    l.Eloqua_Lead_Rating__c = 'D1';
    l.Status = 'Open';
    insert l;
    
    Task t = new Task();
    t.subject = 'Message Sent: Error';
    insert t;
    
    List<Lead> open = [SELECT Id, Status FROM Lead WHERE FirstName = 'Michael'];
    System.assertEquals(0,open.size());
    
    
    List<Lead> contacted = [SELECT Id, Status FROM Lead WHERE FirstName = 'Michael'];
    System.assertEquals(1,contacted.size());
    
    }}



Any help would be greatly appreciated!
 
This is my first Apex Trigger and I realize it will make most of you cringe your teeth!  It is a simple trigger that will update the lead 'status' field to 'contacted' when the following criteria are met:

1- its 'lead rating' is either D1,D2,D3, or D4
2- the current lead 'status' is "open"
3- the lead has a related task containing "Message Sent:" in the subject 

Can anyone please help me bulkify this?  




trigger dleadstatus on Lead (before insert, before update) {



    for (Lead l : Trigger.new) {
    if((l.Eloqua_Lead_Rating__c =='D1' || l.Eloqua_Lead_Rating__c =='D2'|| l.Eloqua_Lead_Rating__c =='D3'|| l.Eloqua_Lead_Rating__c =='D4')&& l.Status =='Open') {
    List<Task> sentemails = [SELECT Id FROM Task WHERE Subject LIKE '%Message Sent:%'];
    
    if(sentemails.size() > 0) {
    l.Status = 'Contacted';}
    else {l.Status = 'Open';}}}

}

I need help with the general steps in creating an apex trigger.  I'm a beginner to apex coding, and have only done very basic field updates and record creations.  I need to build an apex trigger that updates a lead's status (a picklist value) to 'contacted' when the lead rating (also a picklist field) has either "D1", "D2", "D3", or "D4" selected AND the lead has been contacted via email (noted through activity with subject containing "Message Sent:")

So basically here is the criteria:  

IF a lead has status = "OPEN" AND lead rating= D1orD2orD3orD4 AND there is an activity associated with the lead with subject containing "Message Sent"

THEN update lead status to "Contacted"

I know this is a fairly basic trigger, but I could use some help with the architecture of what needs to be included. I would really appreciate any help in getting this going.  

I have a pretty interesting problem to solve here.  It involves duplicating products on that are added to an opportunity when it is a mulit-year contract.  The goal would be to get a line item for each year of the contract.  When adding products to an opportunity, If the 'initial term' field = 24 months, I would like to duplicate or create another line item for each product added to the opportunity that is of the 'type' = recurring (product type).  If the term = 36 months, I would like to add 2 more duplicate products of 'type' = recurring, for a total of 3.  If it's 48 months, then I would like to have a total of 4 of the same line items and so on..  If the initial term is 12 months, then no additional products would be needed.  

I could do this with process builder, but I need this to assess anytime products are added OR taken away.., so it wouldn't work to evaluate this if items were deleted.   I would like this to fire each time the 'initial term' field is changed.  I will also add an 'override' field that is a checkbox for situations that are rare and need overwritten.  The end goal is that I'm trying to get a line item for each year of a contract for multi year contracts, and it is taking my sales guys a while to add these.  They also get confused from time to time.  
 
I'm trying to write a trigger on task that when a new task is created, two fields on the opportunity are updated (opportunity 'Last Sales Activity' = task.createdDate, and opportunity 'Last Sales Activity Type = task.Type

How can I point it to the opportunity fields? Do I have to query for parent data first?  This is what I have:

trigger updateOpportunityActivityFieldsFromTask on Task (before insert) {
    
    for(task t:trigger.new) {
        if(t.whatid != null && t.whatid.getsobjecttype() == opportunity.sobjecttype) {
            t.WhatId.Last_Sales_Activity__c=t.CreatedDate;
            t.whatid.Last_Sales_Activity_Type__c=t.Type;
        }
    }
   
}
I don't know if this can be done, but I'm trying to get a count of tasks and events related to either an account or contact under an account.  

I was hoping something like: 

SELECT Id 
   FROM Account
       (SELECT COUNT(Id) 
           FROM  TASK)

I'm basically trying to see how many tasks and events are related to an account (through account or account contacts).  My query doesn't recognize 'TASK' in this query, plus I am missing many other things like how to query for events also.  

Can anyone help point me in the right direction? I'm just running this from workbench
from a variable myContact I'm trying to reference a user lookup field ID on that contact's account.  The field name is Inside_Sales_Rep_Lookup__c.

I'm trying myContact.Account.Inside_Sales_Rep_Lookup__c.UserID.

I need help getting this right. 
I have a simple trigger that updates a field.  My test class is not passing, however gives 80% coverage on the trigger.  

Here is the trigger:

trigger Update_MQL on Lead (before insert, before update) {
for (Lead myLead : Trigger.new)
{
    if (myLead.MQL_Date__c == null && (myLead.Status =='MQL (Marketing Qualified Lead)' || myLead.Status == 'SAL (Sales Accepted Lead)'))
    {myLead.MQL_Date__c = system.today();
    }else { myLead.MQL_Date__c = myLead.MQL_Date__c;
    }
     }
     
}


Here is the test class:

@isTest 
public class TestUpdate_MQL {
    static testMethod void insertNewLead() {
    
    Lead newLead = new Lead();
    
    newLead.FirstName = 'Mike';
    newLead.LastName = 'DeMille';
    newLead.Status = 'MQL (Marketing Qualified lead)';
    newLead.LeadSource = 'Advertisment';
    
    insert newLead;
    
 
       System.assertEquals(system.today(), newLead.MQL_Date__c);
    
    }
    
    }


What needs to be fixed?
This is a simple field update trigger and I need help getting it bulkified.  I appreciate any help.

trigger Update_MQL on Lead (before insert, before update) {
for (Lead myLead : Trigger.new)
{
    if (myLead.MQL_Date__c == null && (myLead.Status =='MQL (Marketing Qualified Lead)' || myLead.Status == 'SAL (Sales Accepted Lead)'))
    {myLead.MQL_Date__c = system.today();
    }else { myLead.MQL_Date__c = myLead.MQL_Date__c;
    }
     }
     
}
Hi, 

I could use some help getting started creating a trigger to do the following:

On accounts object, I want to summarize accounts passing the following filters into an account field (num_of_customers)

type = customer
ARR > 0

I simply want the total number of accounts that fall under that criteria to display on the accounts object in the 'num_of_customers' field.  Anyone willing to help?
Hi,

I'm a very beginner developer and I really need some help and ideas here on how to write an apex trigger that will change the opportunity stage from stage A to stage B 90 days from the time the opportunity was put into stage A if the opportunity stage has not already been changed.  I know I'm asking a lot here, but help would greatly be appreciated.  I'm looking for general ideas on how to do it as well as some help with the code.  

I don't believe this can be done with process builder or any other point and click features, right?
I have gotten some help and patched together a trigger that seems to work well.  My knowledge of test classes is basically nothing so I would really appreciate the help and would see it as a great opportunity for me to learn.  

Here is my trigger:


trigger dleadstatus2 on Lead (before insert, before update){

    List<Task> sentemails = new List<Task>();

    Set<String> leadRating = new set<String>{'D1', 'D2', 'D3', 'D4'};

     sentemails = [SELECT Id, whoid, Subject FROM Task WHERE whoid IN: Trigger.new];

  for (Task Email: sentemails) {

        if(leadRating.contains(trigger.newmap.get(Email.whoid).Eloqua_Lead_Rating__c) && Email.Subject.contains('Message Sent:')) {

            trigger.newmap.get(Email.whoid).Status = 'Contacted';

}
}


Here is what I have for a test class.  It covers 57%

@isTest
public class Testdleadstatus2 {

    static testMethod void testLeads(){
    
    Lead l = new Lead();
    l.FirstName = 'Michael';
    l.LastName = 'Burns';
    l.Eloqua_Lead_Rating__c = 'D1';
    l.Status = 'Open';
    insert l;
    
    Task t = new Task();
    t.subject = 'Message Sent: Error';
    insert t;
    
    List<Lead> open = [SELECT Id, Status FROM Lead WHERE FirstName = 'Michael'];
    System.assertEquals(0,open.size());
    
    
    List<Lead> contacted = [SELECT Id, Status FROM Lead WHERE FirstName = 'Michael'];
    System.assertEquals(1,contacted.size());
    
    }}



Any help would be greatly appreciated!
 
This is my first Apex Trigger and I realize it will make most of you cringe your teeth!  It is a simple trigger that will update the lead 'status' field to 'contacted' when the following criteria are met:

1- its 'lead rating' is either D1,D2,D3, or D4
2- the current lead 'status' is "open"
3- the lead has a related task containing "Message Sent:" in the subject 

Can anyone please help me bulkify this?  




trigger dleadstatus on Lead (before insert, before update) {



    for (Lead l : Trigger.new) {
    if((l.Eloqua_Lead_Rating__c =='D1' || l.Eloqua_Lead_Rating__c =='D2'|| l.Eloqua_Lead_Rating__c =='D3'|| l.Eloqua_Lead_Rating__c =='D4')&& l.Status =='Open') {
    List<Task> sentemails = [SELECT Id FROM Task WHERE Subject LIKE '%Message Sent:%'];
    
    if(sentemails.size() > 0) {
    l.Status = 'Contacted';}
    else {l.Status = 'Open';}}}

}