Error out of bound assignment to a list

Sorry, we do not have specific information about your error. There are several resources that can help you find a solution:

There is no help page available for this error

Sorry, we do not have specific information about your error. There are several resources that can help you find a solution:

Related Maplesoft Help Pages

  • 4 Basic Data Structures
    Contents Previous Next Index 4 Basic Data Structures The appropriate use of data
    structures is an important part of writing efficient programs. Maple provides various
  • 5 Maple Statements
    Contents Previous Next Index 5 Maple Statements 5.1 In This Chapter Introduction
    Expression Statements Assignments Flow Control The use Statement Other Statements
  • array
    array create an array Calling Sequence Parameters Description Thread Safety Examples
    Calling Sequence array( indexfcn , bounds , list ) array( a ) Parameters indexfcn

Related Posts & Questions on MaplePrimes

  • Error, out of bound assignment to a list — MaplePrimes
    Dec 19, 2017 Question:Error, out of bound assignment to a list … Hello,. I need to construct a sequence of matrices of different sizes, but with similar …
  • Error, out of bound assignment to a list — MaplePrimes
    Jul 20, 2009 Question:Error, out of bound assignment to a list … code for 4 iterations (i am defining this in fourth line) everything is going fine but …
  • Questions — MaplePrimes
    I have a simple proc that generates some arrays based in some input values. … Error, (in f) out of bound assignment to a list. f := proc(i) local A; …

