Ever wonder dynamically displaying a warning or information message on an object’s detail page without affecting whatever layout is used? Here is a simple requirement: you have an object called MyObject. If you go to view any MyObject record that is created today, you will see an information message “Hello world!” at top of the detail page block. If the record you view is not created today, you will not see the message. The layout of the page should remain not affected including fields and related lists previously configured by drag-and-drop.
JavaScript is an obvious solution as the requirement sounds it only needs manipulations on the browser side. But firstly, how do you inject JavaScript on a standard detail page of an object? Secondly, what if the Created Date of the record is not shown on the page? Now here is a solution: Use controller extension and <apex:detail> Visualforce component. See the following sample code for MyObject controller extension:
public with sharing class MyObjectController { private MyObject__c obj; public MyObjectController(ApexPages.StandardController controller) { this.obj = (MyObject__c) controller.getRecord(); } // Add an INFO message if the record to view is not created today. public PageReference checkOnLoad() { MyObject__c record = [ select Id, CreatedDate from MyObject__c where Id = :this.obj.Id]; // Not accurate. Just to illustrate the logic if (record.CreatedDate != Date.today()) { ApexPages.addMessage(new ApexPages.Message( ApexPages.severity.INFO, 'Hello World!')); } return null; } }
Note that in the checkOnLoad method of the controller, it queries the record. This is necessary as this method is going to be called before the standard View action of the controller is invoked, which means obj.CreatedDate value is not retrieved so far in this method. The method is specified in the action property of the <apex:page> component. See the following Visualforce page:
<apex:page standardController="MyObject__c" extensions="MyObjectController" action="{!checkOnLoad}"> <apex:pageMessages /> <apex:detail subject="{!MyObject__c.Id}"/> </apex:page>
The Visualforce component <apex:detail> presents exactly the pre-defined layout used for the record. You can add optional attributes (relatedList, relatedListHover, inlineEdit, etc.) on the tag to specify if the detail page should include related list, related list hover or support inline editing, etc. The <apex:detail> is so neat and so easy to use that a four line code Visalforce page does exactly what you need to do. Moreover, you could now add any powerful JavaScript to this Visualforce page to do all sorts of client side UI changes!
The final step of making it work is to replace the standard View page with the above Visualforce page. Follow these steps: Setup -> Create -> Objects -> MyObject -> Standard Buttons and Links -> Click “Edit” link beside the View -> Override With -> Pick the name of the above Visualforce page -> Save.