I'm creating a custom settings page where the user can specify which layouts they want a custom button to appear on. I want the user to be able to select Leads, Accounts, Opportunities, and Contacts as possible places for the button.

I can figure out the visualforce part, but how can I make an apex controller that will add a custom button to a layout? That part is new to me.

1 Answer 1


Page layouts are metadata, stored as xml files, and Salesforce does not offer direct access to the metadata API in Apex.

There is a workaround in Andrew Fawcett's Apex wrapper for the Metadata API.

This blog post (also by Andy) looks like it contains some examples that work on Layouts.

The Layout Metadata API documentation will also be useful to reference if you want to accomplish this. Particularly, that the custom buttons is a collection of strings that reference names of webLink objects.

Other things to consider are that you will likely want to allow people to remove your button from their layout(s) via the same custom setting. Also, it'd be a good idea to run a check on your target layout before adding a button to it to make sure that the button doesn't already exist on that layout.

You must log in to answer this question.

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