• LBarton
  • NEWBIE
  • 55 Points
  • Member since 2009

  • Chatter
    Feed
  • 1
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 16
    Questions
  • 35
    Replies
I have a custom field in Accounts which keeps track of the opportunities it has. when I update one opportunity it works correctly.  When I update severa opportunties at once, then the custom account field does not get updated although the opportunities themselves are correctly updated. the custom field is AC_Marketing_Category__c.  I think it has to do with the account lists, but I am not sure how to change them.
 
try{
    //the trigger will update the account's Accelero Connect Category field
    
    if (! trigger.isDelete) {
    
      List<Id> oppIds = new List<Id>() ;
      List<Id> AccountIds = new List<Id>() ;
      List<Account> AcctToUpdate = new List<Account>() ;
            
            for (opportunity op : trigger.New)
        {
        oppIds.add(op.Id);
         AccountIds.add(op.AccountId);
        } 
    
      Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select id, StageName from Opportunity where Accountid in :AccountIDs and name = 'Accelero Connect' and Status__c != 'Inactive']) ;   
          Map<Id,Account> acctMap = new Map<Id,Account>([select id, AC_Marketing_Category__c, name, Closed_Won_Opps__c, Type from Account where id in :AccountIDs]);
                
      for (opportunity op : trigger.New){

        //Find the account for this opportunity which is being updated
        Account oAccount =  acctMap.get(op.AccountId);
        Opportunity ACOpportunity = oppMap.get(op.Id);
    
    string stagelist;
    
          if (oppMap.isEmpty()){  //No AC opportunities
        if (oAccount.Closed_Won_Opps__c == 0 ) {
          oAccount.AC_Marketing_Category__c = 5;
        }
        else {
          oAccount.AC_Marketing_Category__c = 4;
        }
        
          }
          else { //There are ACopportunities so see how many of them are closed/won
            Integer iCountClosedWon = 0;
            
          for(Opportunity acMap: oppMap.values()){       
          if (acMap.StageName == 'Closed Won') {
            iCountClosedWon += 1;
          }           
          }     
            
            if (iCountClosedWon > 0) {
          oAccount.AC_Marketing_Category__c = 1;
            }
            else {
              if (oAccount.Closed_Won_Opps__c == 0){
                oAccount.AC_Marketing_Category__c = 3;
            //update oAccount;   
              }
              else {
                 oAccount.AC_Marketing_Category__c = 2;
              }
              
            }
          }
        
          AcctToUpdate.add(oAccount);
        }
        update AcctToUpdate;
    }




 
I am creating a trigger on Opportunity which will do the following according to the stage it is in. It will update the contact custom fields for all those who have a contact-role for the opportunity. thanks for any advice and help!

II the opportunity stage is prospecting or qualification, then do nothing.

If the Opportunity stage is Needs Analysis, Values Proposition, Perception Analysis , or Negotiation Review, 
but the status is not Open4.
then add the name of the opportunity to the custom field MQL__c in Contact (If the name is not already listed there in a semicolon delimited list.)

If the Opportunity is Closed-won, then add the name of the opportunity to the custom field Customer__c in Contact. (If the name is not already listed there in a semicolon delimited list.)

What I have so far will only add the opportunity name to the  MQL__c field, but I would have to remove the name, for instance, if the stage changes to closed-won from Negotiation review.
I also have not taken care of closed-won opportunities.

I am not sure that the opportunity name will be correct. All I am using is oOppName = o.Opportunity__c; I probably need to do something different from that.
//This trigger will update the custom lifecycle stages fields on the contacts who have a contact-role for this opportunity
	if (!trigger.isDelete) {
	        	    
       		set<Id> ContactIDs = new set<Id>();
       		set<Id> oppIds = new set<Id>();
       		List<Contact> ContactToUpdate = new List<Contact>() ;     
       		string oOppName = '';
       		                
            for(opportunity o:trigger.new){
                oppIds.add(o.Id);
                
                oOppName = o.Opportunity__c;
                
                try {
       				OpportunityContactRole contactRole = [select ContactId, OpportunityID from OpportunityContactRole where OpportunityId IN :oppIds];
       				if (contactRole != null) {
       					ContactIDs.add(contactRole.ContactId);
       				}
                }
                catch (Exception e){
                	OpportunityContactRole contactRole = new OpportunityContactRole();
                }
       			
            }
            for(Contact oc:[select MQL__c,
                             (
                             select stagename,opportunity__c from opportunities 
                             where stageName IN ('needs analysis', 'negotiation/review','perception analysis','value proposition')                             
                             and Id IN :oppIds
                             ) 
                           from Contact 
                           where Id IN :ContactIDs])
            {
                string oOppList = '';
                Contact oContact = new Contact();
                oContact = oc;
             	
             	if (oContact.MQL__c != null) {
             		oOppList = oContact.MQL__c;
             	}
                if(oOpplist.contains(oOppname)==false){ 
					oOpplist = oOpplist + ';' +  oOppname;
                }
				
        		oContact.MQL__c = oOpplist;
        		ContactToUpdate.add(oContact);
        		
        		if (ContactToUpdate.size() > 0){
        			update ContactToUpdate;
        		}
        			
            }            
       		
	}

 
I have created a trigger which works to avoid duplicate contacts and leads (by email address).I tried typing in an already-existing email address and got an error message.  However, a few duplicates have cropped up.  Our company is using a program called HubSpot. If names are uploaded from HubSpot to SF, would that bypass the trigger?  I think that is what is happening, but am not sure.

 
I have a rather simple trigger. It updates a custom Account field when the opportunity is updated. I don't know why I get an error about a CPU time limit?

"Apex trigger: UpdateLateStageOppField caused an unexpected exception. SystemLimitException: Apex CPU time limit exceeded. "

When you answer this please, could you actually type in some coding changes?  I hardly use Apex and am really not familiar with it. General advice won't be sufficient. Thanks for your help!

trigger UpdateLateStageOppField on Opportunity (after delete, after insert, after update) {

try{
    //the trigger will update the account's SAM Marketing Customer field
    //and also the Late_Stage_Opps__c, too
   
    if (! trigger.isDelete) {
   
   List<Id> oppIds = new List<Id>() ;
   List<Id> AccountIds = new List<Id>() ;
   List<Account> AcctToUpdate = new List<Account>() ;
  
            for (opportunity op : trigger.New)
      {
    oppIds.add(op.Id);
       AccountIds.add(op.AccountId);
      }
  
      Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type from Account where id in :AccountIDs]);
   Map<Id,Opportunity> oppMap2 = new Map<Id,Opportunity>([Select id, StageName, Opportunity__c from Opportunity where Accountid in :AccountIDs]) ;    
      
      for (opportunity op : trigger.New){

        //Find the account for this opportunity which is being update
        Account oAccount =  acctMap.get(op.AccountId);
  Opportunity StageOpportunities = oppMap2.get(op.Id);
 
  string stagelist;
         stagelist = '';
         if (oppMap2.isEmpty()){  //No opportunities for that account
    stagelist = '';
         }
         else {
          stagelist = '';
          System.debug('In Else StageList ');
          for (Opportunity stageMap: oppMap2.values()) {
           system.debug ('Oppor. ' + StageMap.Opportunity__c);
        if (stageMap.StageName=='Closed Won' || stageMap.StageName=='Negotiation/Review' || stageMap.StageName=='Perception Analysis' || stageMap.StageName=='Value Proposition'){
      stagelist +=  stageMap.Opportunity__c + ',';
        }
          }
   
         }
         oAccount.Late_Stage_Opps__c = stagelist;         
         AcctToUpdate.add(oAccount);
       }
       update AcctToUpdate;
   }

if (trigger.isDelete) {
   
   
   List<Id> oppIds = new List<Id>() ;
   List<Id> AccountIds = new List<Id>() ;
   List<Account> AcctToUpdate = new List<Account>() ;
  
            for (opportunity op : trigger.Old)
      {
    oppIds.add(op.Id);
       AccountIds.add(op.AccountId);
      }
  
   Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type from Account where id in :AccountIDs]);
   Map<Id,Opportunity> oppMap2 = new Map<Id,Opportunity>([Select id, StageName, Opportunity__c from Opportunity where Accountid in :AccountIDs]) ;    
      
      for (opportunity op : trigger.Old){

        //Find the account for this opportunity which is being update
        Account oAccount =  acctMap.get(op.AccountId);
        //Opportunity SamOpportunity = oppMap.get(op.Id);
  Opportunity StageOpportunities = oppMap2.get(op.Id);
 
  string stagelist;
       
         if (oppMap2.isEmpty()){  //No opportunities for that account
    stagelist = '';
         }
         else {
          stagelist = '';
           System.debug('in stage list');
          for (Opportunity stageMap: oppMap2.values()) {
            System.debug('in values list');
        if (stageMap.StageName=='Closed Won' || stageMap.StageName=='Negotiation/Review' || stageMap.StageName=='Perception Analysis' || stageMap.StageName=='Value Proposition'){
      stagelist +=  stageMap.Opportunity__c + ',';
        }
          }
   
         }
         oAccount.Late_Stage_Opps__c = stagelist;     
         AcctToUpdate.add(oAccount);
       }

     update AcctToUpdate;   
   }
}
catch (Exception e ){
            System.debug('Create customer field trigger exception ' + e.getMessage());
           
      }
}



