SFDCian – Best Salesforce Consultant & Architect

Apex error – ‘List has no rows for assignment to SObject’

The error “List has no rows for assignment to SObject” occurs when query doesn’t return any rows.

Resolution   

While a SELECT normally returns an array/list, these statements are using the shorthand syntax that assumes only one row is returned. What’s not obvious is that it also assumes that exactly one row is returned! Although this is unlikely to occur for Contact, it is highly likely to occur for any custom objects you create, especially when a WHERE statement is used that might return zero rows, such as: 

The above code will fail if there is no Player__c record with the matching username. It doesn’t actually return a null.  It would be safer to do the following:

It’s one of those situations for which you would not normally think of creating a test, so it’s safer to just avoid the possibility.

Related Posts

Salesforce: opportunity clone for each opportunity contact role along with opportunity products, are you building lightning app with locker services.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Apex Testing Error: System.QueryException: List has no rows for assignment to SObject

I am trying to get my test data set up for an Apex test class I made and I am getting "System.QueryException: List has no rows for assignment to SObject" in the tests error log. Not really sure what I am missing and any help would be appreciated! The error is occuring at "StaffEmailToolHelper.sendEmails(fiList);" in the test class

StaffEmailHelperTool.apxc

TestStaffEmailHelperTool.apxc

  • queryexception

Austin Kelly's user avatar

  • 1 Welcome to Salesforce Stack Exchange (SFSE)! Thank you for the code. In order to get better/quicker help, please edit your question to include which line(s) the error(s) occur[s] on. –  Moonpie Commented Feb 1, 2022 at 23:22
  • 1 Does the error specifically indicate that fiList is the culprit? That is where the error will show for the test class if the real culprit is an issue within the main class. Can you verify whether an error is occuring in the main class and is "bubbling up" to show you the error on that test class line? If there is an error in the main class, please re-edit to include that line. –  Moonpie Commented Feb 1, 2022 at 23:30
  • 1 Also, a side note, do not send emails or perform queries in a loop. You must bulkify your code . You can use setTargetObjectId instead of query the contact's email address as well. –  sfdcfox ♦ Commented Feb 1, 2022 at 23:44

2 Answers 2

Your issue is that your test is setting an Id for the emailTemplate, whereas your query is looking for the name of the emailTemplate.

long version

SOQL queries always return a List<SObject> (or a List<AggregateResult> if your query includes the GROUP BY clause).

Salesforce has some syntactic sugar that allows us to stick the result of a query into a single SObject instance, but only when the query returns exactly 1 row . If your query returns 0 rows, you get the "System.QueryException: List has no rows for assignment to SObject" error that you're running into. (You'd get a similar, but different, error if your query returned more than 1 row).

