• SFDC-DMG
  • NEWBIE
  • 0 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 18
    Questions
  • 12
    Replies

Hello,

 

I'm trying to write a trigger that updates the Account when a Contact underneath it is updated. I only want to populate a given field if it is updated or populated so that it doesn't overwrite to a blank value if the Account field is populated but the Contact field is not.

 

From researching around, it seems like I have a loop. From the other codes I've looked at and the research I've done, I cannot figure out how to eliminate this loop or what my code should like in order to be "out of the loop" so if someone has direction on that, it would be very much appreciated because I have no idea how to get it out of the loop.

 

The Too Many DML Statements error that I'm getting is not being caused by the actual code that I put it, but rather the code below is causing another trigger I have to encounter the Too Many DML Statements error.

 

Here is the new code I put into Salesforce. After I had this trigger up and running in Salesforce, I started getting the error on other Triggers:

 

trigger updateAccount on Contact(after insert, after update){


List<ID>AccountIds = new list <Id>();
List<Account> accounts = new List<Account>();
List <Contact> Contacts = new List <Contact>();

for(Contact c: Trigger.new){
AccountIds.add(c.AccountId);
}

accounts = [Select Id from Account where ID IN :AccountIDs];
Contacts = [Select Id, AccountID from Contact where AccountID In:AccountIDs];

For(Contact c:Trigger.new){

If(c.TV_Alerts_Present__c !=null){
Account a = new account (id=c.accountid, TV_Alerts_Present__c = c.TV_Alerts_Present__c);  update a;}

If(c.TV_Average_Trace_Size__c !=null){
Account a = new account (id=c.accountid, TV_Average_Trace_Size__c = c.TV_Average_Trace_Size__c);  update a;}

If(c.TV_Broken_Traces__c !=null){
Account a = new account (id=c.accountid, TV_Broken_Traces__c = c.TV_Broken_Traces__c); Update a;}

If(c.TV_Instrumentation_Installed__c !=null){
Account a = new account (id=c.accountid, TV_Instrumentation_Installed__c = c.TV_Instrumentation_Installed__c); Update a;} 

If(c.TV_Is_Dormant__c !=null){
Account a = new account (id=c.accountid, TV_Is_Dormant__c = c.TV_Is_Dormant__c ); Update a;}

If(c.TV_Is_Paying__c !=null){
Account a = new account (id=c.accountid, TV_Is_Paying__c = c.TV_Is_Paying__c ); Update a;}

If(c.TV_Language_Installed__c !=null){
Account a = new account (id=c.accountid, TV_Language_Installed__c = c.TV_Language_Installed__c); Update a;}

If(c.TV_Last_Login__c !=null){
Account a = new account (id=c.accountid, TV_Last_Login__c = c.TV_Last_Login__c); Update a;}

If(c.TV_Max_Hosts__c !=null){
Account a = new account (id=c.accountid, TV_Max_Hosts__c = c.TV_Max_Hosts__c ); Update a;}

If(c.TV_Max_Trace_Size__c !=null){
Account a = new account (id=c.accountid, TV_Max_Trace_Size__c = c.TV_Max_Trace_Size__c); Update a;}

If(c.TV_Min_Trace_Size__c !=null){
Account a = new account (id=c.accountid, TV_Min_Trace_Size__c  = c.TV_Min_Trace_Size__c ); Update a;}

If(c.TV_Number_of_Apps__c !=null){
Account a = new account (id=c.accountid, TV_Number_of_Apps__c  = c.TV_Number_of_Apps__c); Update a;}

If(c.TV_Number_of_Hosts__c !=null){
Account a = new account (id=c.accountid, TV_Number_of_Hosts__c  = c.TV_Number_of_Hosts__c); Update a;}

If(c.TV_Number_of_Requests__c !=null){
Account a = new account (id=c.accountid, TV_Number_of_Requests__c  = c.TV_Number_of_Requests__c); Update a;}

If(c.TV_Number_of_Traces__c !=null){
Account a = new account (id=c.accountid, TV_Number_of_Traces__c  = c.TV_Number_of_Traces__c); Update a;}

If(c.TV_Number_of_Users__c !=null){
Account a = new account (id=c.accountid, TV_Number_of_Users__c  = c.TV_Number_of_Users__c); Update a;}

If(c.TV_Recent_Annotations__c !=null){
Account a = new account (id=c.accountid, TV_Recent_Annotations__c  = c.TV_Recent_Annotations__c); Update a;}

If(c.TV_Rum_Present__c !=null){
Account a = new account (id=c.accountid, TV_Rum_Present__c  = c.TV_Rum_Present__c ); Update a;}

If(c.TV_Tracelyzer_Installed__c !=null){
Account a = new account (id=c.accountid, TV_Tracelyzer_Installed__c   = c.TV_Tracelyzer_Installed__c ); Update a;}

If(c.TV_Traces_Present__c !=null){
Account a = new account (id=c.accountid, TV_Traces_Present__c  = c.TV_Traces_Present__c); Update a;}

If(c.TV_Users_Invited__c !=null){
Account a = new account (id=c.accountid, TV_Users_Invited__c  = c.TV_Users_Invited__c); Update a;}

   }
   }

 

 

 

 

 

After I added the above trigger, I started getting the Apex Trigger Error Message about Too Many DML statements due to the below trigger.

 

The error message I was getting was "There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex triger UpdateLeadContactOppDemoDeliveredTasks caused an unexpected exception, contact your adminitstrator. UpdateLeadContactOppDemoDeliveredTasks: System.LimitException: Too Many DML Statements: 151."

 

Here is the trigger the error said was causing the error:

 

trigger UpdateLeadContactOppDemoDeliveredTasks on Task (after delete, after insert, after undelete,
after update) {

// Updated on 2.28.13 to include only leads and contacts - opportunities were separated out


// Declare the variables

public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();
public set<Id> ContactIDs = new Set<Id>();
public list<Contact> ContactsToUpdate = new List<Contact>();




// Build the list of Leads and Contacts to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(Task t: Trigger.new){
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('003'))
    ContactIDs.add(t.WhoId);


    }
}

if(Trigger.isDelete || Trigger.isUpdate){
    for(Task t: Trigger.old){
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('003'))
    ContactIDs.add(t.WhoId);
    }
}

// Update the Leads

if(LeadIDs.size()>0){
for(Lead l: [Select l.Id, l.Demos_Delivered_Count__c,
(Select Id From Tasks where Status = 'Demo Delivered' )
From Lead l where Id in :LeadIDs])
LeadsToUpdate.add(new Lead(Id=l.Id, Demos_Delivered_Count__c = l.Tasks.size()));
update LeadsToUpdate;
}
if(LeadstoUpdate != null && !LeadsToUpdate.isEmpty())
Database.update(LeadsToUpdate);

// Update the Contacts

if(ContactIDs.size()>0){
for(Contact c: [Select c.Id, c.Demo_Delivered_Count__c,
(Select Id From Tasks where Status = 'Demo Delivered')
From Contact c where Id in :ContactIDs])
ContactsToUpdate.add(new Contact(Id=c.Id, Demo_Delivered_Count__c  = c.Tasks.size()));
update ContactsToUpdate;
}
if(ContactstoUpdate != null && !ContactsToUpdate.isEmpty())
Database.update(ContactsToUpdate);


}

 

Any help would be appreciated. I'm really struggling with this and all of the solutions that I have tried do not seem to be working.

 

Thank you in advance for your help!!

 

 

 

Hi All,

 

