Question

apex trigger governor error

Asked by: mn10191b

I am new to Apex and not a developer for quite awhile.  A trigger works well until in production it hits governor error.  Please help.

trigger trg_OpportunityClone on Opportunity (after insert)
{
  set<String> stateRecords = new set<String>();
  map<String, list<Dodge_State__c>> dodgeRecordMap = new map<String, list<Dodge_State__c>>();
  list<Dodge_State__c> dodgeList = new list<Dodge_State__c>();
  CLS_OpportunityClone obj_CLS_OpportunityClone = new CLS_OpportunityClone();
  if(triggerrecursionPrevention.getVal() == false)
  {
    triggerrecursionPrevention.setVal();
    if(trigger.isAfter && trigger.isInsert)
    {
      if(trigger.new!=trigger.old)
      {
        RecordType recType = [Select SobjectType, Name, Id From RecordType where SobjectType = 'Opportunity' and Name = 'MHC Dodge Project' limit 1];
        System.debug('>>>>>>>>'+recType);
        for(Opportunity o: trigger.new)
        {
          stateRecords.add(o.MHC1__State__c);
        }
        list<Dodge_State__c> dodgeStateRecords = new list<Dodge_State__c>([Select Name, Id, IsPartner__c, Assigned_User__c From Dodge_State__c where Name in : stateRecords]);
        
        for(String s : stateRecords)
        {
          String stateName = s;
          for(Integer i=0;i<dodgeStateRecords.size();i++)
          {
            if(stateName == dodgeStateRecords.get(i).Name)
            {
              dodgeList.add(dodgeStateRecords.get(i));
            }
          }
          dodgeRecordMap.put(stateName, dodgeList);
          dodgeList = new list<Dodge_State__c>();
        }
        System.debug('TheDodge Record Map>>'+dodgeRecordMap);
        for(Opportunity o : trigger.new)
        {
          if(o.RecordTypeId == recType.Id)
          {
            list<Dodge_State__c> tempDodgeRecords = dodgeRecordMap.get(o.MHC1__State__c);
            System.debug('Dodge Records----->>>'+tempDodgeRecords);
            obj_CLS_OpportunityClone.createOpportunity(o, tempDodgeRecords);
          }
        }
      }
    }
  }
}
 
 
 
public class CLS_OpportunityClone
{
  public void createOpportunity(Opportunity Opp, list<Dodge_State__c> dodgeStateList)
  {
    list<Opportunity> oppRecordsInsert = new list<Opportunity>();
    list<MHC1__Project_Bidder__c> ProjBinderInsert = new list<MHC1__Project_Bidder__c>();
    list<MHC1__Project_Firm__c> ProjFirmInsert = new list<MHC1__Project_Firm__c>();
    
    Opportunity Oppty = new Opportunity(Id=Opp.Id);
    
    for(Integer i=0;i<dodgeStateList.size();i++)
    {
      
      if(dodgeStateList.get(i).IsPartner__c == true)
      { 
        Opportunity opportunityRecord = Opp.clone(false,true);
        opportunityRecord.OwnerId = dodgeStateList.get(i).Assigned_User__c;  
        oppRecordsInsert.add(opportunityRecord);      
      }
      else
      {
        Oppty.OwnerId = dodgeStateList.get(i).Assigned_User__c;
      }
      System.debug('<<<<Opportunity records>>>>>'+oppRecordsInsert);
    }
    
    if(oppRecordsInsert.size()>0)
    {
      insert oppRecordsInsert;
      System.debug('#########Inserted Opportunity records>>>>>>'+oppRecordsInsert);
      if(oppRecordsInsert.size() == 1)
      {
        Oppty.Partner_Opportunity_cloned_ID_1__c = oppRecordsInsert[0].Id;
      }
      if(oppRecordsInsert.size() == 2)
      {
        Oppty.Partner_Opportunity_cloned_ID_1__c = oppRecordsInsert[0].Id;
        Oppty.Partner_Opportunity_cloned_ID_2__c = oppRecordsInsert[1].Id;
      }
      if(oppRecordsInsert.size() >= 3)
      {
        Oppty.Partner_Opportunity_cloned_ID_1__c = oppRecordsInsert[0].Id;
        Oppty.Partner_Opportunity_cloned_ID_2__c = oppRecordsInsert[1].Id;
        Oppty.Partner_Opportunity_cloned_ID_3__c = oppRecordsInsert[2].Id;
      }
      
      update Oppty;
    }
    list<MHC1__Project_Bidder__c> projectBinderRecords = new list<MHC1__Project_Bidder__c>([Select Name, MHC1__Type__c, MHC1__Trade__c, MHC1__Sub_Project_Code__c, MHC1__Sub_Project_2__c, MHC1__Opportunity__c, MHC1__Low_Bidder__c, MHC1__Contact__c, MHC1__Bidder__c, MHC1__Bid_Withdrawn__c, MHC1__Bid_Awarded__c, MHC1__Bid_Amount__c, CurrencyIsoCode, ConnectionSentId, ConnectionReceivedId From MHC1__Project_Bidder__c where MHC1__Opportunity__c =: Opp.Id]);
    list<MHC1__Project_Firm__c> projectFirmRecords = new list<MHC1__Project_Firm__c>([Select Name, MHC1__Project_Opportunity__c, MHC1__Project_Firm__c, MHC1__Firm_Role__c, MHC1__Contact__c, MHC1__Awarded__c, CurrencyIsoCode, ConnectionSentId, ConnectionReceivedId From MHC1__Project_Firm__c where MHC1__Project_Opportunity__c =: Opp.Id]);
    for(Integer i=0;i<oppRecordsInsert.size();i++)
    {
      if(projectBinderRecords.size()>0)
      {
        for(Integer j=0;j<projectBinderRecords.size();j++)
        {
          MHC1__Project_Bidder__c ProjBinder = projectBinderRecords.get(j).clone(false,true);
          ProjBinder.MHC1__Opportunity__c = oppRecordsInsert.get(i).Id;
          ProjBinderInsert.add(ProjBinder);
        }
      }
      if(projectFirmRecords.size()>0)
      {
        for(Integer k=0;k<projectFirmRecords.size();k++)
        {
          MHC1__Project_Firm__c ProjFirm = projectFirmRecords.get(k).clone(false,true);
          ProjFirm.MHC1__Project_Opportunity__c = oppRecordsInsert.get(i).Id;
          ProjFirmInsert.add(ProjFirm);
        }
      }       
    }
    if(ProjBinderInsert.size()>0)
    {
      insert ProjBinderInsert;
    }  
    if(ProjFirmInsert.size()>0)
    {
      insert ProjFirmInsert;
    }
  }
  