Hard-coding Ids in a test (or really anywhere) is a red flag. Doing so has a tendency to cause test failures in other orgs (i.e. if you create a record in a sandbox and hard-code that Id in your test, it'll fail when you try to deploy to production).

When it comes to testing, there really aren't many shortcuts in setting up the test data. You're going to need to create your own test Contact records, your own test Account record, etc...

The EmailTemplate SObject is special. It's what's called a setup object , and data for those are available in unit tests. You still don't want to query based on the Id though (and the Id and Name fields are different). Querying it based on the template name is better.

I believe best practice would be to define a custom label to hold the template name (and then use that in your test like Label.DefaultStaffEmailTemplate ), which would allow you to make any necessary changes without the need to do a deployment.

great, so what do I do?

  • Create a test account and test contacts in your test class (and also give your test class the @isTest annotation). Creating an @testSetup method to handle that is best practice, though it does mean you'll need to query to get the Ids in your test method
  • Find the Name of your email template, and use that instead of the Id in your test

Other things to consider:

  • You don't need to cast the result of your EmailTemplate query as an EmailTemplate (so that (EmailTemplate) in front of your query can be removed)
  • If you aren't expecting to handle partial template names (with wildcard(s), e.g. 'myEmailTemp%'), then using Name = :emailTemplate is probably preferable to using Name LIKE :emailTemplate (mostly code-style, I think. Follows the Principle of Least Surprise)

Derek F's user avatar

I think your problem is here:

You are populating requests[0].emailTemplate with an id fi.emailTemplate = '00X1R000001ZvyfUAC';

But you are querying on EmailTemplate.Name (a string)

Now, there are some other issues here with your invocable class:

  • It is not bulkified - it needs to work on all requests (meaning all Flow Interviews in a transaction, not just one.
  • You should mock the Contacts and not use hard-coded IDs as Derek F recommends
  • You should use better names - FlowInput not FlowInputs ; Plurals should be used for collections

cropredy's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged apex unit-test email sobject queryexception ..

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • The minimal Anti-Sudoku
  • Would it be possible for humans to be alive to witness the beginning of a runaway greenhouse effect on Earth?
  • Erase the loops
  • Whats the source of saying Al Cheit at night?
  • What is a word/phrase that best describes a "blatant disregard or neglect" for something, but with the connotation of that they should have known?
  • I submitted a paper and later realised one reference was missing, although I had written the authors in the body text. What could happen?
  • Does the US Congress have to authorize non-combat deployments (e.g. of advisers and trainers) from the US armed forces to a foreign country?
  • Do space stations have anything that big spacecraft (such as the Space Shuttle and SpaceX Starship) don't have?
  • A burning devil shape rises into the sky like a sun
  • What would be the optimal amount of pulses per second for pulsed laser rifles?
  • Can you bring a cohort back to life?
  • Making blackberry Jam with fully-ripe blackberries
  • How to Handle a Discovery after a Masters Completes
  • How to understand the use of "used to"?
  • Isn't an appeal to emotions in fact necessary to validate our ethical decisions?
  • Are there rules of when there is linking-sound compound words?
  • How to determine if a target network supports a given EVM opcode?
  • How can I obscure branding on the side of a pure white ceramic sink?
  • Why does the Nicene Creed not use the attribute ' consubstantial ' for the Holy Spirit?
  • Spread vs midswaps
  • Returning to France with a Récépissé de Demande de Carte de Séjour stopping at Zurich first
  • Word to classify what powers a god is associated with?
  • Why are extremally disconnected spaces so hard to give examples of?
  • Crystal Capacitor or not

no rows for assignment to sobject

Get the Reddit app

Unofficial Salesforce Developer Subreddit

System.QueryException: List has no rows for assignment to SObject

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Docusign Custom Button Error: List has no rows for assignment to SObject

Custom button code:

Visualforce error:

I have checked the permissions suggested by docusign and nothing has changed.

Any advice/help would be HUGELY appreciated!

  • docusignapi

Stacey's user avatar

  • How about formatting your code to make it a little easier to read? –  Andre Perkins Commented Oct 30, 2014 at 15:10

2 Answers 2

The script is failing because DocuSign envelope Id has been set to 961202FA-36C6-4A9A-B061-EDC7BE6C8B07. The DSIED should be set to ‘0’ by default. Set DSIED=0 and the script should work:

Ergin's user avatar

If you set the DSEID=0 then it does not populate the template with the Client data which is what we are trying to do. How do you get the Sign Now custom button to work.

Francois's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged docusignapi or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Do space stations have anything that big spacecraft (such as the Space Shuttle and SpaceX Starship) don't have?
  • What is the soteriological significance of Hebrews 10:1 in the context of God's Redemption Plan?
  • Why do individuals with revoked master’s/PhD degrees due to plagiarism or misconduct not return to retake them?
  • Making blackberry Jam with fully-ripe blackberries
  • Why did evolution fail to protect humans against sun?
  • John 11 and The Sanhedrin Council
  • Can two different points can be connected by multiple adiabatic curves?
  • A study on the speed of gravity
  • Did the Space Shuttle weigh itself before deorbit?
  • Why do instructions for various goods sold in EU nowadays lack pages in English?
  • DIN Rail Logic Gate
  • Shift right by half a trit
  • Why does the Nicene Creed not use the attribute ' consubstantial ' for the Holy Spirit?
  • Why is Excel not counting time with COUNTIF?
  • The minimal Anti-Sudoku
  • What role does the lower bound play in the statement of Savitch's Theorem?
  • Why are extremally disconnected spaces so hard to give examples of?
  • Did Newton predict the deflection of light by gravity?
  • With 42 supernovae in 37 galaxies, how do we know SH0ES results is robust?
  • An idea to prevent the principle of explosion
  • Confused about topographic data in base map using QGIS
  • Why does Air Force Two lack a tail number?
  • How to let LaTeX ignore a part of a \section{....} argument for writing the .aux file?
  • Spread vs midswaps

no rows for assignment to sobject

IMAGES

  1. Salesforce: List has no rows for assignment to SObject in a test class

    no rows for assignment to sobject

  2. Salesforce: List has no rows for assignment to SObject

    no rows for assignment to sobject

  3. System.QueryException: List has no rows for assignment to SObject for

    no rows for assignment to sobject

  4. Understanding 'List has no rows for assignment to SObject' in a trigger

    no rows for assignment to sobject

  5. Salesforce: List has no rows for assignment to SObject test class

    no rows for assignment to sobject

  6. System.QueryException: List has no rows for assignment to SObject

    no rows for assignment to sobject

COMMENTS

  1. Apex error 'List has no rows for assignment to SObject'

    What's not obvious is that it also assumes that exactly one row is returned! Although this is unlikely to occur for Contact, it is highly likely to occur for any custom objects you create, especially when a WHERE statement is used that might return zero rows, such as:

  2. custom object

    This is resulting in no records being returned and Salesforce throwing the System.QueryException: List has no rows for assignment to SObject. Note that this is unlike some other programming languages where you may expect the query to just set your sObject to null. Salesforce's documentation for System.QueryException states it is thrown when ...

  3. I'm getting "List has no rows for assignment to SObject" error on a

    If the query doesn't return any rows you will get the "List has no rows for assignment to SObject" exception. Instead, assign the results to a list of sObjects and check the size of the list. Then only use the first record in the list if it is present. - Daniel Ballinger.

  4. List has no rows for assignment to SObject

    If you get more than 1 row and attempt to assign that to your Accountx variable you will get the opposite of your original problem - System.QueryException: List has more than 1 row for assignment to SObject! So one way of guarding against this would be to use Account accountx = [SELECT Id FROM Account LIMIT 1]'. - frup42.

  5. salesforce

    Impossible. If you're getting "list has no rows to assign to sObject" it means you're assigning to single object. This eliminates getProductsLov(unless you didn't post whole code) because there you assign to a list.. Humo(u)r me and System.debug(JSON.serializePretty(ApexPages.currentPage().getParameters())); in your constructor before firing that query...

  6. Error 'List has no rows for assignment to SObject' in Salesforce CPQ

    This issue can also occur when the user attempts to reconfigure a Primary Quote without Read access to the associated Opportunity. Lack of access to the Opportunity object throws List has no rows for assignment to SObject' since our code queries for the Primary Quote on that opportunity.

  7. Apex error

    What's not obvious is that it also assumes that exactly one row is returned! Although this is unlikely to occur for Contact, it is highly likely to occur for any custom objects you create, especially when a WHERE statement is used that might return zero rows, such as:

  8. System.QueryException: List has no rows for assignment to SObject

    Facing the 'List has no rows for assignment to SObject' error in Salesforce? In this video, I'll explain what this error means, why it occurs, and how you ca...

  9. Document Generation Error- "List has no rows for assignment to SObject

    Make sure this record is shared with the Docgen Document Template Library to avoid any errors. Steps to fetch ContentVersionId: Open the active template in the Document Template tab (NOT the Docgen Document Template) Add ContentVersionId field to the layout if it is not present already. Go to the Id in Salesforce to check Sharing Settings.

  10. apex

    The reason for the failure is 'System.QueryException: List has no rows for assignment to SObject' which I have tried to look up but there are so many answers and they don't apply to my certain case. Tried it multiple ways and I am wondering if anybody here has a good answer.

  11. Common fix to a "Error: List has no rows for assignment to SObject

    Error when rejecting Applications: List has no rows for assignment to SObject Applications (and the other AMS Stages) has a Master-Detail Object Relationship within ...

  12. Help with error: List has no rows for assignment to SObject

    List has no rows for assignment to SObject errors Hot Network Questions Alternative to BlakeTwo256 for WASM Compatibility in a no_std Environment in Rust

  13. Vague "List has No Rows for Assignment to SObject" Error

    List<sObject> // [SELECT Id FROM Contact LIMIT 100] (returns a list of 100 Contacts) sObject // [SELECT Id FROM Contact LIMIT 1] (returns a single Contact) Integer // [SELECT Count() FROM Contact] (returns how many Contacts exist in your org) There is a gotcha here, that you ran up against.

  14. Document Generation Error- "List has no rows for assignment to SObject

    General Information. We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply.

  15. Apex Testing Error: System.QueryException: List has no rows for

    Contact Record - System.QueryException: List has no rows for assignment to SObject 0 System.QueryException: List has no rows for assignment to SObject for Object created in test case

  16. Salesforce Error: List has no rows for assignment to SObject

    Error: List has no rows for assignment to SObject. Error: User unable to update ... Permission Denied. Please check your Field Level Security settings. These errors can occur for iContact for Salesforce Users that do not have Read Access for iContact Custom Fields.

  17. System.QueryException: List has no rows for assignment to SObject

    No. Leaving out the 'limit 1' is fine if the query returns exactly one record - apex will let you skip the whole array thing. Reply reply fredster2004

  18. Error 'List has no rows for assignment to SObject' in Salesforce CPQ

    This issue can also occur when the user attempts to reconfigure a Primary Quote without Read access to the associated Opportunity. Lack of access to the Opportunity object throws List has no rows for assignment to SObject' since our code queries for the Primary Quote on that opportunity.

  19. Docusign Custom Button Error: List has no rows for assignment to SObject

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.