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
TryCodingTryCoding 

Retrieve Sobject based on Id

Hi

i want to create a single method for multiple CustomObjects

 

So i want to pass the id of that object in method and want to run soql for that

 

for e.g.

puvlic static void myMethod(id objectId){

                ----Soql to retrieve record -------

 

}

 

how to retreive whole record for that id within method

 

Please Help

HaagenHaagen

Hi,

 

you could try something similar to:

 

public sObjectType MyObject(ID ObjectId)

{

return [select FIeld1, Field2, ..., FieldN from sObjectType where Id = :ObjectId LIMIT 1];

}

 

However be careful with these kind of construct since it will probably have govenor limit issues if used from a trigger or other places where alot of records is handled. 

 

Cheers!

 

Martin

TryCodingTryCoding

it is not possible friend

Because i neither know the sObjectType nor the fields.. I just have the id in hand

Still i tried this and giving error

Compile Error: sObject type 'sObjectType' is not supported.

HaagenHaagen

Hi,

 

if you don't know what sObject-type you are quering for it get's a bit harder. Your function will probably need to return a sObject and your method needs to build the soql-query dynamically. Have a look at this article:

 

http://www.iowntech.com/?p=204

 

It describe/shows how to get what sObject type you have from an Id. When you know what sObject type it is you can fetch all the field for that type and build the soql query dynamically. Have a look in the "Force.com  APEX Code Developers Guide" under the Reference for the sObject Methods for more information about these methods. 

 

I hope it helps you on your quest!

 

Cheers!

 

Martin

TryCodingTryCoding

This worked for me

thanks a million Haagen

 

Bus does not there exist any short method for solving this problem?????

Cory CowgillCory Cowgill

I wrote a blog post about this a while ago with some additional sample code.

 

Its very similar to the example provided in the link above, but more in depth for a full use-case of buiding the SOQL, populating a VF Page, etc. Hope that helps.

 

http://corycowgill.blogspot.com/2011/01/building-dynamic-soql-select-all-query.html

TryCodingTryCoding

Great post cory

Althouth it uses same method to retrieve object based on id as in the Haggen's link

But still a lot of things at same place in your post

One like from my side :)