Other Resources

  • Review the Error Message Guide Overview
  • Frequently Asked Questions
  • Contact Maplesoft Technical Support
  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • ‘Late-bound assignment’ error

  1. Mar 1st, 2013, 08:01 AM


    #1

    jakeelsley96 is offline

    Thread Starter


    New Member


    ‘Late-bound assignment’ error

    Hello,

    I am trying to program a VB console application for an A level assignment, but I am facing this error when adding a value (the athlete’s name) to the array.

    The error that is displayed is: «Late-bound assignment to a field of value type ‘StructureTable’ is not valid when ‘StructureTable’ is the result of a late-bound expression.»

    StructureTable being my structure that lists the array’s structure.

    I am using Visual Studio 2010, and am coding a console application.

    Any help would be greatly appreciated as I have no understanding of this error.

    Thank you,

    Jake

    Here is my code so far:

    Code:

        
    Option Explicit On
    Module Module1
        Structure StructureTable
            Dim NameOfAthlete As String
            Dim TimeOne As Integer
            Dim TimeTwo As Integer
            Dim TimeThree As Integer
            Dim TimeFour As Integer
        End Structure
    
    
        Sub Main()
            Dim Array(4) As StructureTable
            Console.WriteLine("Athlete Speeds")
            Console.WriteLine()
    
            Dim ArrayNames(4) As String
            ArrayNames(0) = "first"
            ArrayNames(1) = "second"
            ArrayNames(2) = "third"
            ArrayNames(3) = "fourth"
            ArrayNames(4) = "fifth"
    
            Athletes(Array, ArrayNames)
    
    
    End Sub
        Sub Athletes(Array, ArrayName)
    
            Dim x = 0
            Do
                Dim xx = 0
                Console.WriteLine("Please enter the name of the " & ArrayName(xx) & " athlete: ")
                Array(x).NameOfAthlete = Console.ReadLine
                Console.WriteLine()
                Console.WriteLine("Please enter " & Array(x).Name & "'s " & ArrayName(xx) & " speed")
                Console.WriteLine("Example: 0510")
                Array(x).TimeOne = Console.ReadLine
                Console.WriteLine()
                xx = xx + 1
                Console.WriteLine("Please enter " & Array(x).Name & "'s " & ArrayName(xx) & " speed")
                Console.WriteLine("Example: 0510")
                Array(x).TimeOne = Console.ReadLine
                Console.WriteLine()
                xx = xx + 1
                Console.WriteLine("Please enter " & Array(x).Name & "'s " & ArrayName(xx) & " speed")
                Console.WriteLine("Example: 0510")
                Array(x).TimeOne = Console.ReadLine
                Console.WriteLine()
                xx = xx + 1
                Console.WriteLine("Please enter " & Array(x).Name & "'s " & ArrayName(xx) & " speed")
                Console.WriteLine("Example: 0510")
                Array(x).TimeOne = Console.ReadLine
                Console.WriteLine()
                xx = xx + 1
                Console.WriteLine("Please enter " & Array(x).Name & "'s " & ArrayName(xx) & " speed")
                Console.WriteLine("Example: 0510")
                Array(x).TimeOne = Console.ReadLine
                Console.WriteLine()
                xx = xx + 1
            Loop
        End Sub
    End Module


  2. Mar 1st, 2013, 09:37 AM


    #2

    Re: ‘Late-bound assignment’ error

    Hi Jake,

    If this is ‘A’ level then either your Tutors need shooting or your previous Curriculum needs ripping up and throwing in the bin!

    I am sorry to say that this is a bit of a horrible mess.

    So, LESSON 1, TURN Option Strict ON. This is then going to give you 19 compilation errors which all need to be looked at by highlighting the error and seeing what the IDE is telling you about the issue with each line. The first line that will be causing an error will be this one:-

    Code:

    Sub Athletes(Array, ArrayName)

    This should then give you a steer as to what you need to do to ultimately solve your issue.

    If, after turning Option Strict On and trying to sort the issues you still get errors then please post back and we will help you further.

    LESSON 2:-
    1) You must ensure that you do not use Variable names that are EXISTING KEYWORDS/FUNCTIONS/CLASS names within the .NET or VB language since at some point in your learning you are going to «fall on your face» due to conflict issues. As an example consider your variables called «Array», this is an existing Class name within .NET.

    2) To ensure that you can read your own code coherently you must always remember to give your variable objects Descriptive names to describe what those objects are being used for. Consider the following example. What makes more sense to you and what would you remember better in the future:-

    This statement:-

    Code:

    Dim Array(4) as StructureTable

    or this statement:-

    Code:

    Dim  SchoolAthletes(4) as AthleteInformation

    Hope that helps.

    Cheers,

    Ian


  3. Mar 1st, 2013, 12:28 PM


    #3

    Re: ‘Late-bound assignment’ error

    If this is ‘A’ level then either your Tutors need shooting or your previous Curriculum needs ripping up and throwing in the bin!

    It’ll be one of these new fangled A-Levels where you get the marks for doing something not for doing it right, no doubt. The teacher will probably have got their degree in forestry, done a quick PGCE, arrived at the school to find that the computer expert has been eaten by his 3rd years and there’s nobody able to replace him, and, being in no position to argue, got thrown in at the deep end. Cynical, moi?

    As the 6-dimensional mathematics professor said to the brain surgeon, «It ain’t Rocket Science!»

    Reviews: «dunfiddlin likes his DataTables» — jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!


  4. Mar 1st, 2013, 06:05 PM


    #4

    jakeelsley96 is offline

    Thread Starter


    New Member


    Re: ‘Late-bound assignment’ error

    Hello Ian,

    I am afraid to say that my tutor had to idea how to solve this! I believe he studied Mechanics or something similar, as he teaches design work as well. IT I believe is his second calling.

    We’ve only been taught the basic Option Explicit, so that’s new to me but I will try that and post back if get stuck. Thank you for your kind offer.

    That is a good point, I will use more friendlier names in the future. Definitely the latter one.

    @dunfiddlin.. Well… you are kind of right. We have a test (I’m studying Computer Science) where about 30/40% is programming, and the rest is computing questions. One of the largely marked questions was a simple If statement question….

    Thank you for your help and time,

    Jake.


  5. Mar 1st, 2013, 07:42 PM


    #5

    jakeelsley96 is offline

    Thread Starter


    New Member


    Re: ‘Late-bound assignment’ error

    Hello Ian,

    I’ve reorganised the code, and now I’m getting this error:

    Structure ‘Athletes.Module1.AthleteStructureTable’ cannot be indexed because it has no default property

    There is another error with the calling of the sub routine, which can be initially resolved by moving the calling of the sub to after the sub has been declared, but then I get a -1 dimensional error.

    This is probably a simple error, or bad coding style, but here’s the stripped down code:

    Thank you for your time and help,

    Jake

    Code:

    Option Strict On
    Module Module1
        Structure AthleteStructureTable
            Dim NameOfAthlete As String
            Dim TimeOne As Integer
            Dim TimeTwo As Integer
            Dim TimeThree As Integer
            Dim TimeFour As Integer
        End Structure
        Sub Main()
            Console.WriteLine("Athlete Speeds")
            Console.WriteLine()
            InputAthletes(AthleteData, LoopNames)
        End Sub
        Sub DeclaredItems()
            Dim AthleteData(4) As AthleteStructureTable
            Dim LoopNames(4) As String
            LoopNames(0) = "first"
            LoopNames(1) = "second"
            LoopNames(2) = "third"
            LoopNames(3) = "fourth"
            LoopNames(4) = "fifth"
    
        End Sub
        Sub InputAthletes(ByRef AthleteData As AthleteStructureTable, ByVal LoopNames As String)
            Do
                Dim xx = 0
                Console.WriteLine("Please enter the name of the " & LoopNames(xx) & " athlete: ")
                AthleteData() = Console.ReadLine
            Loop
        End Sub
    End Module


  6. Mar 2nd, 2013, 05:20 AM


    #6

    Re: ‘Late-bound assignment’ error

    Hi Jake,

    Why students are given Tutors that have no idea what they are doing just amazes me and it is no wonder you are struggling to understand what is going on. Well done, by the way, in keeping Option Strict On and using descriptive variables. At least this shows you are listening, even if you do not fully understand what is going on at the moment.

    LESSON 3 — Variable Scope.
    When you declare variables you have to consider the SCOPE of the variable. That is, where it can be used and what objects can see that variable. If you declare a variable at the Module level then this variable is exposed to all the subroutines and functions within the module. However, when you declare variables at the Subroutine level then those variables are ONLY exposed to the code contained within that Subroutine unless you pass them elsewhere as a parameter. So in your code you have:-

    Code:

    Sub DeclaredItems()
      Dim AthleteData(4) As AthleteStructureTable
      Dim LoopNames(4) As String
      LoopNames(0) = "first"
      LoopNames(1) = "second"
      LoopNames(2) = "third"
      LoopNames(3) = "fourth"
      LoopNames(4) = "fifth"
    End Sub

    Which you then try and use in the Sub Main routine by calling:-

    Code:

    InputAthletes(AthleteData, LoopNames)

    However, this is incorrect since the variables declared with the Sub DeclareItems are only exposed to code elements within that Subroutine and not outside that subroutine. You therefore need to declare these variables in your Sub Main and get rid of the DeclaredItems subroutine altogether.

    LESSON 4 — Passing Parameters.

    When passing parameters to variables in a subroutine you have to ensure that the variable in the subroutine is of EXACTLY the same type as the parameter being passed to it. I know this sub:-

    Code:

    Sub InputAthletes(ByRef AthleteData As AthleteStructureTable, ByVal LoopNames As String)

    May look right but it is not. You are passing 2 array variables here and yet your sub is expecting 2 variables which are NOT arrays due to the missing brackets. This should be:-

    Code:

    Sub InputAthletes(ByRef AthleteData() As AthleteStructureTable, ByVal LoopNames() As String)

    Also, you should only ever pass variables ByRef if there is a specific need to do so. Do you know the difference between ByVal and ByRef?

    LESSON 5 — Loops.
    There are two basic types of loops in programming. The first type is where you know the EXACT number of times you need to loop (iterate) through something and the second is where you do not know the exact number of times to iterate through something.

    When you know the exact number of times that something needs be iterated then you would always user a FOR … NEXT or a FOR EACH … NEXT loop.

    When you DO NOT know the exact number of times that something needs be iterated then there are various loops that can be used, being:-

    1) Do … Loop Until <condition>
    2) Do Until <condition> … Loop
    3) Do While <condition> … Loop
    4) While <condition> … End While

    In the first example the loop would always occur AT LEAST once but in the other 3 the loops may NEVER occur based on the value of the set condition.

    In your code you have:-

    Code:

    Do
      Dim xx = 0
      Console.WriteLine("Please enter the name of the " & LoopNames(xx) & " athlete: ")
      AthleteData() = Console.ReadLine
    Loop

    1) Based on what you know now, what is wrong with xx as a variable name?
    2) Since you DIM your xx variable within the loop it’s SCOPE is only within the loop but more importantly it is RESET to 0 for each iteration of the loop so you will ALWAYS only be able to set element 0 of your AthleteData array. You need to DIM the xx variable outside of the loop and then INCREMENT that variable by 1 AFTER you have got the name of each Athlete with the ReadLine statement.
    3) Your Do loop will NEVER END since it is not testing for any condition to end the loop. If you have followed point 2 above then this should be:-

    Code:

    Do
    'Your code here ...
    Loop Until xx = 5

    In your case you should actually be using a FOR … NEXT loop since you know exactly how many iterations you need to make to get the 5 Athlete names.

    LESSON 6 — Adding Information to Variable of type Structure.
    In your loop you say this:-

    Code:

    AthleteData() = Console.ReadLine

    Firstly, do not forget that AthleteData is an Array so you must always specify the INDEX of the array element to be interacted with.

    Secondly, AthleteData is of Type AthleteStructureTable which contains the variable names to be assigned values so you CANNOT say AthleteData() =Anything since you have to specify the variable to be used. This should be:-

    Code:

    AthleteData(xx).NameOfAthlete = Console.ReadLine

    I think that is everything, so good luck and hope it helps.

    Cheers,

    Ian


  7. Mar 2nd, 2013, 01:04 PM


    #7

    jakeelsley96 is offline

    Thread Starter


    New Member


    Re: ‘Late-bound assignment’ error

    Hello Ian,

    Thank you for your very helpful information — you are an amazing help!

    «1) Based on what you know now, what is wrong with xx as a variable name?» Would that be that this name could easily become confusing? In the code, I have now changed it to NameCounter.

    So when passing arrays, do I use the brackets, and then, when passing a variable, just the variable name?

    I’m not entirely sure about ByVal and ByRef, but from what I’ve read ByRef is when you are calling something, and ByVal is when you want to change the contents of something? I figured it would be ByVal as I wanted to write data to the array.

    The problem I’m facing now is the calling of the Sub Routine. Normally I would just use Subname(parameters), but when I do this I get this appear:

    Code:

    InputAthletes(AthleteData:= )

    I’ve seen this ‘:=’ before, but have not been sure how to overcome it. I tried adding the Structure type, but that then flagged up more errors.

    I really appreciate you educating me with this.

    Here is my code so far:

    Thank you,

    Jake

    Code:

    Option Strict On
    Module Module1
        Structure AthleteStructureTable
            Dim NameOfAthlete As String
            Dim TimeOne As Integer
            Dim TimeTwo As Integer
            Dim TimeThree As Integer
            Dim TimeFour As Integer
        End Structure
        Sub Main()
            Console.WriteLine("Athlete Speeds")
            Console.WriteLine()
    
            InputAthletes(AthleteData:= )
    
            Dim AthleteData(4) As AthleteStructureTable
            Dim LoopNames(4) As String
            LoopNames(0) = "first"
            LoopNames(1) = "second"
            LoopNames(2) = "third"
            LoopNames(3) = "fourth"
            LoopNames(4) = "fifth"
        End Sub
    
        Sub InputAthletes(ByVal AthleteData() As AthleteStructureTable, ByVal LoopNames() As String)
            Dim NameCounter = 0
            Do
                Console.WriteLine("Please enter the name of the " & LoopNames(NameCounter) & " athlete: ")
                AthleteData(NameCounter).NameOfAthlete = Console.ReadLine
                NameCounter = NameCounter + 1
            Loop Until NameCounter = 4
        End Sub
    End Module


  8. Mar 2nd, 2013, 01:15 PM


    #8

    Re: ‘Late-bound assignment’ error

    As you have declared …

    Sub InputAthletes(ByVal AthleteData() As AthleteStructureTable, ByVal LoopNames() As String)

    … the call to this sub expects you to pass values to it, ie. an array of AthleteStructureTable and another of String. But this isn’t possible because you haven’t actually declared instances of either until after this call is made.

    So …
    Dim AthleteDataActual(4) As AthleteStructureTable
    Dim LoopNamesActual(4) As String
    InputAthletes(AthleteDataActual, LoopNamesActual)

    As a matter of style (and sometimes of error avoidance) it is best not to name variables the same as the generic placeholders in a Sub definition which is why I have changed the names in this example.

    As the 6-dimensional mathematics professor said to the brain surgeon, «It ain’t Rocket Science!»

    Reviews: «dunfiddlin likes his DataTables» — jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!


  9. Mar 2nd, 2013, 01:36 PM


    #9

    jakeelsley96 is offline

    Thread Starter


    New Member


    Re: ‘Late-bound assignment’ error

    Hello Dunfiddlin,

    Ahh, that seems so obvious when you lay it out like that. Thank you!

    That part of the code is now working brilliantly.

    Cheers,

    Jake


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • ‘Late-bound assignment’ error


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range.  