I have the below code that counts the number of a certain type of activity related to a given record. I want to update this to also pull in the date of the most recent task that is in the list. I have added a command to sort the tasks by date, but I'm getting stuck on how to select the most recent date of the generated list and populate that on the lead/contact record. Can anyone help with this?

 

Thanks!

 

trigger UpdateLeadContactOppDemoDeliveredTasks on Task (after delete, after insert, after undelete,
after update) {

// Updated on 2.28.13 to include only leads and contacts - opportunities were separated out


// Declare the variables

public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();
public set<Id> ContactIDs = new Set<Id>();
public list<Contact> ContactsToUpdate = new List<Contact>();




// Build the list of Leads and Contacts to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(Task t: Trigger.new){
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('003'))
    ContactIDs.add(t.WhoId);


    }
}

if(Trigger.isDelete || Trigger.isUpdate){
    for(Task t: Trigger.old){
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('003'))
    ContactIDs.add(t.WhoId);
    }
}

// Update the Leads

if(LeadIDs.size()>0){
for(Lead l: [Select l.Id, l.Demos_Delivered_Count__c,
(Select Id, ActivityDate From Tasks where Status = 'Demo Delivered' Order by ActivityDate DESC )
From Lead l where Id in :LeadIDs])
LeadsToUpdate.add(new Lead(Id=l.Id, Demos_Delivered_Count__c = l.Tasks.size()));
update LeadsToUpdate;
}
if(LeadstoUpdate != null && !LeadsToUpdate.isEmpty())
Database.update(LeadsToUpdate);

// Update the Contacts

if(ContactIDs.size()>0){
for(Contact c: [Select c.Id, c.Demo_Delivered_Count__c,
(Select Id, ActivityDate From Tasks where Status = 'Demo Delivered' Order by ActivityDate DESC)
From Contact c where Id in :ContactIDs])
ContactsToUpdate.add(new Contact(Id=c.Id, Demo_Delivered_Count__c  = c.Tasks.size()));
update ContactsToUpdate;
}
if(ContactstoUpdate != null && !ContactsToUpdate.isEmpty())
Database.update(ContactsToUpdate);


}

Hello,

 

 

I keep receving the following error when I try to click on a custom button that I created on the lead record:

 

A problem with the OnClick JavaScript for this button or link was encountered:

missing ; before statement

 

 

 

I am not sure why I am getting this error. Could someone please take a look at my button code below to see if you can recognize where the error may be?

 

 

 

{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}

If('{!Lead.BANT_Score__c}'=='' && '{Lead.Bant_was_logged__c' == ''){

alert("BANT must be logged before conversion to an Pre-Qualified Opportunity");
}

else
{
window.location.href="https://cs15.salesforce.com/lead/leadconvert.jsp?retURL=%2F{!Lead.Id}&id={!Lead.Id}";
}

 

 

 

Thank you!

 

Danielle

 

Hello,

 

I've been working on trying to create the test class for the below trigger, but I keep getting an error that I have 0% test coverage. Is there a reason that my Test Class is not covering my Trigger? If someone can please help me with this, I would greatly appreciate it - I've been wrestling with it for a few hours to no avail.

 

Thank you!!

 

 

Trigger (it is updating a field on the Opportunity based on a field from a custom child object):

 

trigger Update_SE_NHC_Assignment_Final on Network_Health_Check__c (before insert, after update) {

//Set the Opportunities to Update
Set<Id> OpportunityforUpdate = new Set<Id>();
    
  //When adding a new Network Health Check or Updating an existing Network Health Check
  if(trigger.isInsert || trigger.isUpdate || trigger.isDelete ){
for(Network_Health_Check__c n: [Select Related_Opportunity__r.id, Assigned_SE__r.id from Network_Health_Check__c]) {
    OpportunityforUpdate.add(n.Related_Opportunity__r.id);
 
  List<Opportunity> OpportunitiesToUpdate = new List <Opportunity>();
 
  //Update the SE NHC Assignment field on the related Opportunity to match the SE Assigned field on the Network Health Check Object
  for(Opportunity o : [Select Id, SE_NHC_Assignment__c from Opportunity where Id IN :OpportunityforUpdate]){
    o.SE_NHC_Assignment__c = n.Assigned_SE__r.id;
    OpportunitiesToUpdate.add(o);
  }
 
  update OpportunitiesToUpdate;
}
}
}

 

 

 

Test Class:

 

@isTest
Private class Update_SE_NHC_Assignment_Final_TEST_v2 {

          private static testMethod void myUnitTest() {
          
         Opportunity thisopp; 
         List<Opportunity> thisOpps = [SELECT id, Name, SE_NHC_Assignment__c FROM Opportunity WHERE id = '0064000000KxQ9v' ];
            if (thisopps.isEmpty()) {
            thisopp = new Opportunity();
            thisopp.id = '0064000000XxX4x';
        } else {
           thisopp = thisopps[0];

     Account ConsumerAccount = new Account(Name = 'Consumer Account', Type = 'Consumer');
    insert ConsumerAccount;  
            
       Account PartnerAccount = new Account(Name = 'Partner Account', Type = 'Partner');
    insert PartnerAccount;          
            
            
     ConsumerAccount = [Select Id, Name from Account where ID = :ConsumerAccount.ID];
            
     PartnerAccount = [Select Id, Name from Account where ID = :PartnerAccount.ID];
               
            

                Network_Health_Check__c n = new Network_Health_Check__c(
                Name = 'SE Assignment Test',
                Primary_Deployment_Location__c = 'Home',
                Primary_Deployment_Location_Type__c = 'HQ',
                Applications_Used__c = 'VoIP',
                Use_case__c = 'Application Analysis & Readiness - Cloud Service and Voice & Video Readiness', 
                Related_Opportunity__c = thisopp.id, 
                Assigned_SE__c = '00540000001ZD6G', 
                Partner_Account__c = PartnerAccount.ID,
                Consumer_Account__c = ConsumerAccount.Id);               
                insert n;
               
            {
                 try{
                    update n;
                    Opportunity o = [select id, SE_NHC_Assignment__c from Opportunity where id = :n.Related_Opportunity__r.id];
            
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
    }
}
}
}

 

 

Hello,

 

I wrote the below trigger. It updates a Lookup field (for a user) on the Opportunity from another related lookup field (user) on a custom child object.

 

I am not getting errors, but the field on the opportunity is not being updated.

 

Can anyone take a look at the code below and let me know what might be happening with it or what I can fix to have the field from the custom child object update the field on the opportunity upon edit (of the child object)

 

Thanks!

 

 

 

 

trigger Update_NHC_SE_Assignment on Network_Health_Check__c (before insert, after update) {

// Update the SE NHC Assignment on Opp based on the SE who delivered the Demo


// Declare the variables

public set<Id> OppIDs = new Set<Id>();
public list<Opportunity> OppsToUpdate = new List<Opportunity>();





// Build the list of Opps to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(Network_Health_Check__c n: Trigger.new){
        if(n.Assigned_SE__r.id != null && n.Name != null){
      
       Opportunity Opp = new Opportunity(Id=n.Related_Opportunity__r.Id, SE_NHC_Assignment__c = n.Assigned_SE__r.Id);update Opp;
     }
    }

if(Trigger.isUpdate){
    for(Network_Health_Check__c n: Trigger.old){
    if(n.Assigned_SE__r.id != null && n.Name != null){

       Opportunity Opp = new Opportunity(Id=n.Related_Opportunity__r.Id, SE_NHC_Assignment__c=n.Assigned_SE__r.Id); update Opp;
     }
    }

}
}
}

