• Wilfredo Morillo 20
  • NEWBIE
  • 275 Points
  • Member since 2016
  • Systems Administrator

  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 10
    Likes Given
  • 3
    Questions
  • 70
    Replies
Diving back into Apex so I'm a bit rusty.  What we are looking to do is to create a trigger after insert and after update that will identify the Primary contact on the opportunity.  For that Primary contact, pull a custom field from the contact and then update a custom field on the opportunity with that value.

I know how to update the opportunity field but what I don't understand is how to pull the contact role information.  Can someone point me in the right direction?
I have a workflow rule that sends an email whenever a new lead is created.
If I create leads by importing from a spreadsheet the rule does not get triggered.

 
Hi All,
Not sure if this is even possible but here we go...
I have 2 custom objects 'History' and 'Data' that are both children of the Contact object.  Is there a way that I can display 'History' as a related list on the page layout for a record in the 'Data' object if both are children of the same contact record?  There can be more than one 'History' record and more than one 'Data' but they are always tied back to the parent Contact.  I would really appreciate any ideas/help anyone can suggest?
I am trying to write a class to create a combined list of events and tasks in descending order of created dates.  I need to limit the list to the last 50 records.  I am using a for loop to compare the created dates of tasks and events then trying to assign the record the wrapper class to get the correct order.  When I try to assign the task or activity I get an error that states. "undefinedConstructor not defined: [CTRL_MCContacActivities.activityWrapper].(Event)undefined" and  "undefinedConstructor not defined: [CTRL_MCContacActivities.activityWrapper].(Task)undefined".  I have found mulitple examples and have not been able to find out what is wrong.  My code is below.

