Dynamically applying specific Layout to a record on VF page in Salesforce

Dynamically applying specific Layout to a record on VF page in Salesforce

You may need a specific layout to show in a tab for a particular record (like account settings). For this, we can fetch ‘Metadata’ field from Field Definition with SOQL using Tooling API. In response you will get all the layout formats and you can apply the one you need.

Also, it is synchronised with actual layout of detailed page. If you change the layout from Object’s detail page, the changes will automatically be reflected on your custom VF Page as this is fetching layout dynamically. The response is in JSON format and contains all the details like number of columns, layout Sections, labels, layout Columns, layout Items. You have to traverse this JSON according to your needs and use values on your VF page.

Here is code:

String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
String ObjectName = 'Accounting+Setting+Layout';  //Name of Salesforce Object whose layouts you want to retrieve
String queryStr='select+id,+FullName,+Metadata,+CreatedDate+from+Layout+where+name=\''+ObjectName+'\''; //SOQL
String endPoint =baseURL + '/services/data/v38.0/tooling/query?q='+queryStr; //Tooling API
String method = 'GET';
String sid = UserInfo.getSessionId();
Http h = new Http();
HttpRequest hr = new HttpRequest();
hr.setHeader('Authorization', 'Bearer ' + sid);
String body='';
HttpResponse r = new HttpResponse();
r = h.send(hr);
body = r.getBody();
if(body != null && body != ''){
Map jBody = (Map)JSON.deserializeUntyped(body);
List recordList = (List)jBody.get('records');
Map dataMap = (Map)recordList[0];
Map metadataMap = (Map)dataMap.get('Metadata');
List metaMap = (List)metadataMap.get('layoutSections');



Leave a Reply

Your email address will not be published. Required fields are marked *