10

I am building a generic lightning component that could sit on an account or contact page to display related task data. However it would need to display slightly different data based on object page it is sitting on.

What is the best method to find out what page type a component is on?

2
  • 1
    Suggest you accept Santanu's answer instead of mine - that force:hasSObjectName is much cleaner (though naming it "SObjectName" instead of "SObjectType" adds confusion).
    – Keith C
    Commented Apr 28, 2017 at 10:35
  • Thanks Keith for being a good example :) We learn from seniors like you. Commented Apr 28, 2017 at 19:38

2 Answers 2

20

You can implement force:hasSObjectName interface in your lightning component and you can get the name of the sObject type.

<aura:component implements="force:hasSObjectName">
  <aura:attribute name="sobjecttype" type="String" default="{!v.sObjectName}"/>
  {!v.sobjecttype}
</aura:component>
2
  • Although this is the correct answer, it doesn't work in communities (forceCommunity:hasSObjectName interface does not exist in API 42.0). Check out Keith's answer below if you need to get the record object type for components in communities.
    – sskular
    Commented Jan 15, 2018 at 12:06
  • Good answer (upvoted). I just use v.sObjectName directly and it does the trick. The creation of a new attribute isn't necessary. Commented Aug 7, 2018 at 16:57
7

I presume you are passing an Id into your component?

You can pass the Id to the server and use the Apex Id.getSObjectType() method to discover the type that you can then pass back.

Or if the set of types is limited, you could use DescribeSObjectResult.getKeyPrefix() calls to obtain the key prefixes (the first 3 characters of an Id) for those types and pass those back so your component can do the Id to type translation.

You must log in to answer this question.

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