5

Is it possible to dynamically retrieve the fields on a certain layout? Possibly through something like DescribeLayout()? I'm having trouble finding examples on how to build a lightning component with just the fields that are in a specific page layout.

5

You can synchronously pull details of a page layout in Apex using the Apex Metadata API. Here's a quick example of walking through the layout metadata, freely adapted from Trailhead:

List<Metadata.Metadata> layouts = 
    Metadata.Operations.retrieve(Metadata.MetadataType.Layout, 
                                 new List<String> {'Account-Account Layout'});

Metadata.Layout layoutMd = (Metadata.Layout)layouts.get(0);
for (Metadata.LayoutSection section : layoutMd.layoutSections) {
    for (Metadata.LayoutColumn column : section.layoutColumns) {
        if (column.layoutItems != null) {
            for (Metadata.LayoutItem item : column.layoutItems) {
                System.debug(item.field);
            }
        }
    }
}

If you inspect the log after running this in Execute Anonymous, you'll find, e.g.,

11:56:57:079 USER_DEBUG [10]|DEBUG|Name
11:56:57:079 USER_DEBUG [10]|DEBUG|ParentId
11:56:57:079 USER_DEBUG [10]|DEBUG|Phone

and so forth.

4
  • One more question :) Is it possible to getLabel() on the field? – Jeff May 25 '18 at 22:39
  • Oddly, the Metadata.LayoutItem class doesn't include the label, but you can easily get it from the Describe API. – David Reed May 25 '18 at 22:42
  • 1
    Is there any way to get fields in the order present on the page layout? – Krishnan Mishra Nov 21 '19 at 7:43
  • @KrishnanMishra Metadata mentioned above has layout sections with layout columns with fields in the order like in page layout in UI. You can also use Tooling API for this – Igor Vasylevskyi Oct 21 '20 at 11:55

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.