I think I have done all I can to "bulkify" this trigger but if I update 200 opportunities at once then I get the error about too many SOQL queries. I can't see anything more I need to do for this trigger. What else is there to do?

trigger Update_Sam_Marketing_Customer_Field on Opportunity (after insert, after update, after delete) {

try{
    //the trigger will update the account's SAM Marketing Customer field
    if (! trigger.isDelete) {
    
  List<Id> oppIds = new List<Id>() ;
  List<Id> AccountIds = new List<Id>() ;
  List<Account> AcctToUpdate = new List<Account>() ;
     
      for (opportunity op : trigger.New){
        oppIds.add(op.Id);
        AccountIds.add(op.AccountId);
        
  Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select id, StageName from Opportunity where id in :oppIds and
   name = 'Security Audit Manager'and Status__c != 'Inactive']) ;   
    
  Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type 
   from Account where id in :AccountIDs]);
  
        //Find the account for this opportunity which is being updated
        Account oAccount =  acctMap.get(op.AccountId);
        Opportunity SamOpportunity = oppMap.get(op.Id);

         if (oppMap.isEmpty()){  //No SAM opportunities
    if (oAccount.Closed_Won_Opps__c == 0 && SamOpportunity.StageName != 'Closed Won') {
     oAccount.SAM_Marketing_Customer__c = 5;
    }
    else {
     oAccount.SAM_Marketing_Customer__c = 4;
    }
    AcctToUpdate.add(oAccount);
         }
         else { //There are SAM opportunities so see how many of them are closed/won
          Integer iCountClosedWon = 0;
          
      for(Opportunity samMap: oppMap.values()){       
     if (samMap.StageName == 'Closed Won') {
      iCountClosedWon += 1;
     }      
      }   
          
          if (iCountClosedWon > 0) {
     oAccount.SAM_Marketing_Customer__c = 1;
          }
          else {
           if (oAccount.Closed_Won_Opps__c == 0){
            oAccount.SAM_Marketing_Customer__c = 3;
      //update oAccount;  
           }
           else {
             oAccount.SAM_Marketing_Customer__c = 2;
           }
           
          }
          AcctToUpdate.add(oAccount);
         }
       }
       update AcctToUpdate;
   }
 
 if (trigger.isDelete) {
    
  List<Id> oppIds = new List<Id>() ;
  List<Id> AccountIds = new List<Id>() ;
  List<Account> AcctToUpdate = new List<Account>() ;
    
     for (opportunity op : trigger.Old){
        oppIds.add(op.Id);
        AccountIds.add(op.AccountId);
        
  Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select id, StageName from Opportunity where id in :oppIds and
   name = 'Security Audit Manager'and Status__c != 'Inactive']) ;   
    
  Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type 
   from Account where id in :AccountIDs]);
  
        //Find the account for this opportunity which is being updated
        Account oAccount =  acctMap.get(op.AccountId);
        Opportunity SamOpportunity = oppMap.get(op.Id);

         if (oppMap.isEmpty()){  //No SAM opportunities
    if (oAccount.Closed_Won_Opps__c == 0 && SamOpportunity.StageName != 'Closed Won') {
     oAccount.SAM_Marketing_Customer__c = 5;
    }
    else {
     oAccount.SAM_Marketing_Customer__c = 4;
    }
    AcctToUpdate.add(oAccount);
         }
         else { //There are SAM opportunities so see how many of them are closed/won
          Integer iCountClosedWon = 0;
          
      for(Opportunity samMap: oppMap.values()){       
     if (samMap.StageName == 'Closed Won') {
      iCountClosedWon += 1;
     }      
      }   
          
          if (iCountClosedWon > 0) {
     oAccount.SAM_Marketing_Customer__c = 1;
          }
          else {
           if (oAccount.Closed_Won_Opps__c == 0){
            oAccount.SAM_Marketing_Customer__c = 3;
      //update oAccount;  
           }
           else {
             oAccount.SAM_Marketing_Customer__c = 2;
           }
          }
          AcctToUpdate.add(oAccount);
         }
     }
     update AcctToUpdate;    
   }
}
catch (Exception e ){
            System.debug('Create customer field trigger exception ' + e.getMessage());
            
      }
 }