Hello,

 

We are implementing Zuora in our Salesforce, and I am trying to get some fields on the related Quote object to roll up to the Opportunity level. I'm running into some challenges doing so, and was hoping that someone would be able to help?

 

There are probably other errors that will pop up once I fix this one, but I'm currently running into the following error:

 

"Didn't understand relationship 'zqu__Quote__c' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' aftger the customer relationship name. Please reference your WSDL or the describe call for the appropraite names"

 

Here is the code as it currently stands, and if someone has insight on edits or knows how to make this work, that would be fantastic.

 

Thanks!

 

trigger OppUpdatefromQuoteObject on zqu__Quote__c (after delete, after insert, after undelete,
after update) {

// // This updates the opportunity with the term and amount information from the quote object

// If related to an Opportunity, query to find out the Opportunity number

public set<Id> OpportunityIDs = new Set<Id>();
public list<Opportunity> OpportunitiesToUpdate = new List<Opportunity>();


// Build the list of Opps to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(zqu__Quote__c q: Trigger.new){
    if(q.zqu__Opportunity__c!=null && string.valueOf(q.zqu__Opportunity__c).startsWith('006'))
    OpportunityIDs.add(q.zqu__Opportunity__r.id );

    }
}

if(Trigger.isDelete || Trigger.isUpdate){
    for(zqu__Quote__c q: Trigger.old){
    if(q.zqu__Opportunity__c!=null && string.valueOf(q.zqu__Opportunity__c).startsWith('006'))
    OpportunityIDs.add(q.zqu__Opportunity__r.id );
    }
}


// Update the Opportunities

if(OpportunityIDs.size()>0){
for(Opportunity o: [Select o.Id, o.amount, o.average_contract_value__c, o.Expected_or_Implied_Term_Months_del__c,
(Select id From zqu__Quote__c where zqu__TCV__c > 0 )
From Opportunity o where zqu__Opportunity__r.Id  in :OpportunityIDs])
OpportunitiesToUpdate.add(new Opportunity(Id=o.Id, zqu__TCV__c = o.amount, zqu__InitialTerm__c = o.Initial_Term_From_Quote__c);
update OpportunitiesToUpdate;
}
if(OpportunitiesToUpdate != null && !OpportunitiesToUpdate.isEmpty())
Database.update(OpportunitiesToUpdate);
}

 

Hello,

 

I created the below trigger to automatically update the discount on the opportunity product to reflect the discount calculated on the opportunity level based on a number of field selections. It is working great until we try and make any kind of mass update, and then I get the following error: System.LimitException: Too many SOQL queries.

 

Below is my code - is anyone able to help me fix it to avoid the Too Many SOQL Queries errors that I'm running into??

 

Thank you!!!!

 

trigger Opp_Line_Item_Update on Opportunity (after update) {
for( Opportunity opp: Trigger.new)
{

List<OpportunityLineItem> lineitem = [ SELECT Id, Opportunity.ID, Discount from
OpportunityLineItem where opportunity.isclosed = false and Opportunity.id = :opp.Id];

List<OpportunityLineItem> lineitemToUpdate = new List<OpportunityLineItem>();

for(OpportunityLineItem thislineitem: lineitem )
{
   if( thislineitem.discount !=  opp.total_extended_discount__c)
   {
       thislineitem.discount =   opp.total_extended_discount__c;
      lineitemToUpdate.add(thislineitem);
   }
}

if( lineitemToUpdate!=null)
{
   update lineitemToUpdate;
}

}
}

 

 

Hello All,

 

I am trying to create a batch job (that I have scheduled to run daily) that copies the value of one fied to another field.

 

I thought I had it up and running, but when I ran a report this morning, it only updated the field for a small handful of opportunities and it should be running on all of them.This is my first batch job, and I have been trying to discern how to write it correctly based on other posted examples in different places. I was wondering if anyone would be able to help?

 

Here's what needs to happen:

  • Essentially, on a daily basis, I want the batch job to run a trigger on all Opportunities to take the value of the "Stage" field and copy the text into a custom field called "Start of Day Stage" (which sounds simple enough...)


Here's my trigger apex code for the update:

 

global class DailyStageUpdateBatch implements Database.batchable<sObject>, Database.Stateful{

global Database.QueryLocator start(Database.BatchableContext bc){

    return database.getQuerylocator('select id,name,stagename from opportunity');
}
    
   global void execute(Database.batchableContext info, List<Opportunity> scope){ 
       List<Opportunity> oppsToUpdate = new List<Opportunity>(); 
       for(Opportunity o : scope){ 
           o.start_of_day_stage__c = o.stagename;
           oppsToUpdate.add(o);
       }
       update oppsToUpdate; 
   }     
   global void finish(Database.batchableContext info){     
   } 
}

 

And here's the code that implements it (that I then have scheduled to run every morning):

 

// APEX to schedule the batch run to update Opportunities to capture the stage at the start of the day.  
//
global class DailyStageCaptureSchedule implements Schedulable{
   global void execute(SchedulableContext sc) {
        DailyStageUpdatebatch batch = new DailyStageUpdatebatch();
      ID batchprocessid = Database.executeBatch(batch); 
   }
}

 

Any thoughts/ideas please and thank you!!

Hello,

 

I have the following trigger and it keeps causing this error: "System.Exception: Too many SOQL queries: 101". Can anyone help me to update this code so that it is not in a loop? I've been trying and struggling with it a bit.

 

Thank you!

 

Danielle

 

 

trigger LeadOppStageName on Task (before insert, before update, after insert){
// Goal: Pull fields from the lead record for tracking activities related to lists and to discern in which lead stages these activities occured

// If related to a Lead, query to find out the Lead ID, Lead Stage, and Lead Source Detail

// Create collection of tasks that are related to an lead (where the lead is listed only once)
    Set<Id> leadIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhoId;
        if(wId!=null && wId.startsWith('00Q') && !leadIds.contains(t.whoId)){
            leadIds.add(t.WhoId);
        }
    }
    // Pull in lead ids and related field to populate task record
    List<Lead> taskLead  = [Select Id, leadsource, lead_source_detail__c, Lead_Stage__c, Lead_Channel__c, Lead_Partner_Program__c, Lead_Segment__c,
    Original_Lead_Channel__c, Original_Lead_Partner_Program__c, Original_Lead_Segment__c from Lead where Id in :leadIds limit 1];
    Map<Id, Lead> leadMap = new Map<Id, Lead>();
    for(Lead l : taskLead){
        leadMap.put(l.Id,l);
    }
    
    // Update custom task field with custom lead field
    for(Task t : trigger.new){
        String wId = t.WhoId;
        if(wId!=null && wId.startswith('00Q')){
           Lead thisLead = leadMap.get(t.WhoId);
            if(thislead!=null){t.Sales_Stage__c = thisLead.Lead_Stage__c;} 
            if(thislead!=null){t.Lead_Source__c = thisLead.LeadSource;}            
            if(thislead!=null){t.record_type__c = 'Lead';}
            if(thislead!=null){t.lead_source_detail__c = thislead.Lead_source_detail__c;}           
            if(thislead!=null){t.Lead_Channel__c = thislead.lead_channel__c;} 
            if(thislead!=null){t.Original_Lead_Channel__c = thislead.original_lead_channel__c;}             
            if(thislead!=null){t.lead_partner_program__c = thislead.lead_partner_program__c;}
            if(thislead!=null){t.Original_lead_partner_program__c = thislead.Original_lead_partner_program__c;} 
            if(thislead!=null){t.lead_segment__c = thislead.lead_segment__c;}
            if(thislead!=null){t.Original_lead_segment__c = thislead.Original_lead_segment__c;}            

}
}
}

