function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

How to retrieve the sobject ID by using sobject name?

Hi All,

I need to get the account Id and return the same to Visualforce page. Below is the method I am using.

I am getting an empty array list instead of parrticular Account ID. Have provided the output below for reference.

Any help is appreciated.


 public List<Account> getaccount() {
        account = [SELECT id FROM Account where Name = :contactName Limit 1];
        return account;

Sampath SuranjiSampath Suranji
Hi Pappu,

As  your given code line,
 [SELECT id FROM Account where Name = :contactName Limit 1];

This is returning a Account list where the Account name is equal to contactName variable value. if this list is empty means that you cannot find any Account records where the Account name is equal to contactName value.

If you want return only the Account id then try like below,
public string getAccountId(){
    string id='';
   LIST<Account>  account = [SELECT id FROM Account where Name = 'test' Limit 1];

    return id;

Best regards
Ajay K DubediAjay K Dubedi
Hi Pappu,
Please refer the below code.

public with sharing class StandardAccountDisplayController{ 
public List<Account> records {get; set;} 
public StandardAccountDisplayController(){ 
records = [select Id,Name, AccountNumber from Account where Name='test']; 


<apex:page controller="StandardAccountDisplayController"> 
    <apex:pageBlock title="Account List"> 
        <apex:pageBlockTable value="{!records}" var="record"> 
            <apex:column > 
                <apex:facet name="header">Account Name</apex:facet> 
                <apex:outputText value="{!record.Id}"/> 
            <apex:column > 
                <apex:facet name="header">Account Number</apex:facet> 
                <apex:outputText value="{!record.AccountNumber}"/> 

Mark it as the best answer if it helps you.

Thank You,
Ajay Dubedi