  public static testmethod void test_OpportunityTrigger()
  {
    RecordType recType = [Select SobjectType, Name, Id From RecordType where SobjectType = 'Opportunity' and Name = 'MHC Dodge Project'];
    Account acc = [Select Id from Account limit 1];
    Opportunity opp = new Opportunity(AccountId = acc.Id, MHC1__State__c = 'AL', RecordTypeId = recType.Id, name='testOpp', stageName='Open',CloseDate=Date.newInstance(2000,08,10), Type='New Customer');
    insert opp;
    /*MHC1__Project_Bidder__c ProBidder = new MHC1__Project_Bidder__c(Name='test', MHC1__Opportunity__c = opp.Id);
    insert ProBidder;
    MHC1__Project_Firm__c projFirm = new MHC1__Project_Firm__c(Name = 'test', MHC1__Project_Opportunity__c = opp.Id);
    insert projFirm;*/
  }
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-07 at 17:45:30ID24794547
Tags

Salesforce.com

Topic

CRM Software

Participating Experts
2
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Sorting in Apex TrueDB Grid
    I can't seem to find a way to sort the Apex grid when the user clicks on the column. In the help file, the only sort it shows is by using their XArray object, binding the grid to the XArray then on the column_click you sort the XArray (not the grid itself). We are using the...
  2. QUERY GOVERNOR COST LIMIT
    I have a SQL database that gets hit with pre-built procs for reporting and also ad-hoc queries built by users. I have come across some debate regarding the QUERY GOVERNOR COST LIMIT. Does the default value of 0 allow queires to run as long as they need to? TIA, D...
  3. APEX
    How do you chanage the font color in APEX?
  4. APEX
    Hi Experts, I'm still kind of new working with apex, and I would like to know how can I grab the user information once they are logged into the apex application. The Application is using LDAP single sign on.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Bill-HansonPosted on 2009-10-08 at 07:18:51ID: 25525673

Without seeing the error message, it's kind of hard to pin-point, but I'm guessing you are hitting either the 20 DML/SOQL query limit or the 1,000 SOQL result limit.

Placing DML/SOQL in a loop always presents this type of problem.  The solution is usually to use SOQL For-Loops (see apex documentation) or to combine multiple DML/SOQL calls into a single statement.

Sometimes, I'll loop over records and cache any data I need into a Map keyed by record Id.  Then, I use this cached data to build a large DML/SOQL statement that returns all data for all records, which I then store in another Map (also keyed by record Id.)  Then, I loop over both maps, joining the data as needed by the class.  Sometimes I can keep my code down to a single select statement per object type doing it this way.

Please post the specific error message and I may be able to provide a better answer.

 

by: mn10191bPosted on 2009-10-13 at 10:59:13ID: 25562451

Thanks for your input Bill-Hanson.  Here is the error message.

Apex script unhandled trigger exception by user/organization: 00580000001sEnb/00D00000000hZKZ

trg_OpportunityClone: execution of AfterInsert

caused by: System.Exception: Too many SOQL queries: 21

Class.CLS_OpportunityClone.createOpportunity: line 49, column 90
Trigger.trg_OpportunityClone: line 42, column 7


I did not write the code but I need to fix the error.  Please help.

 

by: mn10191bPosted on 2009-10-15 at 14:20:03ID: 25585030

Bill-Hanson may help me.  He may not pay attention to my new post.

 

by: techhealthPosted on 2009-10-19 at 07:57:32ID: 25605721

Just a final effort to help...
Your trigger calls createOpportunity for each of the Opportunity in the trigger record set.  The method potentially makes 4 to 6 SOQL DML calls (your SELECT into Lists, and your insert statements) on each invocation.  That runs up against your 20 SOQL limit per trigger run pretty quickly.

I think a solution would be to use child relationship in SOQL to retrieve all project_firm and project_bidder info on ALL your opportunities in the triggering record set all at once into one giant list, process them, then update the giant list all at once.  That way you deal with the record limit per trigger (1,000), not the smaller 20 per trigger SOQL query count.  If the trigger is the result of a Web services API batch, the record limit is actually a much higher 20,000.  Or you can make the limit rise from 1,000 to 10,000 for visual interface invocation by using async APEX.

 

by: Bill-HansonPosted on 2009-10-20 at 09:09:18ID: 25615576

I appologize for the late reply.

The error is definietly caused by the select statements.  The only way to solve this is to reduce the number of SELECT statements.  You'll need to reorganize your code so that your lookups are not in a loop.  Here's a snippet of code that shows what I mean.

Lines 3-10: Build a list of ids for all the opportunities that I need to process.

Lines 13-14: Lookup all related records that my script will need.  Notice that this is not in a loop so there is only 1 call for all opportunities rather than 1 call per opportunity.

Lines 16-25: Puts all line item records into a Map keyed by OpportunityId so I can easily retrieve them later in the code.

The next step would be to loop over the Trigger.new records (newRecords in the example below), and use lineItemMap to get related line items rather than SOQL.

You'll need to model this same idea in your code.

public static void run(Opportunity[] newRecords, Map<Id,sObject> oldRecords) {
	
	// build a list of ids for opportunities that need updating
	Set<String> recordsToProcess = new Set<String>();
  for (Opportunity newRecord : newRecords) {
		if (opptyNeedsUpdate(newRecord)) {
			recordsToProcess.add(newRecord.Id);
		}
  }
  if (recordsToProcess.size() == 0) return;
  
  // build a map of all line items for opportunities that need updating
  Map<String, List<OpportunityLineItem>> lineItemMap = new Map<String, List<OpportunityLineItem>>();
  List<OpportunityLineItem> allLineItems = [select Id,PricebookEntryId,Brand__c,UnitPrice,Cost_of_Goods__c from OpportunityLineItem where OpportunityId in :recordsToProcess];
  
  for (OpportunityLineItem lineItem : allLineItems) {
		List<OpportunityLineItem> lineItems;
		if (lineItemMap.containsKey(lineItem.Id)) {
			lineItems = lineItemMap.get(lineItem.Id);
		} else {
			lineItems = new List<OpportunityLineItem>();
		}
		lineItems.add(lineItem);
		lineItemMap.put(lineItem.Id, lineItems);
  }
	
	

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...