Hi,

 

I'm am trying to depoy an apex trigger to production, and I am running into an error that's seemingly completely unrelated to the code I'm trying to deploy but it's preventing me from being able to do it.

 

I'm not sure why this is happening or what changes I can make to avoid this error, but any insight you have would be extremely helpful. I have no idea what else to do to fix it!

 

Here's the failure message I'm getting when I try to deploy the inbound change set and there is a failure:

 

API Name
Type
Line
Column
Problem

UnitTests_logAttempts.SingleLeadAttempts() Class 15 1 Failure Message: "System.Exception: Too many SOQL queries: 101", Failure Stack Trace: "Trigger.ActivityOppStageName2: line 15, column 1"

 

Here's the "Trigger.ActivityOppStageName2" apex code that's causing the problem:

 

trigger ActivityOppStageName2 on Task (before insert, before update){

// If related to an Opportunity, query to find out the Opportunity number

// Create collection of tasks that are related to an opp (where the opp is listed only once)
    Set<Id> opIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startsWith('006') && !opIds.contains(t.WhatId)){
            opIds.add(t.WhatId);
        }
    }
    // Pull in opp ids and related field to populate task record
    List<Opportunity> taskOps = [Select Id, leadsource, lead_source_detail__c, StageName from Opportunity where Id in :opIds limit 1];
    System.assert(taskOps != null);
    Map<Id, Opportunity> opMap = new Map<Id, Opportunity>();
    for(Opportunity o : taskOps){
        opMap.put(o.Id,o);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startswith('006')){
            Opportunity thisOp = opMap.get(t.WhatId);
            if(thisOp!=null){t.Sales_Stage__c = thisOp.StageName;} 
            if(thisOp!=null){t.Lead_source__c = thisOp.LeadSource;}
            if(thisOp!=null){t.record_type__c = 'Opportunity';}
            if(thisOp!=null){t.lead_source_detail__c = thisOp.Lead_source_detail__c;} 
        }
    }
}

 

Here's the "UnitTests_logAttempts.SingleLeadAttempts()" unit test class that's related to the problem:

 

       static testMethod void SingleLeadAttempts() {
        
        if(!runTest_SingleLeadAttempts == true) {
            System.debug('===== SingleLeadAttempts unit test is currently inactive; enable before release');
        } else {
            
            Lead l = new Lead(FirstName = 'Bob',
              LastName = 'Test',
              Company = 'TestCo',
              Email = 'btest@testco.com',
              Title = 'Captain',
              Number_of_Customers__c = 10,
              Leadsource = 'Sourced by Sales',
              Lead_source_detail__c = 'sales',
              Customer_Type__c = 'good',
              How_Do_They_Assess_Networks_Today__c = 'unknown',
              lead_stage__c = 'Suspect',
              Status='None');
              
            insert l;
            
            String sToday = Date.Today().format();
            // Insert a call task
            Task t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call ' + sToday + ' 9:45 AM',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',
              
              ActivityDate = Date.Today());
              
            insert t;
            
            // Inserting a Call Task should automatically update the Lead
            l = ReGetLead(l.Id);
            
           
            
            String sId = l.Id;
            String compareResult;

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call with my mother',
              Type = 'Call',
              Status = 'Completed',          
              ActivityDate = Date.Today());
              
            insert t;
            
            l = ReGetLead(l.Id);
          

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call with my mother',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',          
              ActivityDate = Date.Today());
              
            insert t;
            
            l = ReGetLead(l.Id);
            

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',          
              ActivityDate = Date.Today());
              
            insert t;
            
            l = ReGetLead(l.Id);
         

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call ' + sToday + ' 9:45 AM',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Not Started',
              
              ActivityDate = Date.Today());
              
            insert t;
        
            l = ReGetLead(l.Id);            
            // This should fail as Status <> 'Completed'
           

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call ' + sToday + ' 9:45 AM',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',
              
              ActivityDate = Date.Today());
              
            insert t;
        
            l = ReGetLead(l.Id);            
         

            // Test Connect                         
            compareResult = logAttempts.createAttempt('Connect', 'Lead', sId);
            
            l = ReGetLead(l.Id);
            
           
            
            // Test Profile
            compareResult = logAttempts.createAttempt('Profile', 'Lead', sId);
            
            l = ReGetLead(l.Id);
            
      
           
        }
   }
   
   static testMethod void SingleLead_LiveDemoAttempt() {
    
        if(!runTest_SingleLead_LiveDemoAttempt == true) {
            System.debug('===== SingleLead_LiveDemoAttempt unit test is currently inactive; enable before release');
        } else {        
            
            Lead l = new Lead(FirstName = 'Bob',
              LastName = 'Test',
              Company = 'TestCo',
              Email = 'btest@testco.com',
              Title = 'Captain',
              Number_of_Customers__c = 10,
              Customer_Type__c = 'good',
              Leadsource = 'Sourced by sales',
              Lead_source_detail__c = 'sales',
              Lead_stage__c = 'Suspect',
              How_Do_They_Assess_Networks_Today__c = 'unknown');
              
            insert l;
            
            String sId = l.Id;
            String compareResult;
            
            // Test Live Demo
            compareResult = logAttempts.createAttempt('Live Demo', 'Lead', sId);
            
            // Query for a Task associated to the Lead
            Task newTask = 
              [Select WhoId, Type, Subject, Status, Id 
               From   Task 
               Where  WhoId = :sId
               Limit 1];
                        
          
            
        }
   }
   

 

 

If you need any further information to help, please let me know!!

 

Thank you!

 

Hello,

 

I created apex triggers to pull in information from the related record. I am all set with the leads. However, I have one for Contact and one for Opportunity. I want to Opportunity one to trigger/populate first and then, only if that is empty, to pull in the Contact information as a second step. I have them as two separate triggers, and I'm not sure how to combine them.

 

Could someone please help with figuring out either a) combining these into one to ensure that the order above is correct; or b) let me know if there is a way to have the Contact one trigger after the Opportunity one

 

I am familiar enough with apex that I was able to create these two simple separate ones, but I have no idea how I would make them more advanced to accomplish the above goal.

 

Thank you in advance for any guidance/help that you can give me!

 

Here are my two triggers:

 

Contact:

 

trigger ActivityContactDetails on Task (before insert, before update){
// Goad: Pull fields from the contact record for tracking activities related to lists and to discern in which lead stages these activities occured

// If related to a contact, query to find out the Contact ID, Lead Source, and Lead Source Detail

// Create collection of tasks that are related to an contact (where the contact is listed only once)
    Set<Id> contactIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhoId;
        if(wId!=null && wId.startsWith('003') && !contactIds.contains(t.whoId)){
            contactIds.add(t.WhoId);
        }
    }
    // Pull in contact ids and related field to populate task record
    List<contact> taskContact = [Select Id, leadsource, lead_source_detail__c from Contact where Id in :ContactIds];
    Map<Id, Contact> contactMap = new Map<Id, contact>();
    for(Contact c : taskContact){
        contactMap.put(c.Id,c);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new)
    if(t.what.id == null){
        String wId = t.WhoId;
        if(wId!=null && wId.startswith('003')){
           Contact thisContact = contactMap.get(t.WhoId);
            if(thiscontact!=null){t.Lead_Source__c = thisContact.LeadSource;} 
            if(thiscontact!=null){t.Sales_Stage__c = 'Existing Contact';}
            if(thiscontact!=null){t.Record_Type__c = 'Contact';} 
            if(thiscontact!=null){t.lead_source_detail__c = thiscontact.Lead_source_detail__c;} 
        }
    }
}

