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.

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

Migration using ANT in Salesforce

Avoid recursive trigger in salesforce

get current record id salesforce

  • By Ankush Dureja in salesforce

October 24, 2014

apexpages.currentpage().getparameters().get(‘id’) can be used to get current record id or other url parameters in apex code.

Many times we have requirement to get current record id or url parameters of visualforce page in apex code.

Many times we require the current record id in controller. For example we are redirecting from one visualforce page to another visualforce page using apex code and we have also set some parameters for second visualforce page. Then, in that case we can use apexpages.currentpage().getparameters().get(‘id’) to get parameter with id name or any other name.

One more example if we have a button on detail page overridden by visualforce page and once the button is pressed you require the id(or the other field values of that record) of the record from whose detail page the button was clicked. For this requirement also we can use ApexPages.CurrentPage().getparameters().get(‘id’) to get other parameters.

In the following example we will use a custom extension to get current record id and one parameter with name nameParam. Then we are using one visualforce page to display current record id and all fields related to that record id by querying using SOQL query and also displaying value of one more parameter with name nameParam. In this way we can get value of any parameter in Apex code.

Click for Demo

Visualforce Page:

  • Apex , extension , VF , Visualforce

Ankush Dureja

Permanent link to this article: https://www.sfdcpoint.com/salesforce/get-current-record-id-salesforce/

11 comments

Skip to comment form

list has no rows for assignment to sobject in vf page

  • girish on December 9, 2014 at 9:13 am

where is parameter named nameParam being set in your code

list has no rows for assignment to sobject in vf page

  • Ankush Dureja on December 19, 2014 at 12:06 am

We are not setting nameParam in code. But we are getting it in code. Also we are passing this in URL You can check following link for output of above visualforce page http://demopoint-developer-edition.ap1.force.com/apex/currentRecordIdDemo?id=0019000000nPeLS&nameParam=SFDCPOINT

list has no rows for assignment to sobject in vf page

  • rvpadman on July 24, 2015 at 2:03 am

Where is nameparam used?

list has no rows for assignment to sobject in vf page

  • neha on April 10, 2020 at 9:08 am

I have copy your code for apex and VF. I am not able to get the record id .My visual force page does not display any value . error is showing :List has no rows for assignment to SObject An unexpected error has occurred. Your development organization has been notified.

I solved the above error by putting the account in list. still my value is not displaying.

Please let me know what is the problem.

  • Ankush Dureja on April 11, 2020 at 4:15 am Author

Please make sure that you are passing correct parameter in url. Your url should be like this instance url + /apex/currentRecordIdDemo?id=0019000000nPeLS&nameParam=SFDCPOINT Here you need to replace 0019000000nPeLS with some account id that exist in your org.

Please let me know if you still face any issue.

list has no rows for assignment to sobject in vf page

  • neha on April 11, 2020 at 1:48 pm

Thank for reply Ankush. Now it is working fine . I have one more concern .As we are not using the list return type for account then we are facing this issue “List has no rows for assignment to SObject” . when i used the class variable name in vf page error is displaying “Could not resolve the entity from value binding ‘{!acc.Type}’. can only be used with SObjects, or objects that are Visualforce field component resolvable.” and to solve the above issue i have changed my code

For me it’s little bit confusing . It will be a great help if you tell the reason behind this. Thanks a lot.

  • Ankush Dureja on April 11, 2020 at 3:28 pm Author

Can you please post your code?

list has no rows for assignment to sobject in vf page

  • Saad on May 20, 2020 at 8:55 pm

Thanks man for this spirit of sharing i m thankful !

list has no rows for assignment to sobject in vf page

  • Ashish on November 5, 2020 at 2:31 pm

I want to send account id in url while selecting account and click on continue button my page is redirecting proper but not getting account id in url showing null can you please help me where need to change in my below code.

Vf Page ==========

.txtfield{width:65px; margin-bottom:5px;}

table.bgmpop{ border-collapse:collapse; border:1px solid #333; font-family:calibri; font-size:12px; } table.bgmpop th { border-collapse:collapse; background:#6B95A0; color:#fff; border-right:1px solid #fff; text-align:center; font-family:calibri; font-size:14px; padding:3px; border:1px solid #fff; } table.bgmpop td { color:#333; border:1px solid #ccc; font-family:calibri; font-size:12px; padding:3px; text-align:center; }

if( (typeof sforce != ‘undefined’) && (sforce != null) ) { var lkid = ‘{!lkid}’;

var insertId = ‘{!acc.id}’;

if(insertId!=” && lkid!=”){

window.location = ‘/Account/’+lkid+’/view’; }

function confirmCancel() { var isCancel = confirm(“Are you sure you wish to cancel?”); if (isCancel) return true;

return false; }

Apex code ==============

public with sharing class PurchaseOrderAccount { public Account acc{get;set;} public String targetField {get;set;} public String busAssoID {get;set;} public String retURL {get;set;} public String conid {get;set;} public String message{get;set;} public List contactList {get;set;} public List accountList {get;set;} public List options {get;set;} public string bl1 {get;set;} public boolean contactsection {get;set;} public boolean desabl {get;set;} public String lkid{get;set;} public Account selectedAccount{get;set;}

public PurchaseOrderAccount() { acc=new Account();

public PurchaseOrderAccount(ApexPages.standardController controller) { this.controller = controller; }

public PageReference Redirect(){ String userId = UserInfo.getUserId(); PageReference pageRef = new PageReference(‘/apex/OrderUploadPage_HO?id’+acc.Id); pageRef.getParameters().put(‘UserId’,userId); pageRef.getParameters().put(‘accid’,acc.Id); pageRef.setRedirect(true); return pageRef; }

public pagereference cancel(){ pagereference ref; if(retURL!=null){ if(lkid!=null) { ref = new pagereference(‘/’+lkid); } } return ref; } private final ApexPages.StandardController controller; }

list has no rows for assignment to sobject in vf page

  • manu on January 22, 2021 at 8:59 pm

you manually need to put the id in the url, and for list of Sobjects, you will not get any url in the page.

list has no rows for assignment to sobject in vf page

  • simmy on February 8, 2022 at 3:38 pm

public class AccountListctrl{ public List selreclist; public list areamaster; // public String areaIds;

public AccountListctrl(ApexPages.StandardsetController controller)

{ selreclist = controller.getSelected(); //areaIds=”; list areamaster= [select id,Date__c,Name from Area_Master__c where id in:selreclist]; system.debug(‘test’); test1(); } public void test1(){ // list pjhead1= new list(); PJP_Header__c pjhead = new PJP_Header__c(); pjhead.Visit_Date__c =areamaster[0].Date__c ; //pjhead1.add(pjhead); // pjhead.No_of_Attached_Beats__c =; insert pjhead; // list save = database.insert (pjhead1,false);

list pjpline1 = new list (); for( Area_Master__c armaster : areamaster ){ // areaIds += armaster.Id + ‘,’; //build list of ids string concatenated with comma // system.debug(‘areaIds’+areaIds);

PJP_LIne__c pjpline = new PJP_LIne__c(); pjpline.PJP_Header__c=pjhead.id; pjpline.Visit_Date__c = armaster.Date__c; pjpline.Id=armaster.id; // pjpline.PJP_Month__c= armaster.Month__c; pjpline1.add(pjpline); }

insert PJPline1 ; redirectToLC(); }

public PageReference redirectToLC(){ // String returnUrl = ‘/lightning/cmp/c__ProcessListView?Area_Master__c=’+areaIds; PageReference pgReturnPage = new PageReference(‘https://atctirepvtltd–dev.lightning.force.com/lightning/o/PJP_Header__c/list?filterName=00B0p000002hFkjEAE’); pgReturnPage.setRedirect(true); return pgReturnPage; } } vf=========

function selectAllCheckboxes(obj,receivedInputID){ var inputCheckBox = document.getElementsByTagName(“input”); for(var i=0; i<inputCheckBox.length; i++){ if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){ inputCheckBox[i].checked = obj.checked; } } }

this is my apex class in which I am getting error to insert data DML currently not allowed

Leave a Reply Cancel reply

Your email address will not be published.

Popular Posts

  • Navigation Service in LWC(Lightning Web Components) 16 comments
  • Modal/Popup Lightning Web Component(LWC) 6 comments
  • Batch Apex Example In Salesforce 17 comments
  • for:each template directives in LWC 1 comment
  • Wrapper Class in Apex Salesforce 20 comments
  • Get Record Id in Lightning Web Component 9 comments
  • Lightning Web Components(LWC)Tutorial 4 comments
  • template if:true Conditional Rendering LWC 8 comments
  • Triggers in Salesforce 5 comments
  • Lightning Web Component(LWC) Toast Messages 13 comments
  • May 2023  (1)
  • March 2023  (1)
  • January 2023  (1)
  • November 2022  (1)
  • October 2022  (1)
  • September 2022  (2)
  • August 2022  (2)
  • June 2022  (1)
  • February 2022  (1)
  • January 2022  (1)
  • September 2021  (2)
  • August 2021  (1)
  • June 2021  (2)
  • May 2021  (2)
  • April 2021  (2)
  • January 2021  (2)
  • December 2020  (1)
  • October 2020  (1)
  • September 2020  (1)
  • August 2020  (2)
  • June 2020  (2)
  • May 2020  (20)
  • April 2020  (10)
  • March 2020  (6)
  • February 2020  (6)
  • January 2020  (2)
  • December 2019  (6)
  • November 2019  (3)
  • March 2019  (1)
  • February 2019  (1)
  • January 2019  (2)
  • December 2018  (7)
  • November 2018  (4)
  • October 2018  (2)
  • June 2018  (1)
  • April 2018  (1)
  • March 2018  (1)
  • January 2018  (1)
  • December 2017  (2)
  • November 2017  (1)
  • October 2017  (2)
  • September 2017  (2)
  • August 2017  (1)
  • July 2017  (1)
  • May 2017  (2)
  • April 2017  (8)
  • October 2016  (1)
  • June 2015  (1)
  • February 2015  (1)
  • October 2014  (1)
  • August 2014  (1)
  • June 2014  (4)
  • May 2014  (1)
  • April 2014  (2)
  • March 2014  (4)
  • February 2014  (22)

Recent Posts

  • How Salesforce Einstein GPT is changing the Game for Small-Medium Enterprises
  • What are the benefits of Salesforce health cloud?
  • salesforce customer 360 overview and features
  • Difference Between Workflow Process Builder and Flow
  • Salesforce Integration Interview Questions And Answers
  • Salesforce developer interview questions
  • Salesforce Admin Interview questions
  • Salesforce Lightning Interview Questions
  • Salesforce Field Service Implementation
  • Salesforce Course Details | Eligibility, Fees, Duration

Recent Comments

  • luqmaan s on Pagination using StandardSetController with wrapper class
  • Santosh on Get Record Id in Lightning Web Component
  • Micky on custom label in visualforce page
  • Syed Wassim on salesforce order of execution
  • NoviceDev on Avoid recursive trigger in salesforce

TOTAL PAGEVIEWS

  • SFDC Share Point

Our Facebook page

https://www.facebook.com/sfdcpoint

© 2024 Salesforce Blog.

Made with by Graphene Themes .

Privacy Overview

  • 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.

System.QueryException: List has more than 1 row for assignment to SObject

System.QueryException: List has more than 1 row for assignment to SObject Error is in expression '{!search}' in component apex:commandButton in page simpsons_vf01_car_show: Class.Simpsons_Cl1_classCar.search: line 36, column 1

David Reed's user avatar

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. –  Community Bot Commented Jan 4, 2022 at 19:42

Presumably the value sim is of type Car__c . You cannot assign the result of a query that returns anything other than exactly one record to a value whose type is an SObject. In particular, this does not make sense when you're performing a search query with a LIMIT 20 clause.

You should type your variable as a List<Car__c> .

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 salesforce soql or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • Site maintenance - Tuesday, July 23rd 2024, 8 PM - Midnight EST (3 AM - 7 AM...
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • What happens to a sparse file's holes when the space is needed?
  • Why different signs: Nachash vs Tannin?
  • Whence comes the expression ‘’starve a cold, feed a fever?”
  • Limited list of words for a text or glyph-based messaging system
  • Passphrase generator using German word list and Python's "secrets.choice()" to select from the list. Are those strong passphrases?
  • Braille-based Base64
  • Has D. Trump mentioned whether he'd be willing to debate K. Harris?
  • Guess-the-number game in Python
  • How can the diode conduct in negative half cycle of AC signal in clamper circuit?
  • Shomer Negia in Case of Danger
  • Can trusted timestamping be faked by altering some bytes within the document?
  • Sobolev spaces are smooth? Their dual is strictly convex?
  • How far can an AC signal actually go?
  • What does the word "Eine" mean in Latin?
  • How did the NES's RP2A03 noise generator generator produce 32k bit long sequences despite only being 15 bits wide?
  • MouseDown event
  • Is "avoid extra null pointer risk" a reason to avoid "introduce parameter objects"?
  • What hidden class abilities are there in D&D 5e?
  • Which word can be used to describe either the beat or the subdivision?
  • How can 4 chess queens attack all empty squares on a 6x6 chessboard without attacking each other?
  • Particles and fields
  • "One-time discount" fraud: is any crime committed?
  • "聞けたら聞いてる" what does it mean? Is it some grammar?
  • Trump’s use of the term deportation

list has no rows for assignment to sobject in vf page

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.

VF Email Template throws List has no Rows to sObject when invoked via VF Component

I'm facing an issue with VF Email Template. The error is not very Clear :

"Error Error occurred trying to load the template for preview: List has no rows for assignment to SObject. Please try editing your markup to correct the problem. "

This is my controller :

(Adding the method which returns list has no rows)

This is my VF Component:

This is my VF Email Template:

I'm not sure what to provide here for Case Id. Case Id and Opportunity Id are passed in the URL of the VF Page.

Please let me know what should be done to get this working.

  • visualforce-component
  • email-template
  • vf-email-template

Chinmai Nuthikattu's user avatar

The issue lies at this statement.

Instead try doing it like this.

Please refer to the below article for more information about the error. 'List has no rows for assignment to SObject' error

Hemavantha Rajesh Varma Mudunu's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged visualforce-component email-template send-email vf-email-template ..

  • Featured on Meta
  • Site maintenance - Tuesday, July 23rd 2024, 8 PM - Midnight EST (3 AM - 7 AM...
  • Announcing a change to the data-dump process
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • Has D. Trump mentioned whether he'd be willing to debate K. Harris?
  • How to address past academic misconduct as a new faculty member?
  • What happens to a sparse file's holes when the space is needed?
  • What does the word "Eine" mean in Latin?
  • How can 4 chess queens attack all empty squares on a 6x6 chessboard without attacking each other?
  • Braille-based Base64
  • Is there any way to save an inbred human population that also happens to be the last one left?
  • Why is 我们两个 said instead of 两个我们
  • Tiny worms in blackberries
  • How do I distinguish between "e" the natural log base and a variable conventionally referred to as "e"?
  • "聞けたら聞いてる" what does it mean? Is it some grammar?
  • Where is git-prompt.sh located in Ubuntu 24.04?
  • Shomer Negia in Case of Danger
  • Searching for liquids with a high boron density
  • Choice of Generalized Coordinates
  • Superposition principle and Small signal analysis
  • Diagonal ice tunneling rover to reach a safe pressure in Mars?
  • how to find a good change of variables to solve these kinds of multi-integral questions?
  • The shortest way from A1 to B1
  • MouseDown event
  • Who were the oldest US Presidential nominees?
  • Applying a voltage by DAC to a Feedback pin of a DC-DC controller
  • Spell slots of a Sorlock multiclass
  • Probability for a random variable to exceed its expectation

list has no rows for assignment to sobject in vf page

COMMENTS

  1. 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.

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

    Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site

  3. List has no rows for assignment to SObject

    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 ...

  4. 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...

  5. 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:

  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. 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. If the SOQL query finds no records, it always returns ...

  8. Getting List has no rows for assignment to SObject error

    I have two Custom Objects both are having different VF Pages in my 1st custom object Registration__c I have one field Email_id__c. Every time if user enters value on Email field it should be Auto populate on my 2nd Custom Object FeedbackFrom__c Registered Email Field.

  9. 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:

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

    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. If the ContentVersionId file is not shared, share it manually with the library/user.

  11. List has no rows for assignment to SObject error

    I have a custom Object TimeRecords__c and I want to display the VF Page as a pdf in the object using a custom Button. I created a Visualforce page and a controller class for the Custom Button. On clicking the custom button I get the 'List has no rows to SObject error'. My VF Page Code is as below:

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

    It's a very common mistake to see client devs not do this, and it can lead to serious issues on big orgs. Writing code this way usually lowers C1 complexity, which makes unit tests a lot easier. Having one record gets you 100% coverage and doesn't throw exceptions or have multiple exits.

  13. I want to get rowid in vf page table . List has no rows for assignment

    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.. Visit Stack Exchange

  14. get current record id salesforce

    For this requirement also we can use ApexPages.CurrentPage ().getparameters ().get ('id') to get other parameters. In the following example we will use a custom extension to get current record id and one parameter with name nameParam. Then we are using one visualforce page to display current record id and all fields related to that record ...

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

    6.) Check Salesforce Profile page layout; If the Profile page appears like Version 1, go to the next page for Version 1 steps. If the Profile page appears like Version 2, skip down to Version 2 steps. iContact Field Security Instructions Version 1 Note; Version 1 for accounts with Enhanced Profile User Interface Disabled. 1.)

  16. Insert and then select in VF controller giving List has no rows for

    Insert and then select in VF controller giving List has no rows for assignment to SObject. Ask Question Asked 2 years ago. Modified 2 years ago. ... List has no rows for assignment to SObject. But I am sure Quote and quote line data got inserted succesfully. apex; soql; Share. Improve this question.

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

    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. If the ContentVersionId file is not shared, share it manually with the library/user.

  18. System.QueryException: List has more than 1 row for assignment to SObject

    Presumably the value sim is of type Car__c.You cannot assign the result of a query that returns anything other than exactly one record to a value whose type is an SObject. In particular, this does not make sense when you're performing a search query with a LIMIT 20 clause.. You should type your variable as a List<Car__c>.

  19. VF Email Template throws List has no Rows to sObject when invoked via

    Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site