Python Indexerror: list assignment index out of range Example

If ‘fruits’ is a list, fruits=[‘Apple’,’ Banana’,’ Guava’]and you try to modify fruits[5] then you will get an index error since the length of fruits list=3 which is less than index asked to modify for which is 5.

Python3

fruits = ['Apple', 'Banana', 'Guava']  

print("Type is", type(fruits))  

fruits[5] = 'Mango'

Output:

Traceback (most recent call last):
 File "/example.py", line 3, in <module>
   fruits[5]='Mango'
IndexError: list assignment index out of range

So, as you can see in the above example, we get an error when we try to modify an index that is not present in the list of fruits.

Python Indexerror: list assignment index out of range Solution

Method 1: Using insert() function

The insert(index, element) function takes two arguments, index and element, and adds a new element at the specified index.

Let’s see how you can add Mango to the list of fruits on index 1.

Python3

fruits = ['Apple', 'Banana', 'Guava']

print("Original list:", fruits)

fruits.insert(1, "Mango")

print("Modified list:", fruits)

Output:

Original list: ['Apple', 'Banana', 'Guava']
Modified list: ['Apple', 'Mango', 'Banana', 'Guava']

It is necessary to specify the index in the insert(index, element) function, otherwise, you will an error that the insert(index, element) function needed two arguments.