Opportunity:

 

trigger ActivityOppStageName on Task (before insert, before update){
// Goad: Pull fields from the lead and opportunity record for tracking activities related to lists and to discern in which lead/opp stages these activities occured

// If related to an Opportunity, query to find out the Opportunity number

// Create collection of tasks that are related to an opp (where the opp is listed only once)
    Set<Id> opIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startsWith('006') && !opIds.contains(t.WhatId)){
            opIds.add(t.WhatId);
        }
    }
    // Pull in opp ids and related field to populate task record
    List<Opportunity> taskOps = [Select Id, leadsource, lead_source_detail__c, StageName from Opportunity where Id in :opIds];
    Map<Id, Opportunity> opMap = new Map<Id, Opportunity>();
    for(Opportunity o : taskOps){
        opMap.put(o.Id,o);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startswith('006')){
            Opportunity thisOp = opMap.get(t.WhatId);
            if(thisOp!=null){t.Sales_Stage__c = thisOp.StageName;} 
            if(thisOp!=null){t.Lead_source__c = thisOp.LeadSource;}
            if(thisOp!=null){t.record_type__c = 'Opportunity';}
            if(thisOp!=null){t.lead_source_detail__c = thisOp.Lead_source_detail__c;} 
        }
    }
}

Hi,

 

We're running into code coverage issues. This is something that was written for our org in the past and now it is causing errors that are not allowing us to do a number of functions in our system. Can someone please help me?

 

I am getting only 60% coverage and failed tests for the following. Here are the two reasons given for the failure:

 

appnetaCMRRrollupTest.testTrigger1387.0System.DmlException: Update failed. First exception on row 0 with id 0064000000P2aKkAAJ; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, License Delivery Contact field is required to move an Opportunity to closed won and submit to finance.: [Contact_Name__c]Class.appnetaCMRRrollupTest.testTrigger: line 62, column 1
appnetaCMRRrollupTest.testBatch2234.0System.DmlException: Update failed. First exception on row 0 with id 0064000000P2aKiAAJ; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, License Delivery Contact field is required to move an Opportunity to closed won and submit to finance.: [Contact_Name__c]Class.appnetaCMRRrollupTest.testBatch: line 76, column 1

 

@isTest

//
// Test class for the trigger, batch and methods that perform a recalculation of the  
//   Total_Active_CMRR__c field from all the opportunities associated with those accounts.  
//  
//
//  Walt Thomas - Harvest Solutions - 2012
//

public with sharing class appnetaCMRRrollupTest {
  static Account acct = new Account();
  static Opportunity opp = new Opportunity();
    
  static{
    Product2 prod = new Product2();
    prod.name = 'test product';
    prod.Term__c = '1 year';
    prod.Subcription_Years__c = 1;
    prod.SubscriptionTerm_Months__c = 12;
    prod.Product_Type__c = 'PV Cloud';
    prod.Product_Class__c = 'Product';
    prod.Product_Listing__c = 'Subscription';
    prod.IsActive = true;
    insert prod;
    
    Pricebook2 pricebook = [SELECT id FROM pricebook2 WHERE name = 'Standard Price Book'];
        PricebookEntry pbe = new PricebookEntry();
        pbe.Pricebook2Id = pricebook.id;
        pbe.Product2Id = prod.id;
        pbe.UnitPrice = 100;
        pbe.IsActive = true;
        insert pbe;
        
    acct = new Account();
    acct.name = 'Test Account';
    insert acct;
    
    opp = new Opportunity();
    opp.name = 'test opp 1';
    opp.AccountId = acct.id;
    opp.StageName = 'Opportunity';
    opp.CloseDate = date.today();
    opp.Subscription_Start_Date__c = date.today() - 30;
    opp.Subscription_End_Date__c = date.today() + 30;
    insert opp;
    
    OpportunityLineItem oppLI = new OpportunityLineItem();
    oppLI.Quantity = 3;
        oppLI.UnitPrice = 250.00;
        oppLI.Opportunityid = opp.id;
        oppLI.pricebookentryid = pbe.id;
        insert oppLI;
    
  }
    
  static testMethod void testTrigger(){
    acct = [select id, Total_Active_CMRR__c from Account where id = :acct.id];
    system.debug('Total CMR ' + acct.Total_Active_CMRR__c);
    system.assert(acct.Total_Active_CMRR__c == 0);
    opp.stagename = 'Invoiced';
    update opp;
    opp = [select id, Opportunity_CMRR__c, stagename, iswon, Subscription_Term__c,Amount,
          Subscription_Start_Date__c, Subscription_End_Date__c   
      from Opportunity where id = :opp.id];
    system.debug('Opp  ' + opp);
    acct = [select id, Total_Active_CMRR__c, Total_Active_Contract_Value__c, Total_Active_Opp_Count__c 
      from Account where id = :acct.id];
    system.debug('Total CMR ' + acct.Total_Active_CMRR__c);
    system.assert(acct.Total_Active_CMRR__c <> 0);
    system.assert(acct.Total_Active_Opp_Count__c == 1);
    system.assert(acct.Total_Active_Contract_Value__c == opp.Amount);
  }
  static testMethod void testBatch(){ 
    opp.stagename = 'Invoiced';
    update opp;
    // there will be no change from the batch because the trigger already did the work.  
    Test.StartTest();
       appnetaCMRRbatch batch = new appnetaCMRRbatch();
      ID batchprocessid = Database.executeBatch(batch);
       Test.StopTest();
    acct = [select id, Total_Active_CMRR__c from Account where id = :acct.id];
    system.debug('Total CMR ' + acct.Total_Active_CMRR__c);
    system.assert(true);
  }
  static testMethod void testSchedule(){
    Test.startTest();
    appnetaCMRRschedule testSched = new appnetaCMRRschedule();
        String jobId = System.schedule(  'testSchedule', '20 30 8 10 2 ?', testSched);
       // Get the information from the CronTrigger API object 
         CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, 
           NextFireTime
           FROM CronTrigger WHERE id = :jobId];
      Test.stopTest();
      System.assertEquals(0, ct.TimesTriggered);
    System.assert(ct.NextFireTime <> null);
    }
  
}

Can someone please help? I've been struggling to try and fix this and haven't been able to do so. If you need the original classes that they are testing, please let me know, and I'll be happy to paste them.

 

Thank you!!

 

We have an issue where a Unit Test keeps failing and only reaching 37% cover.

 

When I look at the trigger with 37% coverage and see where the issue lies, below is what I get where the error is in red. I'm not sure how to fix this, and I was hoping someone could please help me on what I need to do to get this coverage up because it's already in our production system, and we can't load any new coding in because the validation fails as a result of the error here.

 

Any help or direction on this would be GREATLY appreciated.

 

Thank you!

 

Code Coverage Help for this Page