I am getting an error
System.Exception: Too many SOQL queries: 101


I have the followiing trigger which I am attempting to change to avoid that error message. 

I have tried using a keyset with this but it has not worked out yet. The tricky part is that I am updating an opportunity from a task, and there are also triggers on opportunities.

trigger UpdateLatestDueDatefromTask on Task (after insert, after update) {


try{
    //the trigger will update the opportunity's latest_open_due_date__c field
    for (task ta : trigger.new){
        id Opportunityid = ta.WhatId;
        
        Opportunity oOpportunity = [select id, Latest_Open_Due_Date__c from Opportunity where id = :Opportunityid LIMIT 1];
        if (oOpportunity.Latest_Open_Due_Date__c <  ta.ActivityDate ) {
        	if (ta.Status != 'Completed' ) {
        		System.debug ('in completed');
        		oOpportunity.Latest_Open_Due_Date__c = ta.ActivityDate;
            	//update oOpportunity;
        	}
        }
        
        if (oOpportunity.Latest_Open_Due_Date__c == null) {
        	if (ta.Status != 'Completed'  ) {
        		oOpportunity.Latest_Open_Due_Date__c = ta.ActivityDate;
            	//update oOpportunity;
        	}
        }
        
       List <Task> ActiveTask = [select id, WhatId from Task where Whatid = :Opportunityid and status != 'Completed'];
          
        	if (ActiveTask.isEmpty()){
        	 	oOpportunity.Latest_Open_Due_Date__c = null;
             	///update oOpportunity;
        	}
    	update oOpportunity;
    }
}
catch (Exception e ){
            System.debug('Create trigger exception ' + e.getMessage());
            
      }
 }


THIS IS AMONG THE THINGS I HAVE BEEN TRYING:

