Can we create custom buttons on the objects through code

I need to create custom buttons for all custom object page layouts through code, is it possible ?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the the following code from the Apex Metadata API to create the buttons via WebLink type.

    // Metadata Weblink (aka Custom Button) for button
    DetailButton = new MetadataService.WebLink();
    DetailButton.fullName = 'MyObject__c.MyButtonName';
    DetailButton.availability = 'online';
    DetailButton.displayType = 'button';
    DetailButton.encodingKey = 'UTF-8';
    DetailButton.linkType = 'page';
    DetailButton.masterLabel = 'My Custom Button';
    DetailButton.openType = 'replace';
    DetailButton.page_x = 'myvfpage';
    DetailButton.protected_x = false;
        new List<MetadataCreateJob.Item> { new MetadataCreateJob.Item(webLink) },
        new MetadataCreateJob.EmailNotificationMetadataAsyncCallback());

Note: The above demo polls the Metadata API (which is an async API) via Batch Apex, however if you are writing a Visualforce page you can use action:poller. Which is how the next part of what you need works as it happens.

You can write code to retrieve, manipulate (via Apex XML classes) and redeploy layouts. Studying and adapt the Retrieve and Deploy demo code to see the mechanics of how to do this.

enter image description here

So calling the Metadata API is easier from Apex with this library. Though one thing that makes the API complex is it is async, regardless of language this adds some handling overhead to you. As you can see i have given a helper Batch Apex wrapper and/or examples of using action:poller to handle this. Once you get your head round this, its pretty easy to use action:poller to create dynamic solutions.

Method 2

Custom buttons are not really something you usually create (or modify) through code in salesforce. They are very easy to create by point-and-click configuration.

See: How to create custom buttons and the examples and references to the documentation given there.

While it may theoretically be possible to use the metadata api from Apex, that would be a huge workaround for something simple and basic. (See Andrew’s answer)

Alternativly, you can overwrite a detail page with visulforce pages which give you full UI control.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x