LeadConversionTrigger (Code Covered: 37%)

 

 line source
 1  trigger LeadConversionTrigger on Lead (after update) {
 2  
 3   // loop over all leads being updated
 4   Integer i;
 5   for(i=0; i<Trigger.new.size(); i++) {
 6  
 7   // check if this is a conversion
 8   if (Trigger.old[i].isConverted == false && Trigger.new[i].isConverted == true) {
 9  
 10   // if a new opportunity was created
 11   if (Trigger.new[i].ConvertedOpportunityId != null) {
 12  
 13   // update the converted opportunity with some fields from the lead
 14   Opportunity opp = [Select o.Id, o.Amount, o.Note_Box__c from Opportunity o Where o.Id = :Trigger.new[i].ConvertedOpportunityId];
 15   opp.Amount = Trigger.new[i].Amount__c;
 16   opp.Note_Box__c = Trigger.new[i].Note_Box__c;
 17   update opp;
 18   }
 19   }
 20   }
 21

  }

I am trying to create apex code that will capture either the Lead or Opportunity stage when an associated activity is created or completed.

 

In other words, when someone makes a phone call, I want that activity record to pull in the lead stage at that moment in time so that we can help track leads and activities throughout their lifecycle. Additionally, when an activity is logged on the opportunity, I would like the same thing... essentially, I can then pull activities and what stages they were completed.

 

Any help or other ideas people have around this would be hugely appreciated!

 

Thanks!

Hi,

 

I'm looking to clone an Opportunity and create a line item at the same time.

 

 

Ideally, I would want to clone the Opportunity with products, make an update on the line items indicating that they were a part of the original Opportunity, and then add an additional line item to credit the total amount of the original Opp.

 

 

My goal is to clone the Oppportunity and create an additional product line item that is basically a credit for the original opportunity's amount. Can anyone help provide me some insight on this? I am new to coding, and I'm getting stuck on what code I use to clone an Opportunity. I think the code below will just update the fields that I specified rather than just clone everythign that's already existing.

 

Can someone please help me get back on the correct path for this or let me know if it is possible?

 

Thank you!!

 

trigger RenewalUpgrade on Opportunity (after insert, after update){

 

List<Opportunity> opptsToInsert = new List<Opportunity>();

        Opportunity newOppt = new Opportunity();

       

        for(Opportunity oppt : [Select RecordTypeId, Name, Contact_Name__c, Email__c, AccountId, Amount

From Opportunity where Id in :mapRepSitesOpportunities.values()])

        {

            newOppt.Name =  oppt.Name + ' Renewal Upgrade';

            newOppt.AccountId = oppt.AccountId;

            newOppt.Contact_Name__c = oppt.Contact_Name__c;

            newOppt.RecordTypeId =  '01240000000USG';                                                     

            newOppt.CloseDate = newOpptCloseDate;

            newOppt.StageName = 'Opportunity'; 

            newOppt.Type = 'Subscription Renewal Upgrade';

            newOppt.Renewal_Upgrade__c = oppt.AccountId ;

            newOppt.Addressable_Renewal_Amount__c = oppt.Amount; 

            

           

            for (OpportunityLineItem lineItem :oppt.OpportunityLineItems) {

                newOppt.Description = lineItem.PricebookEntry.Name;

            }

  insert(opptsToInsert);

           

        } {

 

for(Opportunity opptInserted : [Select Id, Amount, Description from Opportunity where Id in :opptsToInsert])

            {      

                newOpptLineItem.OpportunityId = opptInserted.Id;

                newOpptLineItem.Quantity = 1;  

                newOpptLineItem.UnitPrice = -opptInserted.Amount;

                newOpptLineItem.Product = '01t40000003TkIJ';

                

                                             

         

            insert(opptLineItemsToInsert);

        }

}

 

        }

 

Hi All,

 

I tried reaching out to Salesforce to help on this, and they recommended I try the Developer Board first.

 

Our Marketing team provides lists to our Sales Team who needs to reach out and make phone calls and schedule demos. Right now the activity tracking isn't in one place ( I can pull a Lead or Contact or Opportunity activity and Campaign report), but I need a more cohesive system of tracking so things don't fall off the radar and I can get a full picture of what activities drive our business.

 

I am open to other suggestions, but ideally, I would want any activity on a Lead, Contact, or Opportunity associated with a Campaign to also populate under the "Campaign History" section in additon to the individual record. 

 

Alternatively, another option that is less preferable is to have the Campaign Member status updated based on the activity done on the Lead/Contact/Opp record - i.e. if there is a phone call, change the status to "Call", etc.

 

We are B2B and often provide a company name for our Sales team, but they will add additional Contacts, and those aren't necessarily counted in the campaign... but if I could get the activities from the Opps logged under the campaign, we would have a better idea of what our selling cycle looks like.

 

Does this all make sense?

 

Also, if anyone else runs similar campaigns or has similar challanges and knows of a good way to solve them or help automatically associate Leads/Contact with a campaign, I would love to hear about it.

 

Our marketing team will provide a list to our sales team of company names only and the sales team needs to source the correct people. It's semi-impossible to track these all the way through because of new leads added and I started putting the companies in as Accounts so that any Contacts and Opportunities will be associated but this does not seem ideal.

 

Again, any suggestions of anyone who has found workarounds or apps or codes to help with any of this would be greatly appreciated.

 

I know this is a long post. I am a novice and trying to learn coding but my understanding of coding is very basic right now.

 

Thank you in advance!

 

Danielle

 

 

We have FedEx ZenKraft, and I want the package Delivery Date to update a field on the associated Opportunity.

 

In theory, this seems like it would be very simple to do, but I am very novice at writing any sort of code and still do not understand the commands and formatting yet and it's a frustrating process to go about blindly. Is there someone that can help me with the basic idea of how to do this?

 

Thank you in advance!

I'm trying to create a apex code that will be triggered by a button on the lead/contact page to log an activity. It's currently set up to assign the task to the lead owner, but I'm trying to update the code so that it will assign the task to the current user. I keep running into different errors while I try a bunch of stuff, but I'm having a hard time understanding what I need to do and how I should reference this because I'm a novice updating an existing code. I'm not sure where the "Current User" needs to be defined, and when I've tried I've gotten error message that my value doesn't exist or it works and then when I hit the button I get an error message saying that there are multiple values.

I have been trying to find help online, but, like I said, I'm a beginner and I keep getting lost in the apex language.

Thanks!

Here's the first part of the code -