trigger UpdateLatestDueDatefromTask on Task (after insert, after update) {

  //the trigger will update the opportunity's latest_open_due_date__c field
    for (task ta : trigger.new){
	try{    	
     List<Opportunity> updateOpportunities = new list<Opportunity>();
     
     List <Tasks> OpportunitiesWithTasks = [select id, ActivityDate, WhatId, (Select id, Latest_Open_due_Date__c from Opportunity) from Task 
     	Where Id in :Trigger.newMap.keySet()];
     for (Opportunity oOpportunity: [select id, WhatId, ActivityDate from Opportunity where id in :Trigger.NewMap.keySet()] ) {
			list <Opportunity> parentOpp = [select id, Latest_Open_Due_Date__c From Opportunity where id in :Trigger.NewMap.get (oTask.WhatId)];
			if (parentOpp.Latest_Open_Due_Date__c < oTask.WhatId) {
				parentOpp.Latest_Open_Due_Date__c = oTask.ActivityDate;
				
			}
    }
}

(The error I get is that it doesn't understand the relationship for opportunity.)

THANKS!


Apex Tests are running in our production environment just fine and they all pass.  However, in the Test Sandbox nothing is happening. I select tests and all the tests remain at queued without any results for pass or fail. what can i do to get the tests running in the Sandbox. They used to run just as well as they do now in the Production version.

I want to avoid contacts from having the same email address as a lead except in the situation where a user is manually converting a lead.  I have modified the cookbook code used to avoid duplicates and tried adding

 

if (lead.IsConverted == false )

 

However, this is not doing what I want.  Evidently it is seeing if the lead has been converted but not if it is currently abut to be converted. Thanks for your help!  Here is the code:

 

 

trigger

PreventDuplicateContact onContact (beforeinsert, beforeupdate) {

 

  Try {

   Map<String,

Contact> contactMap = new Map<String, Contact>();

   

for (Contact contact : System.Trigger.new)  {

       

       

// Make sure we don't treat an email address that 

       

// isn't changing during an update as a duplicate.

   

       

if ((contact.Email != null) &&

                (System.Trigger.isInsert ||

                (contact.Email !=

                    System.Trigger.oldMap.

get(contact.Id).Email))) {

       

           

// Make sure another new contact isn't also a duplicate 

   

           

if (contactMap.containsKey(contact.Email)) {

                contact.Email.addError(

'A record with this email address already exists as a Lead or Contact.');

            }

           

else {

                contactMap.put(contact.Email, contact);

            }

       }

    }

   

   

// Using a single database query, find all the contacts in 

   

// the database that have the same email address as any 

       

// of the contacts being inserted or updated. 

   

   

for (Contact contact : [SELECT Email FROM contact

                     

WHERE Email IN :contactMap.KeySet()]) {

       

Contact newContact = contactMap.get(contact.Email);

        newContact.Email.addError(

'A record with this email address already exists as a Lead or Contact.');

    }

   

for (Lead lead : [SELECT Email FROMLead

                    

WHERE Email IN :contactMap.KeySet()]) {

      

if (lead.IsConverted == false ) {

           

Contact newContact = contactMap.get(lead.Email);

            newContact.Email.addError(

'A record with this email address already exists as a Lead or Contact.');

       }

    } 

       

   

  }

 

catch (exception e){

  } 

 

}

I want to add a campaign to an opportunity and not have it be the  Primary Campaign source.  How do I do that?  I tried this in VB.NET

          

Dim oSFOpportunity As sForce.Opportunity = oQR.records(0)

            oSFOpportunity.CampaignId = SCampaignID

            oSFOpportunity.Campaign_Primary__c = Nothing

I see the new campaign linked to the Opportunity, but marked as Primary.  What should I do?

There is a section under the Opportunity called Campaign Influence.  I can't find a table with that name!  I want to uncheck the Primary Campaign Source checkbox programatically.  Does anyone know where that field is coming from?  Which table and what exactly is the field called?

 

Thanks!

 

 

I can't deploy my trigger because there is an error in an Apex class and its corresponding test class. Actually it may just be in the test class.  In fact, I can't deploy anything but I want to change the test class so that it won't get an error!

 

I have been using the Eclpse IDE to deploy.  This really isn't a matter of deploying from the "sandbox" to the Production environment since this already exits in Production.  I am not sure where to begin.

Is there any way to send an outbound message for objects such as OpportunityLineItem or OpportunityContactRole?  I want to update local tables whenever those objects are created or modified but I can't find those listed when I try to create a new outbound message.  Is there a workaround for that so that local datatables can be populated with SalesForce data?

 

 

I have created a SF web service that will add tasks (specifically email messages) to the proper places such as the Accounts or Opportunities that the user has selected.  I have one problem.  In the Comments field, the message is in HTML so it looks strange.  I want just text but can't seem to find out how to get it to look at way.  Here is an example:

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div>This is a test message.&nbsp; Test again.</div>
<div>&nbsp;</div>
<div>Lynne</div>
</body>
</html>

My outboundmessage is going as far as the message queue and then there is an error:

 

'org.xml.sax.SAXException: Bad envelope tag: html'

 

I have a web service written in C# but I can't tell what is wrong because I can't step through it.  I have created a little WinForm app to test just that part of it and it succeeds.  I know the SQL stored proc in SQL Server works because I tested that part and the snippet of code I used based on the web service worksl, also. 

 

Is there any way to find out what has gone wrong by getting a more detailed error message or step through the web service somehow?

I am not sure how to get an identity field to work in a function in an apex class.  I have:

 

public void UpdateSupportFields(ID OpportunityID, string SupportConsultant, string OppStatus ......[other fields])

 

 Opportunity[] op=[SELECT ID, Support_Consultant__c, ...., Support_EXT_Name_Test__c, Support_Network__c,  Support_Last_Update_Live__c, Support_Last_Update_Test__c from Opportunity Where ID= :OpportunityID LIMIT 1];

 

 

//this next part is always 0 even if I have a valid Opportunity.ID


        System.debug('Opsize: ' + op.size());

        if (op.size() > 0)

 

When I use  a test method on this, I have the following:

 

   id MyID =  '0068000000OyuwjAAB';   

        mySupportUpdate.UpdateSupportFields(myID, 'Mr. SupportConsultant', 'Cancelled', MyDate , MyDate , MyDate , .....) ;

Can I have an ID field like the above or is there something else the matter?  I just want to be able to have the selection be for the Opportunity ID I pass into the function.  Thanks!  I just can't get rows when testing.

 

 

I go to Setup/Develop/Apex Classes and there is no "New" button.  I have permissions as an Apex Author (and am a system administrator).  I can't figure out why I can't create classes.  Thanks!

 

Apex Tests are running in our production environment just fine and they all pass.  However, in the Test Sandbox nothing is happening. I select tests and all the tests remain at queued without any results for pass or fail. what can i do to get the tests running in the Sandbox. They used to run just as well as they do now in the Production version.

I can't deploy my trigger because there is an error in an Apex class and its corresponding test class. Actually it may just be in the test class.  In fact, I can't deploy anything but I want to change the test class so that it won't get an error!

 

I have been using the Eclpse IDE to deploy.  This really isn't a matter of deploying from the "sandbox" to the Production environment since this already exits in Production.  I am not sure where to begin.

I have a custom field in Accounts which keeps track of the opportunities it has. when I update one opportunity it works correctly.  When I update severa opportunties at once, then the custom account field does not get updated although the opportunities themselves are correctly updated. the custom field is AC_Marketing_Category__c.  I think it has to do with the account lists, but I am not sure how to change them.
 
try{
    //the trigger will update the account's Accelero Connect Category field
    
    if (! trigger.isDelete) {
    
      List<Id> oppIds = new List<Id>() ;
      List<Id> AccountIds = new List<Id>() ;
      List<Account> AcctToUpdate = new List<Account>() ;
            
            for (opportunity op : trigger.New)
        {
        oppIds.add(op.Id);
         AccountIds.add(op.AccountId);
        } 
    
      Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select id, StageName from Opportunity where Accountid in :AccountIDs and name = 'Accelero Connect' and Status__c != 'Inactive']) ;   
          Map<Id,Account> acctMap = new Map<Id,Account>([select id, AC_Marketing_Category__c, name, Closed_Won_Opps__c, Type from Account where id in :AccountIDs]);
                
      for (opportunity op : trigger.New){

        //Find the account for this opportunity which is being updated
        Account oAccount =  acctMap.get(op.AccountId);
        Opportunity ACOpportunity = oppMap.get(op.Id);
    
    string stagelist;
    
          if (oppMap.isEmpty()){  //No AC opportunities
        if (oAccount.Closed_Won_Opps__c == 0 ) {
          oAccount.AC_Marketing_Category__c = 5;
        }
        else {
          oAccount.AC_Marketing_Category__c = 4;
        }
        
          }
          else { //There are ACopportunities so see how many of them are closed/won
            Integer iCountClosedWon = 0;
            
          for(Opportunity acMap: oppMap.values()){       
          if (acMap.StageName == 'Closed Won') {
            iCountClosedWon += 1;
          }           
          }     
            
            if (iCountClosedWon > 0) {
          oAccount.AC_Marketing_Category__c = 1;
            }
            else {
              if (oAccount.Closed_Won_Opps__c == 0){
                oAccount.AC_Marketing_Category__c = 3;
            //update oAccount;   
              }
              else {
                 oAccount.AC_Marketing_Category__c = 2;
              }
              
            }
          }
        
          AcctToUpdate.add(oAccount);
        }
        update AcctToUpdate;
    }




 
I am creating a trigger on Opportunity which will do the following according to the stage it is in. It will update the contact custom fields for all those who have a contact-role for the opportunity. thanks for any advice and help!

II the opportunity stage is prospecting or qualification, then do nothing.

If the Opportunity stage is Needs Analysis, Values Proposition, Perception Analysis , or Negotiation Review, 
but the status is not Open4.
then add the name of the opportunity to the custom field MQL__c in Contact (If the name is not already listed there in a semicolon delimited list.)

If the Opportunity is Closed-won, then add the name of the opportunity to the custom field Customer__c in Contact. (If the name is not already listed there in a semicolon delimited list.)

What I have so far will only add the opportunity name to the  MQL__c field, but I would have to remove the name, for instance, if the stage changes to closed-won from Negotiation review.
I also have not taken care of closed-won opportunities.

I am not sure that the opportunity name will be correct. All I am using is oOppName = o.Opportunity__c; I probably need to do something different from that.
//This trigger will update the custom lifecycle stages fields on the contacts who have a contact-role for this opportunity
	if (!trigger.isDelete) {
	        	    
       		set<Id> ContactIDs = new set<Id>();
       		set<Id> oppIds = new set<Id>();
       		List<Contact> ContactToUpdate = new List<Contact>() ;     
       		string oOppName = '';
       		                
            for(opportunity o:trigger.new){
                oppIds.add(o.Id);
                
                oOppName = o.Opportunity__c;
                
                try {
       				OpportunityContactRole contactRole = [select ContactId, OpportunityID from OpportunityContactRole where OpportunityId IN :oppIds];
       				if (contactRole != null) {
       					ContactIDs.add(contactRole.ContactId);
       				}
                }
                catch (Exception e){
                	OpportunityContactRole contactRole = new OpportunityContactRole();
                }
       			
            }
            for(Contact oc:[select MQL__c,
                             (
                             select stagename,opportunity__c from opportunities 
                             where stageName IN ('needs analysis', 'negotiation/review','perception analysis','value proposition')                             
                             and Id IN :oppIds
                             ) 
                           from Contact 
                           where Id IN :ContactIDs])
            {
                string oOppList = '';
                Contact oContact = new Contact();
                oContact = oc;
             	
             	if (oContact.MQL__c != null) {
             		oOppList = oContact.MQL__c;
             	}
                if(oOpplist.contains(oOppname)==false){ 
					oOpplist = oOpplist + ';' +  oOppname;
                }
				
        		oContact.MQL__c = oOpplist;
        		ContactToUpdate.add(oContact);
        		
        		if (ContactToUpdate.size() > 0){
        			update ContactToUpdate;
        		}
        			
            }            
       		
	}

 
I have created a trigger which works to avoid duplicate contacts and leads (by email address).I tried typing in an already-existing email address and got an error message.  However, a few duplicates have cropped up.  Our company is using a program called HubSpot. If names are uploaded from HubSpot to SF, would that bypass the trigger?  I think that is what is happening, but am not sure.

 
I have a rather simple trigger. It updates a custom Account field when the opportunity is updated. I don't know why I get an error about a CPU time limit?

"Apex trigger: UpdateLateStageOppField caused an unexpected exception. SystemLimitException: Apex CPU time limit exceeded. "

When you answer this please, could you actually type in some coding changes?  I hardly use Apex and am really not familiar with it. General advice won't be sufficient. Thanks for your help!

trigger UpdateLateStageOppField on Opportunity (after delete, after insert, after update) {

try{
    //the trigger will update the account's SAM Marketing Customer field
    //and also the Late_Stage_Opps__c, too
   
    if (! trigger.isDelete) {
   
   List<Id> oppIds = new List<Id>() ;
   List<Id> AccountIds = new List<Id>() ;
   List<Account> AcctToUpdate = new List<Account>() ;
  
            for (opportunity op : trigger.New)
      {
    oppIds.add(op.Id);
       AccountIds.add(op.AccountId);
      }
  
      Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type from Account where id in :AccountIDs]);
   Map<Id,Opportunity> oppMap2 = new Map<Id,Opportunity>([Select id, StageName, Opportunity__c from Opportunity where Accountid in :AccountIDs]) ;    
      
      for (opportunity op : trigger.New){

        //Find the account for this opportunity which is being update
        Account oAccount =  acctMap.get(op.AccountId);
  Opportunity StageOpportunities = oppMap2.get(op.Id);
 
  string stagelist;
         stagelist = '';
         if (oppMap2.isEmpty()){  //No opportunities for that account
    stagelist = '';
         }
         else {
          stagelist = '';
          System.debug('In Else StageList ');
          for (Opportunity stageMap: oppMap2.values()) {
           system.debug ('Oppor. ' + StageMap.Opportunity__c);
        if (stageMap.StageName=='Closed Won' || stageMap.StageName=='Negotiation/Review' || stageMap.StageName=='Perception Analysis' || stageMap.StageName=='Value Proposition'){
      stagelist +=  stageMap.Opportunity__c + ',';
        }
          }
   
         }
         oAccount.Late_Stage_Opps__c = stagelist;         
         AcctToUpdate.add(oAccount);
       }
       update AcctToUpdate;
   }

if (trigger.isDelete) {
   
   
   List<Id> oppIds = new List<Id>() ;
   List<Id> AccountIds = new List<Id>() ;
   List<Account> AcctToUpdate = new List<Account>() ;
  
            for (opportunity op : trigger.Old)
      {
    oppIds.add(op.Id);
       AccountIds.add(op.AccountId);
      }
  
   Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type from Account where id in :AccountIDs]);
   Map<Id,Opportunity> oppMap2 = new Map<Id,Opportunity>([Select id, StageName, Opportunity__c from Opportunity where Accountid in :AccountIDs]) ;    
      
      for (opportunity op : trigger.Old){

        //Find the account for this opportunity which is being update
        Account oAccount =  acctMap.get(op.AccountId);
        //Opportunity SamOpportunity = oppMap.get(op.Id);
  Opportunity StageOpportunities = oppMap2.get(op.Id);
 
  string stagelist;
       
         if (oppMap2.isEmpty()){  //No opportunities for that account
    stagelist = '';
         }
         else {
          stagelist = '';
           System.debug('in stage list');
          for (Opportunity stageMap: oppMap2.values()) {
            System.debug('in values list');
        if (stageMap.StageName=='Closed Won' || stageMap.StageName=='Negotiation/Review' || stageMap.StageName=='Perception Analysis' || stageMap.StageName=='Value Proposition'){
      stagelist +=  stageMap.Opportunity__c + ',';
        }
          }
   
         }
         oAccount.Late_Stage_Opps__c = stagelist;     
         AcctToUpdate.add(oAccount);
       }

     update AcctToUpdate;   
   }
}
catch (Exception e ){
            System.debug('Create customer field trigger exception ' + e.getMessage());
           
      }
}



I am getting an error
System.Exception: Too many SOQL queries: 101


I have the followiing trigger which I am attempting to change to avoid that error message. 

I have tried using a keyset with this but it has not worked out yet. The tricky part is that I am updating an opportunity from a task, and there are also triggers on opportunities.

trigger UpdateLatestDueDatefromTask on Task (after insert, after update) {


try{
    //the trigger will update the opportunity's latest_open_due_date__c field
    for (task ta : trigger.new){
        id Opportunityid = ta.WhatId;
        
        Opportunity oOpportunity = [select id, Latest_Open_Due_Date__c from Opportunity where id = :Opportunityid LIMIT 1];
        if (oOpportunity.Latest_Open_Due_Date__c <  ta.ActivityDate ) {
        	if (ta.Status != 'Completed' ) {
        		System.debug ('in completed');
        		oOpportunity.Latest_Open_Due_Date__c = ta.ActivityDate;
            	//update oOpportunity;
        	}
        }
        
        if (oOpportunity.Latest_Open_Due_Date__c == null) {
        	if (ta.Status != 'Completed'  ) {
        		oOpportunity.Latest_Open_Due_Date__c = ta.ActivityDate;
            	//update oOpportunity;
        	}
        }
        
       List <Task> ActiveTask = [select id, WhatId from Task where Whatid = :Opportunityid and status != 'Completed'];
          
        	if (ActiveTask.isEmpty()){
        	 	oOpportunity.Latest_Open_Due_Date__c = null;
             	///update oOpportunity;
        	}
    	update oOpportunity;
    }
}
catch (Exception e ){
            System.debug('Create trigger exception ' + e.getMessage());
            
      }
 }


THIS IS AMONG THE THINGS I HAVE BEEN TRYING:

trigger UpdateLatestDueDatefromTask on Task (after insert, after update) {

  //the trigger will update the opportunity's latest_open_due_date__c field
    for (task ta : trigger.new){
	try{    	
     List<Opportunity> updateOpportunities = new list<Opportunity>();
     
     List <Tasks> OpportunitiesWithTasks = [select id, ActivityDate, WhatId, (Select id, Latest_Open_due_Date__c from Opportunity) from Task 
     	Where Id in :Trigger.newMap.keySet()];
     for (Opportunity oOpportunity: [select id, WhatId, ActivityDate from Opportunity where id in :Trigger.NewMap.keySet()] ) {
			list <Opportunity> parentOpp = [select id, Latest_Open_Due_Date__c From Opportunity where id in :Trigger.NewMap.get (oTask.WhatId)];
			if (parentOpp.Latest_Open_Due_Date__c < oTask.WhatId) {
				parentOpp.Latest_Open_Due_Date__c = oTask.ActivityDate;
				
			}
    }
}

(The error I get is that it doesn't understand the relationship for opportunity.)

THANKS!


Apex Tests are running in our production environment just fine and they all pass.  However, in the Test Sandbox nothing is happening. I select tests and all the tests remain at queued without any results for pass or fail. what can i do to get the tests running in the Sandbox. They used to run just as well as they do now in the Production version.
Hi experts,
I found a Salesforce object named OpportunityContactRole by using the IDE (Eclipse) and I want to add a new trigger for this object but I got the following Error message when try to save the new created trigger:
    Save error: SObject type does not allow triggers: OpportunityContactRole
I really need to add the special processing to this object before updating, do any experts have any idea how to fix this issue?
Best regards!
Boi Hue


Message Edited by boihue on 12-09-2008 11:02 AM

Message Edited by boihue on 12-09-2008 11:02 AM
  • December 09, 2008
  • Like
  • 0