Method 2: Using append()

The append(element) function takes one argument element and adds a new element at the end of the list.

Let’s see how you can add Mango to the end of the list using the append(element) function.

Python3

fruits = ['Apple', 'Banana', 'Guava']

print("Original list:", fruits)

fruits.append("Mango")

print("Modified list:", fruits)

Output:

Original list: ['Apple', 'Banana', 'Guava']
Modified list: ['Apple', 'Banana', 'Guava', 'Mango']

Apex errors happen to anyone developing code on Salesforce. You can be an admin trying to troubleshoot something, a junior developer tackling a new task for the first time, or a seasoned developer trying to figure out some legacy code. Regardless, you will run into Apex errors from time to time. Here are some common errors and their root causes:

1. Attempt to de-reference a null object

This Apex error is a big one that comes up in all sorts of scenarios. It simply something is returning null! This could be an sObject, a variable, a data class, or a set but something is not being defined or returned properly. For example:

String nullString;
nullString = nullString.capitalize();

Will return this error. The issue here is the nullString is declared as a variable, but never initialized. When calling the capitalize() method, there is nothing for the method to perform its operation on, returning the error.

Because Apex will not allow you to use an undefined variable, one of your existing variables is either not being initialized properly or it is the return value of a method that is not returning what you expect. For example:

DOM.Document doc = new DOM.Document();
dom.XmlNode rootNode = doc.createRootElement('Envelope', 'namespace', 'soapenv');
String message = rootNode.getChildElement('Body', 'diffnamespace').getText();

Will also return the error. The part here that is null is the getChildEleent() return value, so when you call getText() on it, it is trying to preform it on a null value. More complex or custom methods may not have robust handling of null return and parameter values, so they need to be scrutinized when you encounter this error.

2. List has no rows for assignment to sObject

You will see this Apex error when a SOQL query assigning the value of a single sObject is not returning a value. Double-check what your SOQL criteria is and make sure it is logical. If it is and you are still seeing this error, try running the query in real-time using the developer console. If this is not returning records, you’ll have to edit your criteria or figure out why a record you expect to be there is not.

To prevent this error from happening in the first place, it is possible to always assign your SOQL query results to a list of the sObject you are expecting to get back. A list can accept query results that are empty. Then, simply check if your list is not empty and you can then use the value in the list for whatever you needed it for:

List<Account> emptyList = [SELECT Id FROM Account WHERE Type = 'Non-Account'];
if(emptyList.size() > 0){
	//condition if true
}

3. List index out of bounds: [n]

You will see this Apex error if you are trying to access a list index that is outside the indices of that list. For example:

List<Account> accountList = [Select Id FROM Account LIMIT 1];
Account outOfBounds = accountList[1];

In this example, the list accountList only has one value, the value at index 0. By then trying to access the value at index 1, we get the error that this is out of bounds.

In cases where this error is not as obvious, double-check your variables that are accessing indices and make sure they are not accessing something that does not exist. Similarly, if you are accessing indices you do expect to exist, check out the lists themselves. They may be empty or they may not have the correct number of elements in them, for various reasons. You can also use the list method list.size() to determine how many indices are in the list itself.

Also, the [n] in the error is the index you are trying to reference that does not exist. This is a handy indicator of the error’s location. If you are using a variable to access an index, you will know what value it throws the error. If it is being called discretely, you will know what line to look at in your code.

4. Invalid index at id [n]: null

I was working on debugging some code once and I ran into the above Apex error. It was stumping me for a while because I was checking to make sure records existed, could be queried, etc., but the culprit was something I had simply overlooked. I had no ID to work with! Take a look at the following code:

Opportunity oppNotInserted = new Opportunity();
delete oppNotInserted;

The code I was looking at was essentially adding an object to a list that was being deleted, but the object had not been inserted yet. There’s nothing to delete using that command in the database if it was never inserted in the first place. If I similarly tried to update it without inserting:

Opportunity oppNotInserted = new Opportunity();
update oppNotInserted;

The error ‘Id not specified in update call‘ is returned. Either of these errors mean you are trying to make a DML statement on something that is not yet a record.

5. SObject row was retrieved via SOQL without querying the requested field: [field]

This is a simple Apex error to resolve. The issue here is I made a query to get an sObject and it referenced a field that was not explicitly called in the query. For example:

Account queriedAccount = [SELECT Id FROM Account LIMIT 1];
String accountName = queriedAccount.Name;

Will result in this error. The issue here is the queriedAccount sObject was retrieved without including the field ‘Name.’ If you see this error, simply add the missing field to the query in question. Also, only include fields you need in the query! You are retrieving this record for a reason, so make sure you only get the information you need.

6. Method does not exist or incorrect signature: [method]

This Apex error occurs when you reference a method incorrectly. It can be a little frustrating at first, but once you understand how to troubleshoot it, it is simple to solve.

Look at the reference in the error and ask yourself the following:

  1. Did I include the correct number of parameters?
  2. Are the parameters the right type?
  3. Does the object/type method I am calling exist?
  4. Does the method I am calling exist in the class in a static context?

The error has to lie in one of these areas. If you are calling an error you see in documentation, like Salesforce standard methods, double-check that you are calling the method on the right class/type/object. If this is an error you are seeing with a custom method, confirm you are calling the right class and your types are correct.

Also, if you update existing code, you will need to update all the areas (including test classes) that reference the code you changed. This may seem obvious, but it helps to think simply when troubleshooting.

7. Recursive Trigger Error

