6

I want to get the owner id/ user id of current record.

for this what I know, we have to do 2 things. 1) First we have to fetch record ID from URL by using

ApexPages.CurrentPage().getparameters().get('id');

2) We can fetch owner ID by using this record ID.

If I am correct then how to fetch record owner ID by using record ID?

Regards

1 Answer 1

7

Yes you are correct .Just putting amswer into programmatic way

First get the Id in URL parameter and then on page fetch using

Id recId=ApexPages.CurrentPage().getparameters().get('id');

Secondly use Select statement and get the ownerId(Assuming object is Account)

 ID ownerId=[Select Id,ownerId from Account where Id=:recId].ownerId

Update:

After the comments looks like this has to be dynamic solution

id testid=ApexPages.CurrentPage().getparameters().get('id');
String objecttype=testid.getSobjectType().getDescribe().getName();
try{
    Sobject s=(Database.query('Select Id,ownerId from '+objecttype+' where Id=:testid LIMIT 1'));
    }
catch(exception e){
    }
    Id ownerid=(ID)s.get('ownerId');
9
  • Thank you @Mohith Kumar. Here I am not going to use Account object, because I don't know from which object it will fetch record ID. It'll be decided during run time. I think we have to go for Dynamic SOQl. Correct me If I am wrong. Regards Nov 4, 2013 at 7:55
  • @Rudra_NoVoice Please find the updated response .I have updated the solution to be dynamic.Yes its Dynamic query but with little trick and advanced apex .Welcome to community:) Nov 4, 2013 at 8:29
  • 1
    As a side note, you need to check to see if OwnerId exists before you attempt to query it. Child records in a master-detail relationship do not manifest an OwnerId field.
    – sfdcfox
    Nov 4, 2013 at 8:32
  • This is valid code: Id ownerId, recordId = ApexPages.currentPage().getParameters().get('id'); try { ownerId = database.query('select id, ownerid from '+String.valueof(recordid.getsobjecttype())+' where id = '+string.escapesinglequotes(recordid)).ownerid; } catch(exception e) { }; At the end of the try-catch block, if ownerId != null, then we have a result.
    – sfdcfox
    Nov 4, 2013 at 8:36
  • 1
    I actually kind of intended to mean check before querying, but a try-catch block would eliminate the problem anyways. And my code in the prior comment wasn't quite right, I noticed...
    – sfdcfox
    Nov 4, 2013 at 8:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .