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
Ravi Dutt SharmaRavi Dutt Sharma 

Initializing an sobject with record id

Lets say I have Id of Account record and I am initializing the sobject and assigning the Id to account variable. Below is the code :
sObject obj = Schema.getGlobalDescribe().get(parentObjName).newSObject() ;
obj.Id = recordId;
System.debug('****obj : '+obj);
Debug Result: 
****obj : Account:{Id=0019000001dbup5AAA}
I was hoping that the debug will have the entire information from the account example like : Account:{Id=0019000001dbup5AAA, Name=TestAccount,...}
Is there any way to initialize the sobject in a way such that it gets loaded with the entire information?
Best Answer chosen by Ravi Dutt Sharma
Sumit Kumar Singh 9Sumit Kumar Singh 9
OK Bro, 
You can try this - 
SObjectType objToken = Schema.getGlobalDescribe().get('Account');
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fields = objDef.fields.getMap();
list<string> fieldslist = new List<string>();
for(String s : fields.keySet()) {
    fieldslist.add(s);
}
string q = 'SELECT ' + String.join(fieldslist, ',') + ' FROM account LIMIT 1';
System.debug(q);
sObject sObj = Database.query(q); 
Account acc = (Account)sObj.clone(false, true);
System.debug(acc);

Thanks, 
Sumit Kumar Singh

All Answers

Sumit Kumar Singh 9Sumit Kumar Singh 9
You can try this - 
SObjectType objToken = Schema.getGlobalDescribe().get('Account');
DescribeSObjectResult objDef = objToken.getDescribe();
System.debug(objDef);

Thanks, 
Sumit Kumar Singh
Mathew Andresen 5Mathew Andresen 5
If you want actual account data such as "Name=TestAccount"

Why not just do a SOQL query  such as [SELECT Name, Id etc From Account WHERE Id =  :recordId];
Ravi Dutt SharmaRavi Dutt Sharma
Hi Mathew, I need to clone the record using Sobject clone method. If I will query the record, I need to query all the fields. Since I am trying to build a generic solution, I do not want to query the record. Makes sense?
Ravi Dutt SharmaRavi Dutt Sharma
Hi Sumit, I need the record information, not the object information.
Sumit Kumar Singh 9Sumit Kumar Singh 9
OK Bro, 
You can try this - 
SObjectType objToken = Schema.getGlobalDescribe().get('Account');
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fields = objDef.fields.getMap();
list<string> fieldslist = new List<string>();
for(String s : fields.keySet()) {
    fieldslist.add(s);
}
string q = 'SELECT ' + String.join(fieldslist, ',') + ' FROM account LIMIT 1';
System.debug(q);
sObject sObj = Database.query(q); 
Account acc = (Account)sObj.clone(false, true);
System.debug(acc);

Thanks, 
Sumit Kumar Singh
This was selected as the best answer
Ravi Dutt SharmaRavi Dutt Sharma
Thanks Sumit, this was helpful.