You will encounter this Apex error when you have a recursive trigger situation. Recursive triggers occur when a trigger on Object A makes an update to Object B. Object B then has its own trigger that makes an update to Object A. This will trigger Object A’s trigger again and repeat into an infinite loop. Salesforce can detect these situations and it will throw an error if this happens.

There is a decent amount of content out there on how to get around this issue. I have seen a lot of people recommend using a flag called runOnce, or something similar, and check its context when the triggers fire. The idea is you only run the triggers while the value of runOnce = false, then set it to true. This works, but it is not really a solution!

I recommend taking a step back at what your triggers are actually doing instead. Your code is analogous to a business process. If triggers are firing repeatedly, something is wrong with the process. Look at what is really happening and add some conditions to your triggers so they don’t fire wholesale. There is no business process out there that results in an infinite loop, or else work wouldn’t get done!

8. MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): [sObjects]

This Apex error can show up in test and non-test contexts. Salesforce does not allow you to insert objects before or after certain objects due to how those changes would propagate in the database. The list of objects can be found here.

This error occurs when two separate DML transaction are being made on objects that do not allow insertions in the same transaction. In a non-test scenario, you will have to wrap one of the transactions in a @future context. This means that the transaction will be processed asynchronously (which just means it will be done separately).

If the context is a test method, you have two options:

  1. Initially create some of the objects in the @testSetup method Salesforce allows for test classes. This method runs first and creates test data that all test methods in the class can access.
  2. Use the System.runAs([User]) method to run a DML transaction as a different user. Salesforce will allow test classes to treat this as a different transaction.

I have used both solutions, but I found using the @testSetup method is cleaner and much easier to understand.

9. Too many SOQL queries: 101

This is an Apex error that is very common, especially for developers who are getting used to Saleforce governor limits for the first time. Salesforce will not allow you to make more than 100 SOQL queries in a single transaction. A transaction is defined as the start of an operation seen through to end of itself and any other operations it could have triggered. For example:

Save a record --> custom validation code fires --> sObject trigger fires --> configuration rules fire --> sObject trigger fires --> record is saved

In the above sequence, there cannot be more than 100 queries from the operation of the record being saved until the record is finally saved in the database. If this is the case, some of the configuration may need to be consolidated into code. This helps because a developer can bulkify operations.

You may also be seeing this error because you are introducing code into the system that is not bulkified. For example:

List<Account> accountList = [Select Id FROM Account];
for(Account a : accountList){
    List<Opportunity> oppList = [SELECT Id FROM Opportunity WHERE AccountId = :a.Id];
	//use opp data here
}

A common case of not bulkifying is when you are using an object to get some information about another, related object. In the above case, the limit will trigger because I have more than 100 accounts in that org. I need the opportunities related to the accounts, but this is not the correct way to do it. To bulkify, I will use a map instead.

A Salesforce map is a collection of key-value pairs. You can declare any sObject or datatype as either a key or value. Also, you can have values be maps or lists, which can make for some interesting data structures. To bulkify the above example:

List<Account> accountList = [Select Id FROM Account];
List<Opportunity> oppList = [SELECT Id, AccountId FROM Opportunity];
Map<Id, Opportunity> accountToOppMap = new Map<Id, Opportunity>();
for(Opportunity o : oppList){
    accountToOppMap.put(o.AccountId, o);
}

for(Account a : accountList){
    if(accountToOppMap.containsKey(a.Id)){
        Opportunity oppToUse = accountToOppMap.get(a.Id);
		//use opp value here
    }
}

Now, this is a bit more complicated, but we went from 100+ SOQL queries to 2! I made a map of Id –> Opportunity and I made the keys the related AccountIds. In the loop itself, I used the map method containsKey() to check if the account I am on exists in the map. If it does, I grab the Opportunity using the get method and the ID of the account. I can then use it as I please.

If you’re still running into SOQL query errors, or any of the errors above, leave a comment or contact me for advice.

Понравилась статья? Поделить с друзьями:
  • Error out of band
  • Error out labview
  • Error ostream in namespace std does not name a type
  • Error orpsim 16407 missing model
  • Error orpsim 16103 invalid value