I have lightning component that I want to be able to override any object edit button. I pass the recordId and objectName to the apex controller:

public static String getRedirect(String recordId,String objectType){
    //turn the string into an id and object name
    Id obId = Id.valueOf(recordId);
    Schema.SObjectType obtype = obId.getSObjectType();
    // ...

Now all I want to do is get the recordTypeId of whatever this object is. This'll work with known objects:

switch on objectName{
        when 'Account' {
            return getAccountRedirect(recordId);
        when 'Opportunity' { ...

But I want to be more dynamic:

 String query = "Select Id,recordTypeid From"+objectType+"Where Id="+recordId; 
 sObject sob = Database.query(query);

 String rectypeid = sob.recordTypeid;

This doesn't work though because recordTypeId is not a field on SObject. So I looked at this which kinda helped but I still can't find a way to dynamically get an objects record type.

Any ideas ?


You can use the get method, assuming the object has a record type available:

if(obType.getDescribe().fields.getMap().containsKey('recordtypeid')) {
  SObject record = Database.query('SELECT RecordTypeId FROM '+obType+' WHERE Id = \''+recordId+'\'');
  Id recordTypeId = (Id)record.get('RecordTypeId');
  // ...
  • sweeet thanks ! jsut what I was lookin for May 24 '19 at 19:32
  • Hi, is there a way where we dont need to use the apex class and still can make the 'recordtypeid' as dynamic in lightning controller.
    – user905
    Jul 9 '19 at 11:10
  • @9codie05 In Aura or LWC? You might just want to ask a new question so we can get all the pertinent details. I'd be glad to take a look at it for you.
    – sfdcfox
    Jul 9 '19 at 12:42
  • @sfdcfox In Aura and I have asked a question here: salesforce.stackexchange.com/questions/268733/… Thanks for your comment.
    – user905
    Jul 9 '19 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.