public with sharing class CTRL_MCContactActivities {

    private Contact theContact;
    public Map<String, String> params {get;set;}
    public Integer getRetailActivitesCount {get;set;}
    public String conId;
    public List<Activity_Contact__c> activities {set;get;}
    Public List<Task> taskList {get; set;}
    Public List<Event> eventList {get; set;}
    Public integer tc = 0;
    Public integer ec = 0;
    public List<activityWrapper> activityList {get; set;}

    public CTRL_MCContactActivities(ApexPages.StandardController controller) {
        theContact = (Contact) controller.getRecord();
        If (theContact != null) {
          activityList = new List<activityWrapper>();
          taskList = [SELECT Id, Activity_Type__c, CreatedDate, Meeting_Type__c, Subject, ActivityDate, Description, Activity_Status__c, Owner.Name
                      FROM task
                      WHERE Id IN (Select taskId from taskRelation where Relationid = :theContact.Id) order by CreatedDate DESC] ;
          eventList = [SELECT Id, Activity_Type__c, CreatedDate, Meeting_Type__c, Subject, ActivityDate, Description,Activity_Status__c, Owner.Name
                      FROM event
                      WHERE Id IN (Select eventId from eventRelation where Relationid = :theContact.Id) order by CreatedDate DESC] ;
          IF(taskList.size() > 0 && eventList.size() > 0){
            FOR(integer i = 0; i < 50; i++){
              system.debug(i+' ***** task CreatedDate '+taskList[tc].CreatedDate+' event CreatedDate '+eventList[ec].CreatedDate);
              IF(taskList[tc].CreatedDate  > eventList[ec].CreatedDate){
                activityList.add(new activityWrapper(taskList[tc]));
                tc++;
              }else{
                activityList.add(new activityWrapper(eventList[ec]));
                ec++;
              }
            }

    }
  }
//Wrapper Class
    public class activityWrapper{
Task t {get; set;}
Event e {get; set;}

      }


  
Hello everyone,

I am trying to write a trigger that checks to see if a case is open for an account. If there is no case open then i want it to open a case with certain criteria. I have gotten the code to not throw any errors right up into the end. I was wondering if anyone can help me polish off my last 2 lines of code so that the Case will be Inserted.
trigger caseCheck on Account (After update) {
    for(Account myAccount : Trigger.new){
    List<Case> openCase =[Select id
                          From Case
                          Where (Accountid = :myAccount.Id 
                                 AND
                                 Status IN('New','Open')) ];    
        System.debug(openCase.size() + ' Open case(s) found');
 
        if(openCase.isEmpty()){
            Case c = new Case();
            c.Accountid = myAccount.Id;
            c.Type = 'ICM';
            c.Origin = 'SHIP';
            c.Division__c = 'Case Management';
            c.Status = 'New';
            c.RecordTypeId = '01236000000OJLq';
            }  
        Case.add(c);
        Insert Case;       
    }
}

I am reveiving the following errors;
Variable does not exist: c
Variable does not exist: Case
 
I am trying to write a wrapper class so I can create a combined lists of tasks and events, I have found several examples and documents that say to define a new public list, but whenever I try to add the list (below in bold).  I get the following error: Invalid type: accountWrapper.  Every example I see looks like they are doing the exact same thing so why do I get the error?

public with sharing class CTRL_MCContactActivities {
    private Contact theContact;
    public Map<String, String> params {get;set;}
    public Integer getRetailActivitesCount {get;set;}
    public String conId;
    public List<Activity_Contact__c> activities {set;get;}
    public List<accountWrapper> display_list {get; set;}
    Public List<Task> taskList {get; set;}
    Public List<Event> eventList {get; set;}
    Public integer tC = 0;
    Public integer eC = 0;
    public string activityId {get; set;}
    public string activityType {get; set;}
    public string createdDate {get; set;}
    public string meetingType {get; set;}
    public string subject {get; set;}
    public string activityDate {get; set;}
    public string description {get; set;}
    public string activityStatus {get; set;}
    public string ownerName {get; set;}

    public CTRL_MCContactActivities(ApexPages.StandardController controller) {
        theContact = (Contact) controller.getRecord();
        If (theContact != null) {
            activities = [SELECT Contact__c, Activity_Type__c, Activity_Subtype__c, Subject__c, Due_Date__c,
                                 Short_Description__c, Activity_Status__c, Assigned_To__c
                         FROM Activity_Contact__c
                         WHERE Contact__c = :theContact.Id
                         ORDER BY Due_Date__c DESC
                         LIMIT 50];
        } else {
            activities = new List<Activity_Contact__c>();
      }
    }
  //  remove this comment }

    public class activityWapper{
      
    }
    public Integer getRetailActivitesCount() {
           return  [SELECT count() FROM Task WHERE Id in (Select taskId from taskRelation where Relationid = :conId)  AND (RecordTypeId = '0126000000018NT' OR RecordTypeId = '0126000000018NU')];
    }






}
 
Someone could help me with the Assignment Rules triggered by Apex Code?
I am able to use the Assignment Rule using the new Case button checking the dedicated field in the Page Layout.

Here the Rule Configured

Rule Configured

I am also able to trigger the rule using the trigger on the Case on After Insert using the following Code:

public void OnAfterInsert(Case[] newCase, Map<Id, Case> newCaseMap) {
        List<Id> caseIdSet = new List<Id>();
        for(Case c : newCase) {
            caseIdSet.add(c.Id);
        }
        
        //updateOwnership(caseIdSet);
        
           List<Case> caseList = new List<Case>();
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.AssignmentRuleHeader.useDefaultRule = true;
        
        
        for(Case c : [SELECT Id FROM Case WHERE Id IN: caseIdSet]) {
            c.setOptions(dmo);
            caseList.add(c);
        }
        update caseList;
    }

Unfortunatelly the Email Notification isn't sent when I use the trigger. Could you help me please?
If I use the following code I don't receive any email :-(

dmo.EmailHeader.triggerAutoResponseEmail = true;

Do you have any Idea?
I am looking for a way to to add Look up Ids from a query to a set without using a for loop.  I am essentially looking for the most efficient way to write the code below.  I have found techniques using keyset() but that only pulls in the Id of the task relation object.

set<Id> retActivityIdList = new Set<Id>();
List<taskRelation> taskRelationList = [SELECT TaskId FROM taskRelation WHERE relationId = :contId ORDER BY CreatedDate DESC ];
        IF(!taskRelationList.isEmpty()){
          for(taskRelation tr: taskRelationList){
            retActivityIdList.add(tr.TaskId);
          }
        }
We have a requiremetn that on some accounts they attach a document that starts with the words "Opt-In". Once they attach that document we need to repvent them from ever deleting it. WOuld anyone be willing to help a loan Admin with no developer support with the actual trigger and test class code to make this work? I know enough to read the code and tweek for my use if necessary. I jsut do not have the skill set to actually write the code. 

Understand if can't be done but worth a shot to ask
after the winter'18 prduction upgrade no @future method are running in our org. I checked my class and testclass. I don't see the future handler in the logs. Is there anything else that I can check? 
I created this function to add or remove selected values in a multipicklist. It works but I'm trying to simplify it. Any comments or suggestions are truly apriciated. 
 
// This function returns an string with the values for a multipicklist after adding or removing an input Value.
	Public Static String MultipicklistUpdate(String currentValues,String inputValue,boolean addValue){
            
            list<String> allValues = new List<String>();
            boolean inputExist = false;
            
            String newValue = null;
            
            If (!(currentValues == '' || currentValues ==null)){
               
                allValues = currentValues.split(';');
    
                for(String value :allValues){
                    if(value == inputValue){
                      inputExist = true;  
                      if(addValue == true)newValue =+';'+ value;
                    }else{
                        if(newValue==null){
                             newValue =+ value;
                        }else {
                           newValue = newValue +';'+ value; 
                       }  
                    }
                }  
            }
            If(addValue == true && inputExist == false){
                if(newValue == null){
                    newValue = inputValue;
                }else{
               newValue = newValue+ ';'+inputValue;
                }
            }
            return newValue;
    }

 
I'm trying to find a way to fire a trigger when a content version history is inserted is that possible? 
Hi folk,

year is coming like this type 2,009.   i don't want comma .in data base int(10) . which was in php .so i created field year__c and taken data type -number. 
if i'm taken data type text then (comma) is not coming . but i need year data type number without comma 
Result ---2009

pls help me out 
 
Diving back into Apex so I'm a bit rusty.  What we are looking to do is to create a trigger after insert and after update that will identify the Primary contact on the opportunity.  For that Primary contact, pull a custom field from the contact and then update a custom field on the opportunity with that value.

I know how to update the opportunity field but what I don't understand is how to pull the contact role information.  Can someone point me in the right direction?
public void beforeUpdate( ) {
    List<Opportunity> oppLst = Trigger.old;
List < Opportunity > newOptyList = Trigger.New;
    List < Quote > QuoteList = [SELECT Id, Name, Opportunity.name  FROM Quote where OpportunityID = : oppLst[0].Id];
    List < Opportunity_Building__c > buildingopportunityList = new List < Opportunity_Building__c > ([SELECT Opportunity__c,Id, Name FROM Opportunity_Building__c where Opportunity__c = : oppLst[0].Id]);
   for(Opportunity oppNew :newOptyList ) {
    for(opportunity oppOld: oppLst){
        if ((buildingopportunityList.size() == 0 )){ 
        if(oppOld.StageName == 'Prospecting' && oppNew.StageName == 'Cost analysis' ) {
            oppNew.StageName.addError(Label.Opp_Stage_CostAnalysis_Error_without_OppBldg);
           }
        
        }
        if ((QuoteList.size() == 0)){
             if(oppOld.StageName == 'Cost analysis' && oppNew.StageName == 'Offer negotiation'){
                oppNew.StageName.addError(Label.Opp_Stage_Offernegotiation_Error_without_Quote);
            }
        }   
Hi,
I am new to Salesforce testing.When I try to push a trigger class it says your code coverage is below 75%.I need to deploy it urgently.I tried running all tests and by going to developer console to check code coverage for each class.
Here is the screenshot
User-added image

I am thinking if I could exclude the classes with miminal coverage from the code coverage so that they do not lower the overall code coverage.I tried that by annotating each class by @isTest but even after that when I tried run all tests and went to develop console I could still see those classes with 0% coverage.
Hi, 

 I wrote a code in line 62 code is covering the bulk issue please let me know how to fix this issue. 

 
public class CtapAssessmentTriggerUtils { 
  
   
    public static void processInsert(List<CTAP_Assessment__c> newLst) {
        Set<String> emailSet = new Set<String>();
        Set<String> partnerSet = new Set<String>();
        Lead l = new lead();
        
        Map<String, Id> mapEmailToConId = new Map<String, Id>();
        Map<String, Id> mapEmailToLeadId = new Map<String, Id>();
        List<Lead> newLeadLst = new List<Lead>();
        Map<String, CTAP_Assessment__c> newLeadforCtapMap = new Map<String, CTAP_Assessment__c> ();
         
        // collect emails in a set
        for(CTAP_Assessment__c ctap : newLst) {
            emailSet.add(ctap.Contact_Email__c);
            partnerSet.add(ctap.Partner_Account__c);
            system.debug('ctap.Contact_Email__c ' + ctap.Contact_Email__c);
        }
        // removing nulls
        emailSet.remove(null);
        
        system.debug('emailSet '  + emailSet);
        
        if(!emailSet.isEmpty()) {
            for(Contact objCon : [select id,email from contact where email IN :emailSet]){
                mapEmailToConId.put(objCon.Email, objCon.Id);
            }
            
            for(Lead objLead: [select id,email from Lead where email IN :emailSet]){
                mapEmailToLeadId.put(objLead.Email, objLead.Id);
            }
        }
        
         Account[] partnerActs = [select ownerid,owner.name from account where id = :partnerSet limit 1]; 
         
        // asssign based on map key match with email
        for(CTAP_Assessment__c ctap : newLst){
            if( mapEmailToConId.get(ctap.Contact_Email__c) != null){
              ctap.Contact__c = mapEmailToConId.get(ctap.Contact_Email__c);
              ctap.Lead__c = null;
             }else if ( mapEmailToLeadId.get(ctap.Contact_Email__c) != null) {
              ctap.Lead__c = mapEmailToLeadId.get(ctap.Contact_Email__c);
              ctap.Contact__c = null;
              }
              else {         
                  // Create a new lead         
                  l.Company = ctap.End_Customer_Name__c;
                  l.FirstName = ctap.Contact_First_Name__c; 
                  l.LastName = ctap.Contact_Last_Name__c; 
                  l.Email = ctap.Contact_Email__c;
                  l.Phone = ctap.Phone__c;
                  l.Title = ctap.Title__c;
                  l.Industry = ctap.Industry__c;
                  l.LeadSource = ctap.Lead_Source__c;
                  l.Country = ctap.End_Customer_Country__c;
                  l.State = ctap.state__c;
                  l.Postalcode = ctap.postalcode__c;
                  l.Employee_Size__c = ctap.Employee_Size__c;   
                  
                  if(ctap.Partner_Account__c !=  null && ( ctap.End_Customer_Country__c != 'USA') ){ //Here it checks only for country USA
                    l.Ownerid =  partnerActs[0].ownerid;
                  }  
                                              
                 if(ctap.Contact_Email__c <> null && 
                    ctap.End_Customer_Country__c <> null &&
                    ctap.End_Customer_Name__c <> null &&
                    ctap.Contact_First_Name__c <> null ) {                                                    
                   newLeadLst.add(l);
                  }
                  
                 newLeadforCtapMap.put(ctap.Contact_Email__c, ctap);
             
          } 
        }
        
           if ( !newLeadLst.isEmpty() ){
                insert newLeadLst;
     
                      /* Run lead assignment rule.
                         Database.DMLOptions dmo = new Database.DMLOptions();
                         dmo.assignmentRuleHeader.useDefaultRule = true;
                         Database.update(newLeadLst, dmo); 
                        */
                    
                 for(Lead lead : newLeadLst){
                    CTAP_Assessment__c ctap = newLeadforCtapMap.get(lead.Email);
                    ctap.Lead__c = lead.id; //Assign new lead to lead
                 }
            }
    }
     
    public static void processUpdate(Map<id,CTAP_Assessment__c> newMap, Map<id,CTAP_Assessment__c> oldMap) {
        List<CTAP_Assessment__c> changedLst = new List<CTAP_Assessment__c>();
        for(CTAP_Assessment__c ctap : newMap.values()){
            CTAP_Assessment__c oldCtap = oldMap.get(ctap.id);
            //Compare with if condiction 
           // if(ctap.Contact_Email__c != oldCtap.Contact_Email__c) {// compare other required fields here.
              if(ctap.Contact_Email__c != null){
                changedLst.add(ctap);
            }
        
            if(!changedLst.isEmpty())
                processInsert(changedLst);
        }
    }
    
  
    
  
}

 
Hi, 

  I need to update the lead owner id based on a condition else it must just follow the regular lead assingment rule. 

  Below is the code 

 
for(CTAP_Assessment__c ctap : newLst){

  
    if(ctap.Partner_Account__c !=  null && ctap.End_Customer_Country__c != 'USA'){
                  LeadOwner = partnerActs[0].ownerid;
               system.debug('Lead owner is assigned' + LeadOwner ); 
             }


   Lead l = new lead (Company = ctap.End_Customer_Name__c, 
                                  FirstName = ctap.Contact_First_Name__c, 
                                  LastName = ctap.Contact_Last_Name__c, 
                                  Email = ctap.Contact_Email__c,
                                  Phone = ctap.Phone__c,
                                  Title = ctap.Title__c,
                                  Industry = ctap.Industry__c,
                                  LeadSource = ctap.Lead_Source__c,
                                  Country = ctap.End_Customer_Country__c,
                                  State = ctap.state__c,
                                  Postalcode = ctap.postalcode__c,
                                  Employee_Size__c = ctap.Employee_Size__c                                 
                                  //,Ownerid = LeadOwner  // here is the problem it is showing null always Please suggest me how to set ownerid or update owner id conditionally                                   
                              );


  }

Thanks
Sudhir
I thought I’d share a logical complication am dealing with, as figuring this is kind of crushing me.
I have the below data in a map…..
while creating invoice for 120 quantity
First 100 qty should be charged for $20 each
Next 20 qty should be charged for $15 each
Invoice Total = (100 X 20) + (20 X 15) = $2300.
 
ItemDescriptionBilling UnitPrice Frequency of ThresholdStart Date of CalculationExpiration Date of Threshold  MinThreshold Max
Chem01LandDropDrum$20.00Yearly01/01/1712/31/171100
Chem01LandDropDrum$15.00 Yearly01/01/1712/31/17101150
Chem01LandDropDrum$10.00 Yearly01/01/1712/31/17151200
 
 
But Inside trigger, I couldn’t get the exact price ($15) for next 20 qty, as I do not have a proper unique key on Map…..couldn’t think of decent logic to get there. any thoughts would be appreciated.

Thanks
Kishore
  • October 28, 2017
  • Like
  • 0
I've got a method called from the after update of my opportunity trigger.  I'll paste it below.  Somewhere in here there's a too many soql queries error I get when updating a particular opportunity.  The debug log shows the error at the line with this map:

 
Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, (SELECT Term_Begin_Date__c, Term_End_Date__c, Finance_Grace_Period_Date__c FROM Customer_Assets__r 
                                            WHERE Term_End_Date__c != null ORDER BY Term_End_Date__c DESC) 
                                        FROM Account WHERE Id IN: accIds]);





Here's the full code with that in it:
 
public static void createUpdateAssets(Map<ID, OpportunityLineItem> qualifiedOLIsMap){
        if(qualifiedOLIsMap.size() > 0){
          //get all the product ids from the OLIs
          Set<Id> prodIds = new Set<Id>();
          Set<Id> contractIds = new Set<Id>();
          Set<Id> accIds = new Set<Id>();
          Opportunity thisOpp;
          for(OpportunityLineItem oli : qualifiedOLIsMap.values()){
            if(thisOpp == null){
                thisOpp = oli.Opportunity;
            }
            if(oli.PriceBookEntry.Product2Id != null){
              prodIds.add(oli.PriceBookEntry.Product2Id);
            }
            if(oli.Opportunity.Contract__c != null){
              contractIds.add(oli.Opportunity.Contract__c);
            }
            if(oli.Opportunity.Contract__r.MLSA__c != null){
              contractIds.add(oli.Opportunity.Contract__r.MLSA__c);
            }
            accIds.add(oli.Opportunity.AccountId);
          }
          
          Map<Id, Product2> prodMap = new Map<Id, Product2>([SELECT Id, (SELECT Id, Name FROM Versions_Product_Junctions__r)
                                      FROM Product2 WHERE Id IN: prodIds]);
          
          //added Term_Date__c to SOQL query
          Opportunity test = [SELECT Id, RecordTypeId FROM Opportunity WHERE Id =: thisOpp.Id];
          Map<Id, Contract> contractMap = new Map<Id, Contract>([SELECT Id, StartDate, EndDate, Term_Date__c,
                                          (SELECT Term_Begin_Date__c, Term_End_Date__c, Finance_Grace_Period_Date__c FROM Taxware_Assets__r 
                                            WHERE Term_End_Date__c != null ORDER BY Term_End_Date__c DESC) 
                                        FROM Contract WHERE Id IN: contractIds]);
            
          for(Contact_Contract_Junction__c ccj : [SELECT Contact__c, Contract__c FROM Contact_Contract_Junction__c WHERE Contract__c IN: contractIds]){
            Set<Id> contactIds = contractContactMap.get(ccj.Contract__c);
            if(contactIds == null){
              contactIds = new Set<Id>(); 
            }
            contactIds.add(ccj.Contact__c);
            contractContactMap.put(ccj.Contract__c, contactIds);
          }
            
            List<OLIAssetWrapper> allOLIAssets = getOLIAssets(qualifiedOLIsMap, prodMap, contractMap);
            
            List<Customer_Asset__c> allAssetsToInsert = new List<Customer_Asset__c>();
            List<Customer_Asset__c> allAssetsToUpdate = new List<Customer_Asset__c>();
            Customer_Asset__c thisOLIAsset;
            for(OLIAssetWrapper oliAst: allOLIAssets){
                thisOLIasset = oliAst.ast;
                if(thisOLIasset.Id == null){
                    allAssetsToInsert.add(thisOLIasset);
                }else{
                    allAssetsToUpdate.add(thisOLIasset);
                }
            }
            
            update allAssetsToUpdate;
            //IR-1357
            insert allAssetsToInsert;
            Set<Id> newAssetIds = new Set<Id>();
            for(Customer_Asset__c thisAsset : allAssetsToInsert){
                newAssetIds.add(thisAsset.Id);
            }
            List<Customer_Asset__c> newAssets = new List<Customer_Asset__c>();
            newAssets = [SELECT Id, Account__c FROM Customer_Asset__c WHERE Id =: newAssetIds];
            if(test.RecordTypeId != '012f0000000D9H9'){
                List<Contract_Asset_Connection__c> conns = new List<Contract_Asset_Connection__c>();
                Contract_Asset_Connection__c thisConn;
                for(Customer_Asset__c thisAsset : newAssets){
                    thisConn = new Contract_Asset_Connection__c();
                    thisConn.Contract__c = thisOpp.Contract__c;
                    thisConn.Asset__c = thisAsset.Id;
                 thisConn.Account__c = thisAsset.Account__c;
                  if(thisConn != null)
                    conns.add(thisConn);
                }
                if(!conns.isEmpty() && test.RecordTypeId != '012i0000001AgIY' && test.RecordTypeId != '012i000000129Hi' && test.RecordTypeId != '012i0000001AgId'){
                    insert conns;
                }
            }   
            Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, (SELECT Term_Begin_Date__c, Term_End_Date__c, Finance_Grace_Period_Date__c FROM Customer_Assets__r 
                                            WHERE Term_End_Date__c != null ORDER BY Term_End_Date__c DESC) 
                                        FROM Account WHERE Id IN: accIds]);
            
            Map<Id, Entitlement> entMap = new Map<Id, Entitlement>();
            for(OpportunityLineItem oli: qualifiedOLIsMap.values()){
            //if it's an update and the order type is renewal, update the Entitlement dates
                if(oli.Opportunity.Order_Type__c == Constants.ORDER_TYPE_RENEWAL || oli.Opportunity.Order_Type__c == Constants.ORDER_TYPE_ADD_ON || oli.Opportunity.Division__c == 'Taxify'){
                  if(oli.Opportunity.Entitlement__c != null && !entMap.containsKey(oli.Opportunity.Entitlement__c)){
                    Entitlement e = new Entitlement(Id = oli.Opportunity.Entitlement__c);
                    Date oldEntStart = oli.Opportunity.Entitlement__r.StartDate;
                    
                    if(oli.Opportunity.Contract_Paper_Type__c == 'New Paper'){
                        if(oldEntStart != null){//e.StartDate == null
                            e.StartDate = oldEntStart;
                        }else{
                            e.StartDate = oli.Opportunity.Contract__r.StartDate;
                        }
                        //changed EndDate to Term_Date
                        //e.EndDate = oli.Opportunity.Contract__r.Term_Date__c;
                        Account acc = accMap.get(oli.Opportunity.AccountId);
                        Date furthest = Date.today().addYears(-1);
                        if(acc != null && acc.Customer_Assets__r != null && acc.Customer_Assets__r.size() > 0){
                            for(Customer_Asset__c ass : acc.Customer_Assets__r){
                                if(ass.Term_End_Date__c > furthest){
                                    furthest = ass.Term_End_Date__c;
                                }
                            }
                            if(furthest > Date.today()){
                                e.EndDate = furthest;
                            }
                        }
                    }else if(oli.Opportunity.Contract_Paper_Type__c == 'Old Paper'){
                        Account acc = accMap.get(oli.Opportunity.AccountId);
                        Date furthest = Date.today().addYears(-1);
                        if(acc != null && acc.Customer_Assets__r != null && acc.Customer_Assets__r.size() > 0){
                            if(oldEntStart != null){//e.StartDate == null
                                e.StartDate = oldEntStart;
                            }else{
                                e.StartDate = oli.Opportunity.Contract__r.StartDate;
                            }
                            for(Customer_Asset__c ass : acc.Customer_Assets__r){
                                if(ass.Term_End_Date__c > furthest){
                                    furthest = ass.Term_End_Date__c;
                                }
                            }
                            if(furthest > Date.today()){
                                e.EndDate = furthest;
                            }
                        }
                    }
                    //check if finance grace period applies, update entitlement end date
                    Date latestGraceDate = null;
                    Customer_Asset__c thisAsset;
                    Account thisAcc = accMap.get(oli.Opportunity.AccountId);
                    integer numAssets = thisAcc.Customer_Assets__r.size();
                    for(integer i = 0; i < numAssets; i++){
                        thisAsset = thisAcc.Customer_Assets__r.get(i);
                        if(thisAsset.Finance_Grace_Period_Date__c > latestGraceDate){
                            latestGraceDate = thisAsset.Finance_Grace_Period_Date__c;
                        }
                    }
                    if(latestGraceDate > e.endDate){
                        e.endDate = latestGraceDate;
                    }
                    entMap.put(e.Id, e);
                  }
                }
            }
            update entMap.values();
            
            
            List<OpportunityLineItem> allOLIsToUpdate = new List<OpportunityLineItem>();
            Set<ID> opptyIDs = new Set<ID>();
            for(OLIAssetWrapper oliAst: allOLIAssets){
                OpportunityLineItem oli = oliAst.oli;
                oli.Asset__c = oliAst.ast.id;
                
                allOLIsToUpdate.add(oli);
                
                opptyIDs.add(oli.OpportunityID);
            }
            update allOLIsToUpdate;
            
            List<Opportunity> allOpptysToUpdate = new List<Opportunity>();
            for(ID opptyid : opptyIDs){
                Opportunity oppty = new Opportunity(id = opptyid);
                oppty.Fulfillment_Date__c = Date.Today();
                allOpptysToUpdate.add(oppty);
            }
            update allOpptysToUpdate;
        }
    }




I don't see any queries in for loops so I'm not sure how this can be re-written to eliminate the error.  Anyone see anything wrong here?  This is really old code that never really has a problem so this seems to be an edge case/bug in the code, I just can't find it.
Hi all,

I am new in Salesforce and I need a bit of help.
We customize a field in a Dev Sandbox, we made it to show the total amount of the opportunities attached to an vehicle. And also created a triger that updates that value every time a value in the opportunty is changed. But now we need to move all of that to a different sandbox.
Can you please help me with how can we do that.
What tool can I use to do that?

Thank You,
Calin B.

 
I used the following apex trigger in order to count the amount of open and closed tasks on opportunities.

trigger CountTask on Task (after insert, after update) {
    
    public List<Task> ltask1 = new List<Task>();
    public id oppid;
    public integer inp=0;   
    public integer inr=0;
    for(Task t:Trigger.New){
        oppid = t.WhatId;
        system.debug('oppid'+oppid);
        
    }
    ltask1 = [select id,Status from task where whatid=:oppid];
    system.debug('oppsize'+ltask1.size());
    
    
    for(task t:ltask1){
        if(t.Status!='Abgeschlossen'){
            inp = inp+1;
        } else{
            inr = inr +1;
        }                
    }
    List<Opportunity> opp = new List<opportunity>();    
    List<opportunity> op = [select id from Opportunity where id = :oppid];
    system.debug('oppsize'+op.size());
    for(opportunity o: op){
        o.Open_Tasks__c = inp;
        o.Closed_Tasks__c = inr;
        opp.add(o);  
    }
    if(opp.size()>0){
        update opp;
    }        
    system.debug('No of Tasks'+inp+inr);       
}

when trying to create a task on an opportunity I get the the following error:

CountTask: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 0065800000MKq82AAD; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: [] Trigger.CountTask: line 32, column 1

Since I am a bit new with Apex triggers, could someone explain, what do I need to do to fix this?
Thank you very much in advance

Debug Log:
30.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WAVE,INFO;WORKFLOW,INFO
16:28:44.2 (2103082)|ENTERING_MANAGED_PKG|APXTConga4
16:28:44.2 (11606583)|SOQL_EXECUTE_BEGIN|[46]|Aggregations:0|SELECT id, APXTConga4__WhatId__c FROM APXTConga4__Conga_Email_Staging__c 
16:28:44.2 (17655073)|SOQL_EXECUTE_END|[46]|Rows:0
16:28:44.18 (18693349)|CUMULATIVE_LIMIT_USAGE
16:28:44.18 (18693349)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.18 (18693349)|LIMIT_USAGE_FOR_NS|APXTConga4|
  Number of SOQL queries: 1 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.18 (18693349)|CUMULATIVE_LIMIT_USAGE_END

16:28:44.166 (166843648)|CODE_UNIT_STARTED|[EXTERNAL]|01q3E000000CzBl|Counttasks on Task trigger event AfterInsert for [00T3E000006N4P7]
16:28:44.166 (166926635)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
16:28:44.166 (167097773)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:10
16:28:44.166 (167215648)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:28
16:28:44.166 (167237693)|VARIABLE_SCOPE_BEGIN|[1]|this|Counttasks|true|false
16:28:44.166 (167316006)|VARIABLE_ASSIGNMENT|[1]|this|{}|0xba5e15e
16:28:44.166 (167401981)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:28
16:28:44.166 (167726154)|VARIABLE_SCOPE_BEGIN|[1]|this|Counttasks|true|false
16:28:44.166 (167769513)|VARIABLE_ASSIGNMENT|[1]|this|{}|0xba5e15e
16:28:44.166 (167782415)|STATEMENT_EXECUTE|[1]
16:28:44.166 (167784464)|STATEMENT_EXECUTE|[3]
16:28:44.166 (167814696)|HEAP_ALLOCATE|[3]|Bytes:4
16:28:44.166 (167882366)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
16:28:44.166 (167897985)|VARIABLE_ASSIGNMENT|[3]|this.ltask1|[]|0xba5e15e
16:28:44.166 (167904053)|STATEMENT_EXECUTE|[4]
16:28:44.166 (167916662)|VARIABLE_ASSIGNMENT|[4]|this.oppid|null|0xba5e15e
16:28:44.166 (167922885)|STATEMENT_EXECUTE|[5]
16:28:44.166 (167930867)|HEAP_ALLOCATE|[5]|Bytes:4
16:28:44.166 (167940385)|VARIABLE_ASSIGNMENT|[5]|this.inp|0|0xba5e15e
16:28:44.166 (167945619)|STATEMENT_EXECUTE|[6]
16:28:44.166 (167951062)|HEAP_ALLOCATE|[6]|Bytes:4
16:28:44.166 (167959200)|VARIABLE_ASSIGNMENT|[6]|this.inr|0|0xba5e15e
16:28:44.166 (168076642)|HEAP_ALLOCATE|[7]|Bytes:5
16:28:44.166 (168163019)|VARIABLE_SCOPE_BEGIN|[7]|t|Task|true|false
16:28:44.166 (183115571)|VARIABLE_ASSIGNMENT|[7]|t|{"LastModifiedDate":"2017-10-23T14:28:44.000Z","AccountId":"0015800000rcsReAAI","WhatId":"0065800000MKq82AAD","WhatCount":1,"IsHighPriority":false,"IsClosed":false,"WhoCount":0,"CreatedById":"00558000001scKvAAI","OwnerId":"00558000001scKvAAI","RecordTypeId":"01258000000cf60AAA","IsReminderSet":false,"CallAttptDateVa__c":"2017-10-23T14:28:44.000Z","Agent_ID__c":"00558000001scKv","Status":"Offen","QualifiedVa__c":false,"IsDeleted":false,"ActivityDate":"2017-10-27T00:00:00.000Z","Priority":"Normal","Qualified__c":false,"CurrencyIsoCode":"EUR","IsRecurrence":false,"Subject":"Test task","SystemModstamp":"2017-10-23T14:28:44.000Z","IsArchived":false,"Overdue_Task__c":"Not yet due","TaskSubtype":"Task","CreatedDate":"2017-10-23T14:28:44.000Z","Id":"00T3E000006N4P7UAK","etreminder__Reminder (3 more) ...":false,"LastModifiedById":"00558000001scKvAAI"}|0x4b02ac77
16:28:44.166 (183156343)|STATEMENT_EXECUTE|[7]
16:28:44.166 (183158555)|STATEMENT_EXECUTE|[8]
16:28:44.166 (183418924)|VARIABLE_ASSIGNMENT|[8]|this.oppid|"0065800000MKq82AAD"|0xba5e15e
16:28:44.166 (183428932)|STATEMENT_EXECUTE|[9]
16:28:44.166 (183436148)|HEAP_ALLOCATE|[9]|Bytes:5
16:28:44.166 (183536527)|HEAP_ALLOCATE|[9]|Bytes:18
16:28:44.166 (183599211)|HEAP_ALLOCATE|[9]|Bytes:23
16:28:44.166 (183637592)|USER_DEBUG|[9]|DEBUG|oppid0065800000MKq82AAD
16:28:44.166 (183674707)|HEAP_ALLOCATE|[7]|Bytes:5
16:28:44.166 (183707930)|VARIABLE_ASSIGNMENT|[7]|t|null|
16:28:44.166 (183720883)|STATEMENT_EXECUTE|[12]
16:28:44.166 (183726941)|HEAP_ALLOCATE|[12]|Bytes:51
16:28:44.166 (183759355)|HEAP_ALLOCATE|[12]|Bytes:4
16:28:44.166 (184248439)|SOQL_EXECUTE_BEGIN|[12]|Aggregations:0|SELECT id, Status FROM task WHERE whatid = :tmpVar1
16:28:44.166 (210054678)|SOQL_EXECUTE_END|[12]|Rows:1
16:28:44.166 (210102431)|HEAP_ALLOCATE|[12]|Bytes:8
16:28:44.166 (210127862)|HEAP_ALLOCATE|[12]|Bytes:44
16:28:44.166 (210190225)|HEAP_ALLOCATE|[12]|Bytes:8
16:28:44.166 (210271650)|VARIABLE_ASSIGNMENT|[12]|this.ltask1|[{"Id":"00T3E000006N4P7UAK","Status":"Offen"}]|0xba5e15e
16:28:44.166 (210283838)|STATEMENT_EXECUTE|[13]
16:28:44.166 (210291150)|HEAP_ALLOCATE|[13]|Bytes:7
16:28:44.166 (210392442)|HEAP_ALLOCATE|[13]|Bytes:1
16:28:44.166 (210413354)|HEAP_ALLOCATE|[13]|Bytes:8
16:28:44.166 (210430785)|USER_DEBUG|[13]|DEBUG|oppsize1
16:28:44.166 (210511107)|HEAP_ALLOCATE|[16]|Bytes:5
16:28:44.166 (210548229)|HEAP_ALLOCATE|[16]|Bytes:12
16:28:44.166 (210568605)|VARIABLE_SCOPE_BEGIN|[16]|t|Task|true|false
16:28:44.166 (210591779)|VARIABLE_ASSIGNMENT|[16]|t|{"Id":"00T3E000006N4P7UAK","Status":"Offen"}|0x1f929a41
16:28:44.166 (210601216)|STATEMENT_EXECUTE|[16]
16:28:44.166 (210637116)|HEAP_ALLOCATE|[17]|Bytes:9
16:28:44.166 (210670079)|STATEMENT_EXECUTE|[17]
16:28:44.166 (210671997)|STATEMENT_EXECUTE|[18]
16:28:44.166 (210686339)|HEAP_ALLOCATE|[18]|Bytes:4
16:28:44.166 (210699455)|VARIABLE_ASSIGNMENT|[18]|this.inp|1|0xba5e15e
16:28:44.166 (210717258)|HEAP_ALLOCATE|[16]|Bytes:5
16:28:44.166 (210733116)|VARIABLE_ASSIGNMENT|[16]|t|null|
16:28:44.166 (210745375)|STATEMENT_EXECUTE|[23]
16:28:44.166 (210778777)|HEAP_ALLOCATE|[23]|Bytes:4
16:28:44.166 (210859430)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
16:28:44.166 (210872795)|VARIABLE_ASSIGNMENT|[23]|this.opp|[]|0xba5e15e
16:28:44.166 (210879797)|STATEMENT_EXECUTE|[24]
16:28:44.166 (210883638)|HEAP_ALLOCATE|[24]|Bytes:46
16:28:44.166 (210901808)|HEAP_ALLOCATE|[24]|Bytes:4
16:28:44.166 (211225629)|SOQL_EXECUTE_BEGIN|[24]|Aggregations:0|SELECT id FROM Opportunity WHERE id = :tmpVar1
16:28:44.166 (228382474)|SOQL_EXECUTE_END|[24]|Rows:1
16:28:44.166 (228423557)|HEAP_ALLOCATE|[24]|Bytes:8
16:28:44.166 (228445757)|HEAP_ALLOCATE|[24]|Bytes:29
16:28:44.166 (228509663)|HEAP_ALLOCATE|[24]|Bytes:8
16:28:44.166 (228590026)|VARIABLE_ASSIGNMENT|[24]|this.op|[{"Id":"0065800000MKq82AAD"}]|0xba5e15e
16:28:44.166 (228602917)|STATEMENT_EXECUTE|[25]
16:28:44.166 (228699301)|HEAP_ALLOCATE|[25]|Bytes:1
16:28:44.166 (228720486)|HEAP_ALLOCATE|[25]|Bytes:8
16:28:44.166 (228757069)|USER_DEBUG|[25]|DEBUG|oppsize1
16:28:44.166 (228950342)|HEAP_ALLOCATE|[26]|Bytes:5
16:28:44.166 (228986680)|HEAP_ALLOCATE|[26]|Bytes:8
16:28:44.166 (229004080)|VARIABLE_SCOPE_BEGIN|[26]|o|Opportunity|true|false
16:28:44.166 (229024855)|VARIABLE_ASSIGNMENT|[26]|o|{"Id":"0065800000MKq82AAD"}|0x3cd4bd33
16:28:44.166 (229032667)|STATEMENT_EXECUTE|[26]
16:28:44.166 (229034029)|STATEMENT_EXECUTE|[27]
16:28:44.166 (229080362)|HEAP_ALLOCATE|[27]|Bytes:28
16:28:44.166 (229087921)|HEAP_ALLOCATE|[27]|Bytes:28
16:28:44.166 (229148700)|HEAP_ALLOCATE|[27]|Bytes:-4
16:28:44.166 (229165722)|VARIABLE_ASSIGNMENT|[27]|this.Open_Tasks__c|1|0x3cd4bd33
16:28:44.166 (229171858)|STATEMENT_EXECUTE|[28]
16:28:44.166 (229190966)|HEAP_ALLOCATE|[28]|Bytes:28
16:28:44.166 (229197103)|HEAP_ALLOCATE|[28]|Bytes:28
16:28:44.166 (229229141)|HEAP_ALLOCATE|[28]|Bytes:-4
16:28:44.166 (229240584)|VARIABLE_ASSIGNMENT|[28]|this.Closed_Tasks__c|0|0x3cd4bd33
16:28:44.166 (229246898)|STATEMENT_EXECUTE|[29]
16:28:44.166 (229295763)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
16:28:44.166 (229331151)|HEAP_ALLOCATE|[26]|Bytes:5
16:28:44.166 (229351385)|VARIABLE_ASSIGNMENT|[26]|o|null|
16:28:44.166 (229392780)|STATEMENT_EXECUTE|[31]
16:28:44.166 (229396733)|STATEMENT_EXECUTE|[32]
16:28:44.166 (229472763)|DML_BEGIN|[32]|Op:Update|Type:Opportunity|Rows:1
16:28:44.166 (229520965)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
16:28:44.320 (320138761)|ENTERING_MANAGED_PKG|Five9LSP
16:28:44.320 (325816235)|ENTERING_MANAGED_PKG|Five9LSP
16:28:44.320 (325879741)|ENTERING_MANAGED_PKG|Five9LSP
16:28:44.320 (326061566)|ENTERING_MANAGED_PKG|Five9LSP
16:28:44.332 (332314872)|CUMULATIVE_LIMIT_USAGE
16:28:44.332 (332314872)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 2 out of 100
  Number of query rows: 2 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 1 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.332 (332314872)|LIMIT_USAGE_FOR_NS|APXTConga4|
  Number of SOQL queries: 1 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.332 (332314872)|CUMULATIVE_LIMIT_USAGE_END

16:28:44.166 (337368997)|CODE_UNIT_STARTED|[EXTERNAL]|01q58000000eNwB|OpportunityTrigger on Opportunity trigger event BeforeUpdate for [0065800000MKq82]
16:28:44.166 (337404714)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
16:28:44.166 (337413925)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
16:28:44.166 (337458882)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
16:28:44.166 (337472388)|VARIABLE_SCOPE_BEGIN|[1]|this|OpportunityTrigger|true|false
16:28:44.166 (337540283)|VARIABLE_ASSIGNMENT|[1]|this|{}|0x79af66c3
16:28:44.166 (337586081)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
16:28:44.166 (337598233)|VARIABLE_SCOPE_BEGIN|[1]|this|OpportunityTrigger|true|false
16:28:44.166 (337614878)|VARIABLE_ASSIGNMENT|[1]|this|{}|0x79af66c3
16:28:44.166 (337623491)|STATEMENT_EXECUTE|[1]
16:28:44.166 (337637315)|STATEMENT_EXECUTE|[3]
16:28:44.166 (337646669)|STATEMENT_EXECUTE|[6]
16:28:44.337 (337650964)|CUMULATIVE_LIMIT_USAGE
16:28:44.337 (337650964)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 2 out of 100
  Number of query rows: 2 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 1 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.337 (337650964)|LIMIT_USAGE_FOR_NS|APXTConga4|
  Number of SOQL queries: 1 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.337 (337650964)|CUMULATIVE_LIMIT_USAGE_END

16:28:44.166 (339259338)|CODE_UNIT_FINISHED|OpportunityTrigger on Opportunity trigger event BeforeUpdate for [0065800000MKq82]
16:28:44.166 (389961988)|DML_END|[32]
16:28:44.166 (390113032)|EXCEPTION_THROWN|[32]|System.DmlException: Update failed. First exception on row 0 with id 0065800000MKq82AAD; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
16:28:44.166 (390843952)|HEAP_ALLOCATE|[32]|Bytes:144
16:28:44.166 (391119104)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id 0065800000MKq82AAD; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

Trigger.Counttasks: line 32, column 1
16:28:44.166 (391137831)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id 0065800000MKq82AAD; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

Trigger.Counttasks: line 32, column 1
16:28:44.391 (391143142)|CUMULATIVE_LIMIT_USAGE
16:28:44.391 (391143142)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 2 out of 100
  Number of query rows: 2 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 1 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.391 (391143142)|LIMIT_USAGE_FOR_NS|APXTConga4|
  Number of SOQL queries: 1 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

16:28:44.391 (391143142)|CUMULATIVE_LIMIT_USAGE_END
Hello All,
I am fetching contacts and few email from custom lables to send an email from singlemailmessge but i am receiving several times .can any one help me to fix this issue.


public class IncidentTriggers {
    public static void SendEmailtoSiteCOntact(List < Incident__c > lnewind) {
    
    Map < ID, ID > mCaseIDtoSiteContID = new Map < ID, ID > ();
    Map < ID, Incident__c > mSiteIDtoIncident = new Map < ID, Incident__c > ();
    
 try{
 //Find all Incident__cs with Sites
    for (Incident__c c: lnewind) {
    if (c.Site__c != null) {
    system.debug('incident:' + c.ID);
    system.debug('Incident__c.Site__c:' + c.Site__c);
    mCaseIDtoSiteContID.put(c.ID, c.Site__c);
    system.debug('values in the map'+mCaseIDtoSiteContID);
    system.debug('incidnetid:' + mCaseIDtoSiteContID.get(c.id));
    //mSiteIDtoIncident.put(c.Site__c, c);
    }

 //-----------------------------------

 //Find All Site_Contacts referenced in the above incidents
 List < Site_Contact__c > lSContacts = [SELECT ID, Site__c, Role__c, Contact__c, contact__r.Email, Transfer_To_Customer_Complaint__c, Transfer_To_Supplier_Complaint__c, Transfer_To_Product_Specification__c FROM Site_Contact__c WHERE Site__c in : mCaseIDtoSiteContID.values()];

 //Incident__c c = mSiteIDtoIncident.get(sc.Site__c);


    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    string address1=label.Incident_Manager1;
    string address2=label.Incident_Manager2;
    string address3=label.Incident_Manager3;
    string addresses=address1+':'+address2+':'+address3;
    for (Site_Contact__c sc: lSContacts) {
    if (sc.contact__r.Email != null || sc.contact__r.Email != 'null') {         
    addresses = addresses + ':' + sc.contact__r.Email;
    system.debug('intial Email Address Information ' + addresses);
    List < String > emailAddresses = new List < String > ();
    emailaddresses = addresses.split(':', 0);
    system.debug('final list of Email Address Information ' + emailaddresses);
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    EmailTemplate et = [SELECT Id ,name FROM EmailTemplate WHERE Name = 'Test Template for incident'];
    email.ToAddresses = (emailaddresses);
    email.setTemplateId(et.Id);
    email.setSaveAsActivity(false);
    email.setTargetObjectId(sc.contact__c);
    email.setOrgWideEmailAddressId('0D2200000004EQx');
    email.setwhatid(c.id);
    mails.add(email);
    }
    }
    
    }
    Messaging.sendEmail(mails); 
}
    
catch(Exception ec)
       {    
          system.debug('error is' + ec);
        }

    
   }
}

Regards,
Krishna
Hello all,

I'm running into an error that just doesn't make sense to me. I have a trigger on OrderItem that evaluates related payments to an order to determine if it is paid off. The error claims that a change to the order currency is happening, but that is not the case. I've debugged the before and after object maps to verify that CurrencyIsoCode is unchanged.
 
Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OrderItemTrigger: execution of AfterInsert
caused by: System.DmlException: Update failed. First exception on row 0 with id 8013D0000009C8hQAE; first error: FIELD_INTEGRITY_EXCEPTION, You can't edit the order currency when the order has order products.: Contract Currency: [CurrencyIsoCode]

Here is the trigger handler:
private void evaluatePaidOffStatus(List<OrderItem> orderItems) {
	if (shouldRun('evaluatePaidOffStatus')) {
		methodRunMap.put('evaluatePaidOffStatus', false);
		
		Set<Id> orderIds = new Set<Id>();
		for (OrderItem orderItem : orderItems) {
			orderIds.add(orderItem.OrderId);
		}
			
		OrderTransferService.evaluateOrderPayments(orderIds);
	}
}



and the erroring method:
public static void evaluateOrderPayments(Set<Id> orderIds) {
	Order[] orders = [select Id, Grand_Total__c, Paid_Off__c, (select Id, pymt__Amount__c from Payments__r) from Order where Id in :orderIds];// and Type != 'EDI'];
	for (Order order : orders) {
		Decimal amountPaid = 0.00;
		for (pymt__PaymentX__c payment : order.Payments__r) {
			amountPaid += payment.pymt__Amount__c;
		}

		order.Paid_Off__c = amountPaid >= order.Grand_Total__c;
	}
		
	update orders;
}

Thanks for any insight you all can give
 
I have a workflow rule that sends an email whenever a new lead is created.
If I create leads by importing from a spreadsheet the rule does not get triggered.

 
Hi 

I have Requirement on community  whenever user login community header image/branding  change . Please reply ..........
We currently have a trigger that was set up by a third party vendor automatically adds an Account Team based on the linked account data of our syncing database.  There is one representaive that the trigger doesn't seem to be recognizing.

I'm unfamiliar with the coding to be able to pin point the issue.  Is there anyone that can point me in the direction of a solution?

trigger AddAccountTeamMembers on Account (after insert,after update){
 //Get User's Name,Id and Store into userMap
   Map<String,Id> userMap=new Map<String,Id>();
   List<Id> userIds= New List<Id>();
   for(User u:[Select id,name from user]){
       userMap.put(u.name,u.id);
       userIds.add(u.Id);
    }
  if(trigger.isInsert && trigger.isAfter){
    Set<Id> repId=new Set<Id>();
    Set<Id> accList=new Set<Id>();
    List<AccountTeamMember> memberList=new List<AccountTeamMember>();   
  //Add account repid and account id's
    for(Account acc : trigger.new){
      repId.add(acc.OASP__OAS_Rep__c);
      accList.add(acc.id);
    }
    Map<id,String> conMap=new Map<id,String>();
  //Query the contacts with account RepId's
    if(repId != null && !repId.isEmpty()){
       for(Contact con: [Select id,name from Contact where Id In:repId]){
          conMap.put(con.id,con.name);
       }
    }
    for(Account acc : trigger.new){
  //Splitting the contacts
     String contactName = conMap.get(acc.OASP__OAS_Rep__c);
     if(contactName!=null){
        List<String> conSplit=contactName.Split(' and ');
  //Add the contacts into Account Team Members
        for(String temp: conSplit){
             AccountTeamMember accMember=new AccountTeamMember();
             accMember.TeamMemberRole='Account Manager';
             accMember.AccountId=acc.id;
             accMember.UserId=(Id)userMap.get(temp);
             memberList.add(accMember);
             
        }
      } 
    } 
    System.debug('++Acc Team Member++'+memberList);
   //insert the contacts and Sharing rules
    if(memberList!=null){
      Database.insert(memberList,false);
    }
    System.debug('++Account List++'+accList);
    //Use future method for Insert Account Share Access
    if(accList != null && accList.size()>0 && memberList.size()>0)
    FutureAccountShare.updateAccountShareAccess(accList);
  }
  if(trigger.isUpdate && trigger.isAfter){
    Set<Id> accId=new Set<Id>();
    Set<Id> repId=new Set<Id>();
    Map<String,AccountTeamMember> accTeamMap = New Map<String,AccountTeamMember>();
    list<AccountTeamMember> accmemlist = New list<AccountTeamMember>();
    list<AccountTeamMember> accteamMembers = New list<AccountTeamMember>();
    Map<id,String> conMap=new Map<id,String>();   
    Set<AccountTeamMember> uniquedelete = new Set<AccountTeamMember>();
    
     for(Account acct: trigger.new){
        accId.add(acct.Id);
        repId.add(acct.OASP__OAS_Rep__c);
     }
     for(Account acct: trigger.old){
        repId.add(acct.OASP__OAS_Rep__c);
     }
     
     For(AccountTeamMember acctmem: [Select id,AccountId,UserId,AccountAccesslevel,TeamMemberRole  from AccountTeamMember where AccountId In: accId]){
          accTeamMap.put(acctmem.AccountId+'&'+acctmem.UserId,acctmem);
          accmemlist.Add(acctmem);
     }
     if(repId != null && !repId.isEmpty()){
       for(Contact con: [Select id,Name from Contact Where ID IN: repId]){
         conMap.put(con.id,con.name);
       }
     }
     Set<Id> accupdateId=new Set<Id>();
     for(Account temp: trigger.New){
      if(temp.OASP__OAS_Rep__c != Trigger.oldMap.get(temp.id).OASP__OAS_Rep__c){
       accupdateId.add(temp.Id);
       for(Id userTemp: userIds){
        String Name = conMap.get(Trigger.oldMap.get(temp.id).OASP__OAS_Rep__c);
        if(Name!=null){
        List<String> contSplitdelete =Name.Split(' and ');
         for(String str: contSplitdelete){
            AccountTeamMember AccmemId = accTeamMap.get(temp.Id+'&'+userMap.get(str)); // 
            if(AccmemId != null) {
              uniquedelete.add(AccmemId);
            }
          }
        }
       }
      } 
     }
     if(uniquedelete!=null){ 
         List<AccountTeamMember> finalDelete = new list<AccountTeamMember>();
         finalDelete.addALL(uniquedelete);
         Database.delete(finalDelete,false);
     }
     List<AccountTeamMember> teamMember=new List<AccountTeamMember>();
        for(Account accUpdate : trigger.new){
        if(accUpdate.OASP__OAS_Rep__c != Trigger.oldMap.get(accUpdate.id).OASP__OAS_Rep__c){
         String contName = conMap.get(accUpdate.OASP__OAS_Rep__c);
          if(contName!=null){
             List<String> contSplit=contName.Split(' and ');
             for(String temp1: contSplit){
                AccountTeamMember acctMember=new AccountTeamMember();
                acctMember.TeamMemberRole='Account Manager';
                acctMember.AccountId=accUpdate.id;
                acctMember.UserId=(Id)userMap.get(temp1);
                teamMember.add(acctMember);          
             }
          }
        } 
        }
     if(teamMember!=null){
     //Insert Account Team Members and Sharing rules for update
      Database.insert(teamMember,false);
     }
 //Use future method for Update Account Share Access
 if(accupdateId != null && accupdateId.size()>0){
    FutureAccountShare.updateAccountShareAccess(accupdateId);
  }
  }
}
Using the one trigger per object best practice, my trigger is not updating the results back to old values when an update (that would NOT be counted in the SOQL query) or delete occurs. Please see code below:

Class:
public with sharing class CompletedEvents {
    protected final Event[] eventOldList;
    protected final Event[] eventNewList;
    Set<Id> contIds = new Set<Id>();

    public CompletedEvents(Event[] eventOldList, Event[] eventNewList) {
        this.eventOldList = eventOldList;
        this.eventNewList = eventNewList;
    }

    public CompletedEvents(List<Event> events){
        this.eventNewList = events;
    }
   
 public void executeTotalConferenceCalls(){
        for(Event e : eventNewList){
            if(e.WhoId != null){
                contIds.add(e.WhoId);
            }
        }

        AggregateResult [] ars = [Select WhoId eventId, count(id) ConfCount
                                  From Event
                                  Where WhoId in :contIds
                                  AND EndDateTime < :date.today()
                                  AND isDeleted = False
                                  AND Subject = 'Conference Call'
                                  GROUP BY WhoId All Rows];

        List<Contact> updCon = new List<Contact>();
        for(AggregateResult ar : ars){
            Contact c = new Contact();
            c.Id = (Id)ar.get('eventId');
            c.Total_Conference_Calls__c = Integer.ValueOf(ar.get('ConfCount'));
            updCon.Add(c);
        }

        if(updCon.size()>0){
            update updCon;
        }
    }

    public void executeLastCompletedEvent(){
        for(Event e : eventNewList){
            if(e.WhoId != null){
                contIds.add(e.WhoId);
            }
        }

        Event[] eventList = [Select WhoId, Subject, EndDateTime, ActivityDateTime, ActivityDate
                             From Event
                             Where WhoId in :contIds
                             AND EndDateTime < :date.today()
                             AND isDeleted = False
                             AND Subject != 'B/D-Conference'
                             AND Subject != 'Cancel/No Show'
                             AND Subject != 'DD Meeting'
                             AND Subject != 'NRS-Conference'
                             AND Subject != 'Other'
                             AND Subject != 'Drop-In'
                             AND Subject != 'Business Review'
                             AND Subject != 'One-On-One'
                             AND Subject != 'Travel'
                             AND Subject != 'Professional Association Event'
                             ORDER BY EndDateTime ASC All Rows];

        Map<Id, Contact> cMap = new Map<Id, Contact>();
        for(Event e : eventList){
            Contact c = new Contact(Id = e.WhoId);
            if(c.Id != null){
                c.Last_Completed_Event__c = e.EndDateTime;
                cMap.put(c.Id, c);
            }
        }

        update cMap.values();
    }
}

Trigger
trigger MasterEventTrigger on Event (
    before insert, after insert,
    before update, after update,
    before delete, after delete){
    Event[] eventOldList = trigger.IsDelete ? null : trigger.old;
    Event[] eventNewList = trigger.IsDelete ? trigger.old : trigger.new;
        
    if (Trigger.isBefore) {
        if (Trigger.isInsert) {
                new CompletedEvents(eventOldList, eventNewList).executeTotalConferenceCalls();
                new CompletedEvents(eventOldList, eventNewList).executeLastCompletedEvent();
        }

        if (Trigger.isUpdate) {
                new CompletedEvents(eventOldList, eventNewList).executeTotalConferenceCalls();
                new CompletedEvents(eventOldList, eventNewList).executeLastCompletedEvent();
        }

        if (Trigger.isDelete) {
                new CompletedEvents(eventOldList, eventNewList).executeTotalConferenceCalls();
                new CompletedEvents(eventOldList, eventNewList).executeLastCompletedEvent();
        }
    }
    
    if (Trigger.IsAfter) {
        if (Trigger.isInsert) {
        }
        if (Trigger.isUpdate) {
        }
        if (Trigger.isDelete) {
        }
    }
}

 

Hi All is it posssible to write single query to get records filter by date and sum of a field for records greater than equals to the date as newsum and oldSum for the records lesser than the date.

Consider below code for help;:

AggregateResult[] newForecastAmount = [SELECT User__c,sum(Forecast_AMT__c) newAmount FROM Forecast__c WHERE Creation_Date__c >= startDate GROUP BY User__c];


AggregateResult[] newForecastAmount = [SELECT User__c,sum(Forecast_AMT__c) oldAmount FROM Forecast__c WHERE Creation_Date__c > startDate GROUP BY User__c];

Please let me know ASAP.

Thanks

Regards

Hitesh Khatri

Hello Guys,

I have a string variable for example:

String str = 'Priority==\'xyz\' && Isescalated==true';
I want to execute the above statement in apex by replacing the Priority and Isescalated with record values.

I tried to use tooling API in triggers but i get exception cannot call future method from future. (I solved it by using stopping the recursion) but the record takes some time to reflect the changed owner.

Also i want to know what is the best way to do this. I cant use existing assignment rules as we can have more than 3000 rules setup and we also have to customize the assignment rules to use weightage.

Any suggestions?
How does one apply Lens or SQL filter to obtain records for curent date?
This does not work for example;
q = filter q by date('CreatedDate_Year', 'CreatedDate_Month', 'CreatedDate_Day') == TODAY();
I have an Apex Class that generates a List of Events:
 
Public class AgentAppointmentsPast30 {
    
	String sortOrder = ' Who.Name ';
    String ascendingOrDescending = ' ASC ';
    String UserID = UserInfo.getUserId();
    String dateTimeFormat = DateTime.now().format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
    
    String myRequest = 'SELECT id, Owner.Id, type, subject, Decision_Made_by_Client__c, Appointment_Result__c, Reason_for_Cancellation_No_Show__c,'+
                ' WhoId, Who.Name, Appoint_Set_By__c, ActivityDateTime, No_Show_Cancelled_Disposition__c,Request_to_Shuffle__c,Contact_Name__r.Actual_Sale_Date__c, Contact_Name__r.Foreclosure_Status__c, Contact_Name__r.FAIR_Packet__c,'+ 
        	    ' Contact_Name__c, Contact_Name__r.Name, Contact_Name__r.Id, Contact_Name__r.Account.Property_Address__c,Contact_Name__r.Account.Name, Contact_Name__r.Account.Id'+
                ' FROM Event ' + 
                ' WHERE Owner.Id = \''+UserId+'\' And RecordTypeId = \'0126A0000004Qle\' AND ( ActivityDateTime = LAST_N_DAYS:30 OR (ActivityDateTime = TODAY And Type != \'Appointment - Booked\' And Type != \'Appointment - Confirmed\' ))'+
				' ORDER BY ';

    
    	public void sortByContact() 	{this.sortOrder = ' Who.Name ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
   		public void sortByActivityDateTime() 	{this.sortOrder = ' ActivityDateTime ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByType() 	{this.sortOrder = ' Type ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortBySubject() 	{this.sortOrder = ' Subject ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByOutcome() 	{this.sortOrder = ' Decision_Made_by_Client__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByOutcomeNotes() 	{this.sortOrder = ' Appointment_Result__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByNoShowDisp() 	{this.sortOrder = ' No_Show_Cancelled_Disposition__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByNoShowReason() 	{this.sortOrder = ' Reason_for_Cancellation_No_Show__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByAddress() 	{this.sortOrder = ' Contact_Name__r.Account.Name ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByPacket() 	{this.sortOrder = ' Contact_Name__r.FAIR_Packet__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}



        List<Event> events;
     	public List<Event> getEvents() {
		events = new List<Event>();
        events = Database.query(myRequest + sortOrder + ascendingOrDescending);
        system.debug(events);
        return events;}

  		public void saveAndReturn() {
        update events;        
        }
}
I use the following test class:
 
@isTest
public class AgentAppointmentsPast30Test {
    
    static testMethod void TestApptPast30(){
        
        Account Testaccount = new account();
       	Testaccount.name = '123 Test Drive';
        Testaccount.RecordTypeId = '0126A0000004Qo4';
        Testaccount.APN__c = '123';
        Testaccount.OwnerId = '0056A000000HeMZ';
        insert Testaccount;
        
        Contact Testcontact = new contact();
        Testcontact.Lastname = 'Berenato';
        Testcontact.AccountId = Testaccount.Id;
        Testcontact.RecordTypeId = '0126A0000004QlU';
        Testcontact.OwnerId = '0056A000000HeMZ';
        insert Testcontact;
        
        Event Testevent = new event();
		Testevent.WhoId = Testcontact.id;        
        Testevent.Subject='Test';
        Testevent.type='Appointment - Booked';
        Testevent.RecordTypeId = '0126A0000004Qle';
        Testevent.ActivityDateTime=date.valueOf('2017-10-17 11:00:00z');
        Testevent.DurationInMinutes=120;
        insert Testevent;
        
        AgentAppointmentsPast30 at = new AgentAppointmentsPast30();
      	List<Event> list1 = at.getEvents();
        at.saveAndReturn();
        at.sortByActivityDateTime();
        at.sortByAddress();
        at.sortByContact();
        at.sortByNoShowDisp();
        at.sortByNoShowReason();
        at.sortByOutcome();
        at.sortByOutcomeNotes();
        at.sortByPacket();
        at.sortBySubject();
        at.sortByType();
        system.assertEquals(1, list1.size());
    }
}

I've never been able to have the event from the Test Class meet the criteria from the Apex Class, I always get the error:

System.AssertException: Assertion Failed: Expected: 1, Actual: 0

Even if I remove everything from the WHERE clause except the getUserId.

However, my Visualforce page in the Sandbox seems to be working fine, minus one major error.

If I assign two events to myself, I see them both in the Apex PageBlockTable.

User-added image

If I edit the event that is farther in the future, I click the Save Button I added to the table.

User-added image

The page reloads:

User-added image

The records are sorted by ActivityDateTime.

And then I manually refresh the page.

User-added image

And the event that was originally farther in the past gets automatically updated to match the new events edit.

As if the Save button is saving the new value to all of the records.

I'm totally stumped on how this is happening. I can't seem to find any workflow rule that would suggest this, and I've tested it several times outside of the PageBlockTable (in the Event's Detail page) and can't find proof that it updates both records independently.

Does anyone know what might be causing this, or why my Apex Class can't pass its test?



 
I'm creating a VF page for employees to create a record for a custom object. I'm having issues writing the redirect Apex code so that after they hit "Submit", the employees will be redirected to another VF page (that I've created called "SuccessPage") that says "Your profile has been submitted successfully". After five seconds the SuccessPage it automatically redirect to the company's website. But if the employee hits Cancel, it will close the VF page.

Record Code
<apex:page standardController="Object__c"> 
<apex:form >

<div class="header">
    <center><img src="{!$Resource.companylogo}" width="10%"/></center>
  </div> 
 
        <style>
            body .bPageBlock .pbBody .blue .pbSubheader{
                background-color:#154f82;
            
            }
            body .bPageBlock .pbBody .white .pbSubheader h3{
                color:#ffffff;
            }
        </style>
        

<apex:outputPanel styleClass="blue" layout="block">
      <apex:pageBlockSection title="Skills" id="section7">
       <apex:inputField value="{!Employee_Profile__c.Skills__c}"/>        
</apex:pageBlockSection>
</apex:outputPanel>

</apex:pageBlock>

<center><apex:commandButton value="Submit" action="{!save}"/><apex:commandButton value="Cancel" action="{!cancel}"/></center> 


  </apex:form>
</apex:page>
Success VF page
<apex:page >
    <h1>Success</h1>

  
  <script type="text/javascript">
    window.setTimeout("redirectpage();", 5000);    
    function redirectpage(){
    window.top.location.href = 'http://www.website.com';
    }
</script>
</apex:page>




 
I have get this error when loading the visualforce page and we put read only=true but i get view state error.Please suggest how to overcome this issue.

Thanks in advance.
Hello, 

New to writing trigger so I'm unsure why I'm getting the Id is not specified error. Goal is if an existing user record's Channel OR LOB field  is updated then, it should look for existing User History record and update the Role_End_Date__c and create a new history record with for that same user with the Role_Start_Date__c as today. 
 
public class UserHistory_CreateUpdateFromUser  {

	public static void findUser(List<User> newUsers, Map<Id,User> oldUsers, Boolean isInsert){

		List<User> newUserList = new List<User>(); 
		List<User> lOBChannelList = new List<User>();
		List<User> isActiveList = new List<User>(); 
		List<User> uManagerLOBChannelList = new List<User>();
        List<User> uManagerList = new List<User>(); 
		Map<Id,List<User>> reasonForUpdatingUser = new Map<Id,List<User>>(); 
			
       	for(User u : newUsers){
            //New user && Channel != Non Sales  
            if(u.Channel__c != 'Non Sales'){
                if(isInsert){ 
       				newUserList.add(u); 
       				System.debug('newUserList: '+ newUserList); 
       			}
                //Existing user && Channel || LOB is changed 
       			else if(!isInsert && (u.Channel__c != oldUsers.get(u.Id).Channel__c || u.LOB_Focus__c != oldUsers.get(u.Id).LOB_Focus__c)) {
       				lOBChannelList.add(u); 
       				System.debug('lOBChannelList: '+ lOBChannelList); 
       			}
       			//Existing user && deactived 
       			else if(!isInsert && u.IsActive != oldUsers.get(u.Id).IsActive){
       				isActiveList.add(u); 
       				System.debug('isActiveList: '+ isActiveList);
                }
                //Existing user && Manager is changed && Channel || LOB is changed 
       			else if(!isInsert && u.ManagerId != oldUsers.get(u.Id).ManagerId &&
                        (u.Channel__c != oldUsers.get(u.Id).Channel__c || u.LOB_Focus__c != oldUsers.get(u.Id).LOB_Focus__c)){
       				uManagerLOBChannelList.add(u); 
       				System.debug('uManagerLOBChannelList: '+ uManagerLOBChannelList);
       			}
       			//Existing user && Manager is changed 
                else if(!isInsert && u.ManagerId != oldUsers.get(u.Id).ManagerId){
                    uManagerList.add(u); 
                    System.debug('uManagerList: '+ uManagerList);
                }
            }     
       	}

       	if(newUserList.size()>0){
       		newUser(newUserList);
       	}	

       	if(lOBChannelList.size()>0){
       		lOBChannelUpdate(lOBChannelList); 
       	}

       	if(isActiveList.size()>0){
       		userisActiveUpdate(isActiveList); 
       	}

       	if(uManagerList.size()>0){
       		managerUpdateOnly(uManagerList); 
       	}

       	if(uManagerLOBChannelList.size()>0){
       		managerLOBChannelUpdate(uManagerLOBChannelList); 
       	}
       
	}

	public static void lOBChannelUpdate(List<User> lOBChannelList){
		//Find existing User History record and update end date fields 
		//Create new user history record and update fields based on user changes 

		List<Id> userIds = new List<Id>(); 
		List<User_History__c> existingUHtoUpdate = new List<User_History__c>(); 
		List<User_History__c> newUHtoInsert = new List<User_History__c>(); 

		for(User u : lOBChannelList){
			userIds.add(u.Id); 
		}
		System.debug('userIds: '+ userIds);
		System.debug('lOBChannelList: '+ lOBChannelList);

		if(userIds.size()>0){
			List<User_History__c> eUH = [SELECT Id, User__C, Role_End_Date__c, Manager_End_Date__c FROM User_History__c
											WHERE User__c =:userIds]; 
            System.debug('eUH' + eUH); 

			for(User_History__c uH : eUH){

                User_History__c existingUH = new User_History__c(); 
                
                if(uH.Role_End_Date__c == NULL){
					existingUH.Role_End_Date__c = Date.today(); 
					existingUH.Id = uH.Id;
                }
                else if(uH.Manager_End_Date__c == NULL){
					existingUH.Manager_End_Date__c = Date.today(); 
					existingUH.Id = uH.Id;
                }
                else if(uH.Role_End_Date__c == NULL && uH.Manager_End_Date__c == NULL){
                    existingUH.Role_End_Date__c = Date.today(); 
                    existingUH.Manager_End_Date__c = Date.today(); 
                    existingUH.Id = uH.Id;
                }
				existingUHtoUpdate.add(existingUH); 
			}
			System.debug('existingUHtoUpdate: '+ existingUHtoUpdate);

			for(User u1 : lOBChannelList){
                
				User_History__c newUH = new User_History__c(
				User__c = u1.Id, 
				Channel__c = u1.Channel__c,  
				LOB_Focus__c = u1.LOB_Focus__c,  
				Role_Start_Date__c = Date.today(), 
				Manager_Start_Date__c = Date.today()
			); 
				newUHtoInsert.add(newUH); 
				
			}	
			System.debug('newUHtoInsert: '+ newUHtoInsert);
		}

		if(!existingUHtoUpdate.isempty()){
			Database.update(existingUHtoUpdate); 
		}
		System.debug('Databaseupdate existingUHtoUpdate: ' + existingUHtoUpdate); 

		if(!newUHtoInsert.isempty()){
			Database.insert(newUHtoInsert);
		}

	}
I've checked on the debug log that it is finding the Id of the existing User History record when I do the query and added it on the list 'eUH' and looped through that list. 

 
  • October 17, 2017
  • Like
  • 1
Someone could help me with the Assignment Rules triggered by Apex Code?
I am able to use the Assignment Rule using the new Case button checking the dedicated field in the Page Layout.

Here the Rule Configured

Rule Configured

I am also able to trigger the rule using the trigger on the Case on After Insert using the following Code:

public void OnAfterInsert(Case[] newCase, Map<Id, Case> newCaseMap) {
        List<Id> caseIdSet = new List<Id>();
        for(Case c : newCase) {
            caseIdSet.add(c.Id);
        }
        
        //updateOwnership(caseIdSet);
        
           List<Case> caseList = new List<Case>();
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.AssignmentRuleHeader.useDefaultRule = true;
        
        
        for(Case c : [SELECT Id FROM Case WHERE Id IN: caseIdSet]) {
            c.setOptions(dmo);
            caseList.add(c);
        }
        update caseList;
    }

Unfortunatelly the Email Notification isn't sent when I use the trigger. Could you help me please?
If I use the following code I don't receive any email :-(

dmo.EmailHeader.triggerAutoResponseEmail = true;

Do you have any Idea?
In rest api i'm setting status code as 400.but it is always throwing error as bad request which is standard error message.but I need to send error message as no page.
Is it possible to override the error messages of standard http codes.
Thanks
The use case is that customer is presented with a VF page to book a resource (typically a consultant) for number of hours on a particular date. Once customer selects a specific resource her/his availability calendar appears where start and end time can be selected to make a booking.

thanks