global class logAttempts {
 
  WebService static String createAttempt(
    String sAttemptType,
    String sCallerType, 
    Id objectId) {
      
      List<Task> lstTasks = new List<Task>();
    
    try {
       
      If (sCallerType == 'Lead') {
        Lead newLead = 
          [Select Id, OwnerId, Status, Lead_Stage__c,
           Title, Email
           from   Lead 
           where  ID = :objectId];


Hi All,

 

I tried reaching out to Salesforce to help on this, and they recommended I try the Developer Board first.

 

Our Marketing team provides lists to our Sales Team who needs to reach out and make phone calls and schedule demos. Right now the activity tracking isn't in one place ( I can pull a Lead or Contact or Opportunity activity and Campaign report), but I need a more cohesive system of tracking so things don't fall off the radar and I can get a full picture of what activities drive our business.

 

I am open to other suggestions, but ideally, I would want any activity on a Lead, Contact, or Opportunity associated with a Campaign to also populate under the "Campaign History" section in additon to the individual record. 

 

Alternatively, another option that is less preferable is to have the Campaign Member status updated based on the activity done on the Lead/Contact/Opp record - i.e. if there is a phone call, change the status to "Call", etc.

 

We are B2B and often provide a company name for our Sales team, but they will add additional Contacts, and those aren't necessarily counted in the campaign... but if I could get the activities from the Opps logged under the campaign, we would have a better idea of what our selling cycle looks like.

 

Does this all make sense?

 

Also, if anyone else runs similar campaigns or has similar challanges and knows of a good way to solve them or help automatically associate Leads/Contact with a campaign, I would love to hear about it.

 

Our marketing team will provide a list to our sales team of company names only and the sales team needs to source the correct people. It's semi-impossible to track these all the way through because of new leads added and I started putting the companies in as Accounts so that any Contacts and Opportunities will be associated but this does not seem ideal.

 

Again, any suggestions of anyone who has found workarounds or apps or codes to help with any of this would be greatly appreciated.

 

I know this is a long post. I am a novice and trying to learn coding but my understanding of coding is very basic right now.

 

Thank you in advance!

 

Danielle

 

 

Hello,

 

I wrote the below trigger. It updates a Lookup field (for a user) on the Opportunity from another related lookup field (user) on a custom child object.

 

I am not getting errors, but the field on the opportunity is not being updated.

 

Can anyone take a look at the code below and let me know what might be happening with it or what I can fix to have the field from the custom child object update the field on the opportunity upon edit (of the child object)

 

Thanks!

 

 

 

 

trigger Update_NHC_SE_Assignment on Network_Health_Check__c (before insert, after update) {

// Update the SE NHC Assignment on Opp based on the SE who delivered the Demo


// Declare the variables

public set<Id> OppIDs = new Set<Id>();
public list<Opportunity> OppsToUpdate = new List<Opportunity>();





// Build the list of Opps to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(Network_Health_Check__c n: Trigger.new){
        if(n.Assigned_SE__r.id != null && n.Name != null){
      
       Opportunity Opp = new Opportunity(Id=n.Related_Opportunity__r.Id, SE_NHC_Assignment__c = n.Assigned_SE__r.Id);update Opp;
     }
    }

if(Trigger.isUpdate){
    for(Network_Health_Check__c n: Trigger.old){
    if(n.Assigned_SE__r.id != null && n.Name != null){

       Opportunity Opp = new Opportunity(Id=n.Related_Opportunity__r.Id, SE_NHC_Assignment__c=n.Assigned_SE__r.Id); update Opp;
     }
    }

}
}
}

Hello,

 

We are implementing Zuora in our Salesforce, and I am trying to get some fields on the related Quote object to roll up to the Opportunity level. I'm running into some challenges doing so, and was hoping that someone would be able to help?

 

There are probably other errors that will pop up once I fix this one, but I'm currently running into the following error:

 

"Didn't understand relationship 'zqu__Quote__c' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' aftger the customer relationship name. Please reference your WSDL or the describe call for the appropraite names"

 

Here is the code as it currently stands, and if someone has insight on edits or knows how to make this work, that would be fantastic.

 

Thanks!

 

trigger OppUpdatefromQuoteObject on zqu__Quote__c (after delete, after insert, after undelete,
after update) {

// // This updates the opportunity with the term and amount information from the quote object

// If related to an Opportunity, query to find out the Opportunity number

public set<Id> OpportunityIDs = new Set<Id>();
public list<Opportunity> OpportunitiesToUpdate = new List<Opportunity>();


// Build the list of Opps to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(zqu__Quote__c q: Trigger.new){
    if(q.zqu__Opportunity__c!=null && string.valueOf(q.zqu__Opportunity__c).startsWith('006'))
    OpportunityIDs.add(q.zqu__Opportunity__r.id );

    }
}

if(Trigger.isDelete || Trigger.isUpdate){
    for(zqu__Quote__c q: Trigger.old){
    if(q.zqu__Opportunity__c!=null && string.valueOf(q.zqu__Opportunity__c).startsWith('006'))
    OpportunityIDs.add(q.zqu__Opportunity__r.id );
    }
}


// Update the Opportunities

if(OpportunityIDs.size()>0){
for(Opportunity o: [Select o.Id, o.amount, o.average_contract_value__c, o.Expected_or_Implied_Term_Months_del__c,
(Select id From zqu__Quote__c where zqu__TCV__c > 0 )
From Opportunity o where zqu__Opportunity__r.Id  in :OpportunityIDs])
OpportunitiesToUpdate.add(new Opportunity(Id=o.Id, zqu__TCV__c = o.amount, zqu__InitialTerm__c = o.Initial_Term_From_Quote__c);
update OpportunitiesToUpdate;
}
if(OpportunitiesToUpdate != null && !OpportunitiesToUpdate.isEmpty())
Database.update(OpportunitiesToUpdate);
}

 

Hello,

 

I created the below trigger to automatically update the discount on the opportunity product to reflect the discount calculated on the opportunity level based on a number of field selections. It is working great until we try and make any kind of mass update, and then I get the following error: System.LimitException: Too many SOQL queries.

 

Below is my code - is anyone able to help me fix it to avoid the Too Many SOQL Queries errors that I'm running into??

 

Thank you!!!!

 

trigger Opp_Line_Item_Update on Opportunity (after update) {
for( Opportunity opp: Trigger.new)
{

List<OpportunityLineItem> lineitem = [ SELECT Id, Opportunity.ID, Discount from
OpportunityLineItem where opportunity.isclosed = false and Opportunity.id = :opp.Id];

List<OpportunityLineItem> lineitemToUpdate = new List<OpportunityLineItem>();

for(OpportunityLineItem thislineitem: lineitem )
{
   if( thislineitem.discount !=  opp.total_extended_discount__c)
   {
       thislineitem.discount =   opp.total_extended_discount__c;
      lineitemToUpdate.add(thislineitem);
   }
}

if( lineitemToUpdate!=null)
{
   update lineitemToUpdate;
}

}
}

 

 

Hello All,

 

I am trying to create a batch job (that I have scheduled to run daily) that copies the value of one fied to another field.

 

I thought I had it up and running, but when I ran a report this morning, it only updated the field for a small handful of opportunities and it should be running on all of them.This is my first batch job, and I have been trying to discern how to write it correctly based on other posted examples in different places. I was wondering if anyone would be able to help?

 

Here's what needs to happen:

  • Essentially, on a daily basis, I want the batch job to run a trigger on all Opportunities to take the value of the "Stage" field and copy the text into a custom field called "Start of Day Stage" (which sounds simple enough...)


Here's my trigger apex code for the update:

 

global class DailyStageUpdateBatch implements Database.batchable<sObject>, Database.Stateful{

global Database.QueryLocator start(Database.BatchableContext bc){

    return database.getQuerylocator('select id,name,stagename from opportunity');
}
    
   global void execute(Database.batchableContext info, List<Opportunity> scope){ 
       List<Opportunity> oppsToUpdate = new List<Opportunity>(); 
       for(Opportunity o : scope){ 
           o.start_of_day_stage__c = o.stagename;
           oppsToUpdate.add(o);
       }
       update oppsToUpdate; 
   }     
   global void finish(Database.batchableContext info){     
   } 
}

 

And here's the code that implements it (that I then have scheduled to run every morning):

 

// APEX to schedule the batch run to update Opportunities to capture the stage at the start of the day.  
//
global class DailyStageCaptureSchedule implements Schedulable{
   global void execute(SchedulableContext sc) {
        DailyStageUpdatebatch batch = new DailyStageUpdatebatch();
      ID batchprocessid = Database.executeBatch(batch); 
   }
}

 

Any thoughts/ideas please and thank you!!

Hello,

 

I have the following trigger and it keeps causing this error: "System.Exception: Too many SOQL queries: 101". Can anyone help me to update this code so that it is not in a loop? I've been trying and struggling with it a bit.

 

Thank you!

 

Danielle

 

 

trigger LeadOppStageName on Task (before insert, before update, after insert){
// Goal: Pull fields from the lead record for tracking activities related to lists and to discern in which lead stages these activities occured

// If related to a Lead, query to find out the Lead ID, Lead Stage, and Lead Source Detail

// Create collection of tasks that are related to an lead (where the lead is listed only once)
    Set<Id> leadIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhoId;
        if(wId!=null && wId.startsWith('00Q') && !leadIds.contains(t.whoId)){
            leadIds.add(t.WhoId);
        }
    }
    // Pull in lead ids and related field to populate task record
    List<Lead> taskLead  = [Select Id, leadsource, lead_source_detail__c, Lead_Stage__c, Lead_Channel__c, Lead_Partner_Program__c, Lead_Segment__c,
    Original_Lead_Channel__c, Original_Lead_Partner_Program__c, Original_Lead_Segment__c from Lead where Id in :leadIds limit 1];
    Map<Id, Lead> leadMap = new Map<Id, Lead>();
    for(Lead l : taskLead){
        leadMap.put(l.Id,l);
    }
    
    // Update custom task field with custom lead field
    for(Task t : trigger.new){
        String wId = t.WhoId;
        if(wId!=null && wId.startswith('00Q')){
           Lead thisLead = leadMap.get(t.WhoId);
            if(thislead!=null){t.Sales_Stage__c = thisLead.Lead_Stage__c;} 
            if(thislead!=null){t.Lead_Source__c = thisLead.LeadSource;}            
            if(thislead!=null){t.record_type__c = 'Lead';}
            if(thislead!=null){t.lead_source_detail__c = thislead.Lead_source_detail__c;}           
            if(thislead!=null){t.Lead_Channel__c = thislead.lead_channel__c;} 
            if(thislead!=null){t.Original_Lead_Channel__c = thislead.original_lead_channel__c;}             
            if(thislead!=null){t.lead_partner_program__c = thislead.lead_partner_program__c;}
            if(thislead!=null){t.Original_lead_partner_program__c = thislead.Original_lead_partner_program__c;} 
            if(thislead!=null){t.lead_segment__c = thislead.lead_segment__c;}
            if(thislead!=null){t.Original_lead_segment__c = thislead.Original_lead_segment__c;}            

}
}
}

