How to get Layout assigned to Profile and Record Type by Apex Code

If you are interested in solution which would work only for Salesforce Classic, I have it.

It is possible to make Tooling API ProfileLayout Object Query

[ select Layout.Name from ProfileLayout where ProfileId = :UserInfo.getProfileId() AND RecordTypeId = :record.RecordTypeId ]

To make it possible to use in Apex Code you need preparation step.

1) Allow Self-Callout. To do this, go to Remote Site Settings by link on production or Developer Edition instance or on any of sandbox instance and input link to your instance and click save.

2) Run the following code from Anonymous Execution Window

static String restGet(String endPoint, String method, String sid) {
    Http h = new Http();
    HttpRequest hr = new HttpRequest();
    hr.setHeader('Authorization', 'Bearer ' + sid);
    HttpResponse r = h.send(hr);
    return r.getBody();
static String toolingAPISOQL( String query) {
    String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
    return restGet( baseURL +
'/services/data/v41.0/tooling/query?q='+ (query.replace(' ', '+'))
'GET', UserInfo.getSessionId() );

static String getLayoutNameForCurrentUserProfile( Id recordId ) {
    String body = toolingAPISOQL('select Layout.Name from ProfileLayout where ProfileId = \'' + UserInfo.getProfileId() + '\' AND RecordTypeId = \'' + [ select RecordTypeId  from Account where id = :recordId].RecordTypeId + '\'');
    System.debug(LoggingLevel.ERROR, '@@@ v: ' + body );
    String name = body.substringBetween('"Name":"', '"');
    System.debug(LoggingLevel.ERROR, '@@@ v: ' + name );
    return name;

You will can the name of desired layout.

Note that this would work only in Salesforce Classic and not in Lightning by strange Salesforce policy which disadvantages Lightning very much since

By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex code from making API calls to Salesforce.

This entry was posted in salesforce. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s