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
PappuPappu 

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.

Code:

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

Output:

https://XXXXXX.my.salesforce.com/[]?IDforaccountname=ZZZZ
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];

    if(account.size()>0)
    {
         id=account[0].id;
    } 
    return id;
}

Best regards
Sampath
 
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:column > 
                <apex:facet name="header">Account Number</apex:facet> 
                <apex:outputText value="{!record.AccountNumber}"/> 
            </apex:column> 
        </apex:pageBlockTable> 
    </apex:pageBlock> 
</apex:page>

Mark it as the best answer if it helps you.

Thank You,
Ajay Dubedi