Hello,

 

I created apex triggers to pull in information from the related record. I am all set with the leads. However, I have one for Contact and one for Opportunity. I want to Opportunity one to trigger/populate first and then, only if that is empty, to pull in the Contact information as a second step. I have them as two separate triggers, and I'm not sure how to combine them.

 

Could someone please help with figuring out either a) combining these into one to ensure that the order above is correct; or b) let me know if there is a way to have the Contact one trigger after the Opportunity one

 

I am familiar enough with apex that I was able to create these two simple separate ones, but I have no idea how I would make them more advanced to accomplish the above goal.

 

Thank you in advance for any guidance/help that you can give me!

 

Here are my two triggers:

 

Contact:

 

trigger ActivityContactDetails on Task (before insert, before update){
// Goad: Pull fields from the contact record for tracking activities related to lists and to discern in which lead stages these activities occured

// If related to a contact, query to find out the Contact ID, Lead Source, and Lead Source Detail

// Create collection of tasks that are related to an contact (where the contact is listed only once)
    Set<Id> contactIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhoId;
        if(wId!=null && wId.startsWith('003') && !contactIds.contains(t.whoId)){
            contactIds.add(t.WhoId);
        }
    }
    // Pull in contact ids and related field to populate task record
    List<contact> taskContact = [Select Id, leadsource, lead_source_detail__c from Contact where Id in :ContactIds];
    Map<Id, Contact> contactMap = new Map<Id, contact>();
    for(Contact c : taskContact){
        contactMap.put(c.Id,c);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new)
    if(t.what.id == null){
        String wId = t.WhoId;
        if(wId!=null && wId.startswith('003')){
           Contact thisContact = contactMap.get(t.WhoId);
            if(thiscontact!=null){t.Lead_Source__c = thisContact.LeadSource;} 
            if(thiscontact!=null){t.Sales_Stage__c = 'Existing Contact';}
            if(thiscontact!=null){t.Record_Type__c = 'Contact';} 
            if(thiscontact!=null){t.lead_source_detail__c = thiscontact.Lead_source_detail__c;} 
        }
    }
}

Opportunity:

 

trigger ActivityOppStageName on Task (before insert, before update){
// Goad: Pull fields from the lead and opportunity record for tracking activities related to lists and to discern in which lead/opp stages these activities occured

// If related to an Opportunity, query to find out the Opportunity number

// Create collection of tasks that are related to an opp (where the opp is listed only once)
    Set<Id> opIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startsWith('006') && !opIds.contains(t.WhatId)){
            opIds.add(t.WhatId);
        }
    }
    // Pull in opp ids and related field to populate task record
    List<Opportunity> taskOps = [Select Id, leadsource, lead_source_detail__c, StageName from Opportunity where Id in :opIds];
    Map<Id, Opportunity> opMap = new Map<Id, Opportunity>();
    for(Opportunity o : taskOps){
        opMap.put(o.Id,o);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startswith('006')){
            Opportunity thisOp = opMap.get(t.WhatId);
            if(thisOp!=null){t.Sales_Stage__c = thisOp.StageName;} 
            if(thisOp!=null){t.Lead_source__c = thisOp.LeadSource;}
            if(thisOp!=null){t.record_type__c = 'Opportunity';}
            if(thisOp!=null){t.lead_source_detail__c = thisOp.Lead_source_detail__c;} 
        }
    }
}

I am trying to create apex code that will capture either the Lead or Opportunity stage when an associated activity is created or completed.

 

In other words, when someone makes a phone call, I want that activity record to pull in the lead stage at that moment in time so that we can help track leads and activities throughout their lifecycle. Additionally, when an activity is logged on the opportunity, I would like the same thing... essentially, I can then pull activities and what stages they were completed.

 

Any help or other ideas people have around this would be hugely appreciated!

 

Thanks!

Good day, 

 

I trying to create a trigger which intend to update oppty field if contact role are inserted, and noticed that we can't create a trigger for OpportunityContactRole object, and worst, the opportunity trigger seem do not trigger on update when new contact role record are created, but noticed lastmodifiedDate is changed on opportunity.

 

I would appreciated if someone point out if i wrong in understanding this limitation and possible state any mistake of the trigger as well (I'm newbie of SFDC)

 

trigger MycontactRoleTrigger on Opportunity (before update) {
	
List<OpportunityContactRole> opptyContactRoleList= [SELECT contact.name, 
ContactId, Id, CreatedById, CreatedDate, IsDeleted, LastModifiedById, LastModifiedDate, 
OpportunityId, IsPrimary, Role, SystemModstamp FROM OpportunityContactRole 
WHERE OpportunityId IN :trigger.newmap.keyset() ];
									
System.debug('opptyContactRoleList list = '+opptyContactRoleList);									
	

if(trigger.isBefore){			
			for(Opportunity oppty : trigger.new){
				if(al.StringUtils.isBlank(oppty.contactPersonName__C) )){
					for(OpportunityContactRole ocr :opptyContactRoleList){
						if(al.StringUtils.equalsIgnoreCase(oppty.id,ocr.OpportunityId)){							
							oppty.contactPersonName__C 	 = ocr.contact.name;							
							break;
						}
					}
				}
			}
		}
	
	}