Custom Related Lists

The Problem

A few weeks ago my wife, a Salesforce admin, asked me if it was possible to create a related list that filtered out inactive contacts. I explained that it’s entirely possible to do something similar, but only with Apex and Visualforce. It got me to thinking that it’s possible to write code that, well, writes the code needed to build related lists with filters. A few weeks later, I’m releasing Custom Related Lists.

No coding required.

Custom Related Lists is an unmanaged package that enables Declarative Developers and Admins to create related list Visualforce pages. You can embed these Visualforce pages on standard and custom detail page layouts using the page layout editor. They mimic the functionality of native related lists with a few additions. With Custom Related Lists, users can select and create criteria to filter records displayed in the list. Now users can create a related list of Contacts on the Account detail page that filter out inactive contacts, or contacts of a given record type. Additionally, Custom Related Lists is not bound to the 10 field limit. Custom Related Lists is capable of displaying all the fields of a child object in the list, but users should be mindful of the user experience implications that carries with it.

How it works.

This is the technical bit, and if you’re just interested in using Custom Related Lists, you might want to skip this section. Fundamentally, Custom Related Lists (CRL) (ab)uses Visualforce as a template system to abstract out the boilerplate bits of Apex and Visualforce. It consists of three Visualforce template files:

  • CRL_MetaGenCtrl – the Controller template
  • CRL_MetaGenPage – Visualforce page template
  • CRL_MetaGenTests – Apex tests for the controller

Each of these files uses the CRL_MetaGeneratorCtrl controller, which is responsible for providing the non-boilerplate bits of code. The new Related_List__c record page has been overridden to give a nice Visualforce wizard. The user selects the “master” object whose detail pages this list will display, and the “detail” object whose records will be displayed on the list. Once selected, the user can select the fields to display, as well as defining criteria filters. The wizard is intentionally dynamic; selecting the “master” object automatically determines which objects relate to it and populates the detail selection list with related objects. Once the user has specified the details, the page controller first saves the record, and generates the controller, test, and Visualforce pages needed. Generated from the templates I mentioned above, using a little-known pageReference method – getContents(). getContents renders the given Visualforce page into a string as if it were requested by a browser. This allows us to use Visualforce as a templating system. Tied to a custom controller, the templates mentioned above are rendered in Apex through getContents(), and result in Apex code with the user-selected options merged in. For example, to be included on a detail page, the Visualforce page that displays the list must extend the standard controller of the selected object. The controller has a method to generate the startPageTag which is simply written to the final Visualforce page with standard merge syntax: {!startPageTag}

Putting it in place

After the custom controller extension, test, and Visualforce page are rendered to strings, the application puts the code in place. Apex code is placed with the Tooling API and the Visualforce page in place with a standard Rest call. (I have no idea, why Visualforce can be created with a rest call, but we need the Tooling API for Apex.) I want to give a shout out to Andrew Fawcett and James Loghry for their excellent Tooling API Apex library. (Please note, that the version of the library packages with Custom Related Lists is truncated to include only enough of it to insert Apex classes.) Because of how Custom Related Lists uses the Tooling API. It’s important to note that generating the code will work in Sandboxes and Developer orgs, but is not supported in Production orgs as these require full test runs for deployment. The tooling API requires a custom remote site setting to function. This is automatically generated using the Javascript metadata API wrapper JSForce whenever you load the app. If autogeneration of the remote site setting fails for some reason, users are given instructions on creating it.

Dynamicity and Data Portability

Custom Related Lists is designed to be run for creation in a Sandbox, and to use in a Production environment. However, it’s also designed to be highly dynamic. It would be a pain to re-generate the code and change set every time we wanted to adjust what fields are displayed. To prevent that need, the generated code references a Custom Related List object record on page load. This allows admins to change the criteria and fields displayed without having to re-generate the code and deploy it. However, this also means that users would have to re-create the record in the Production org. To prevent this need, the generated code contains a JSON encoded version of the initial Related_Lists__c record. After deployment to Production, on the first display of the related list, the code will de-serialize the JSON and create the needed record. It is highly recommend that you leave sharing settings for Related_List__c records as public read.

Using Custom Related Lists

Installing Custom Related lists is slighting more complex than a standard package as it must be installed in both your Production and Sandbox orgs. Once you’ve installed it in both orgs using these links…

Once installed, the process is straightforward. First, open the Custom Related Lists app from the app selection menu.app selection This will load the apps info page which will attempt to securely create a remote site setting on your behalf. If you’re an administrator of the org, this should succeed, and you’ll see a green success menu like this.remote site setting success

 

If it fails, follow the instructions to manually create the needed remote site setting. Once your remote site setting is settled, you can navigate to the Custom Related List tab. crl tabThis is a standard list view for your Custom Related Lists objects.

This is a standard list view for your Custom Related Lists objects. To facilitate ease of use, I’ve overwritten the New button to utilize a custom Visualforce page that looks like this:

wizzard

Lets go through each of the input fields here and talk about what they do.

  1. Step 1: The name you provide here in Step 1 is used as the name of your Visualforce page that you’ll end up placing on a page layout. It’s good to be descriptive, but you only have 40 characters, so a good example would be something like “Active Contacts for this Account.” Short but descriptive.
  2. Step 2: This is where the fun starts. Whatever object you choose here determines everything else available to you. You want to choose the object on whose detail page layout you want to display this list. If you want to display, for instance, Active Contacts on this Account, you’d choose Account here. Custom Related Lists determines the options available to you in Step 3.
  3. Step 3: Choose the relationship you want to display. In the background, it asks the system to describe all objects that are related to your choice in Step 2, and shows you the Labels for those relationships. If you have a situation where you have multiple relationships, say a Master/Detail relationship and a Lookup relationship to the same object you must pay careful attention to choose the one you’re looking for. As an Administrator or Developer, you need to ensure you’re naming your relationships such that you can distinguish them! In our example of active contacts on this account, we’d choose Contact in Step 3.
  4. Step 4: Once you’ve selected the relationship to display, the app will load all of the relevant fields that are available for display. You can select fields on the left hand side and move them to the right, which will select them for display in your list. While standard related lists are limited to 10 fields, custom related lists are not.
  5. Step 5 is probably the most powerful and crucial step here. Unfortunately,itcan be the most confusing. Let’s start with some terminology.Criteria are the options you’re setting to filter which recordswill be displayed in your list. Constraintsare made up of a selected field, an ‘operand’ which defines the comparison method used, a Value field where you specify the valueto be compared, and afinalpicklist that lets youdetermine if this criteriashould be evaluated with AND or OR.If you’ve ever created a custom list view, thisshould be familiar. The wizard starts you off with a single criteria line, but you can add more by clicking on the Add New Constraint button. In our example of Active Contacts on Account you might select “Active” for the field name, set the operandpicklist to ‘=’ and set the value to ‘true’ (note, no quotesare needed). This would filter your list’s contents so that it only displays Contacts whose Active__c field is equal to true. Other operands available to you include ‘!=’ or not equal, as well as <, >, <= and >= or greater than, less than, less than or equal to, and greater or equal torespectively. Some example criteria to get your imagination going:
    1. RecordTypeId, =, your RecordTypeId here — would result in a related list only displaying related records of a selected record type.
    2. Email, !=, null -- Null is a special word, and in this case allows you to filter your list to exclude contacts with no email listed.
    3. CreatedDate, >=, 2005-06-15 — show only records thatwere created after June 15th, 2005.Note that you can use any of the APEX Date Literals for the value, and that you are responsible for providing the proper date format string! See here for more details!
    4. I mentioned before that you could create multiple criteria lines by clicking the Add New Constraint button. How those constraints are interpreted in relation to one another is dependent on your selection of AND or OR. For instance, you could use AND to ensure that both: RecordTypeID = your RecordTypeId, as well as lastModifiedDate >= LAST_90_DAYS criteria are met, ensuring that your list would only display records with the matching Record Type Id that were also modified in the last 90 days. If you select OR for those constraints, records with the selected Record Type Id OR who were modified in the last 90 days would be displayed.
    5. It is important to note here that you MUST have at least one constraint for Custom Related Lists to properly work. If you do not have criteria to add, use a standard related list.
  6. After clicking the Create New Custom Related List button and the page reloads, you’ll see the Generate Controller and Page button. Once you click the button, Custom Related Lists will generate the controller, the test class, and the Visualforce page.
  7. At this point, you’ve got everything you need, but only in your Sandbox org. There are three files you’ll need to include in your change set, and their filenames are listed on the final page. Deploy your change set, and then edit your page layout to include your Visualforce page and you’re set!

Important Considerations and Caveats.

This package makes several assumptions, and while they’re valid in the vast majority of cases, they’re not always going to work. While the package works hard to ensure that the fields listed for inclusion in the related list are queryable and available for use, not all of them actually are. For instance, say you’re creating a related list of notes to a given Account. The system will report that “Name” is available, but upon running it… not so much. Let’s call it a platform quirk. The good news is that most of the fields I’ve found that are affected by such quirks are not the kind of fields you’d typically want to put in such a list. The really good news, is that the related lists are fully dynamic. When the page loads, it pulls its configuration details from the Related_List__C object. If you run into an issue with a field not being available you can edit the fields on the object and reload. No code regeneration needed.

I hope y’all find this as useful, as I had a ton of fun building it. In the future I want to fix the edit screen to use the same wizard, and capture as many edge cases as possible. In the meantime, you can find the code on Github, and I’ll gladly accept pull requests and issues for feature requests. If Custom Related Lists makes it into your org, and saves you time and energy, feel free to hit that tip button on the left.

19 comments

  1. Including the object as JSON in the deployed code and deserializing it on first run is an absolutely GENIUS move. That’s brilliant. This projects looks amazing, so congratulations on getting it working, getting it out the door, and allowing admins to save the day with it. Thank you!

    1. The JSON is a backup if it can’t find the original ID. If it can’t find the id, that seems like the type of exception you would want fail on and not back up with JSON. there is no way to create consistency between the JSON code and whats in the db

  2. Hello. I recently tried to install this in a sandbox and got a notification that the package has been deprecated. Is there an updated link?

  3. Would this work w/ the Activity history related list as well? (which is not a standard / simple related list). It would be great to be able to build History lists that excluded various activities (like automated emails, for example).

      1. codefriar, I gave this a try on activity history and received the following error:

        INVALID_FIELD_FOR_INSERT_UPDATE : Field is not writeable: ActivityHistory.WhoId
        Error is in expression ‘{!generateCode}’ in component in page crl_newcrl: Class.ToolingAPI.submitRestCall: line 489, column 1
        Class.ToolingAPI.submitRestCallAndDeserialize: line 418, column 1
        Class.ToolingAPI.createSObject: line 79, column 1
        Class.CRL_CodeGenerationLib.GenerateClass: line 9, column 1
        Class.CRL_NewCRLCtrl.generateCode: line 221, column 1

        Any ideas?

  4. Will this work for indirectly related lists? For example, if I have a table Discussion__c with a lookup of Contact, and I want to show a related list of Discussions under the Account, is there a way to do that?

  5. This package could be a lifesaver for me. However, I’ve installed the package and am running into an error while trying to Generate Controller and Page:

    Script-thrown exception
    Error is in expression ‘{!generateCode}’ in component in page crl_newcrl: Class.ToolingAPI.submitRestCall: line 476, column 1
    Class.ToolingAPI.submitRestCallAndDeserialize: line 418, column 1
    Class.ToolingAPI.createSObject: line 79, column 1
    Class.CRL_CodeGenerationLib.GenerateClass: line 9, column 1
    Class.CRL_NewCRLCtrl.generateCode: line 220, column 1
    Caused by
    Class.ToolingAPI.submitRestCall: line 473, column 1
    Class.ToolingAPI.submitRestCallAndDeserialize: line 418, column 1
    Class.ToolingAPI.createSObject: line 79, column 1
    Class.CRL_CodeGenerationLib.GenerateClass: line 9, column 1
    Class.CRL_NewCRLCtrl.generateCode: line 220, column 1

    Any idea what’s happening? Or if there’s anything that I can do to get this working properly? Thanks in advance for your help!

    1. Error Update: I was able to get this to work by adding a new remote site in sandbox. For others that run into this error, jump into your developer console and identify the endpoint URL that needs to get added as a new remote site and your custom related lists will generate perfectly.

      1. Seems that you just need to update the Remote Site Settings Name from “CustomRelatedList” to “CustomRelatedLists”

  6. This is a great class and will save our org a ton of money by not having to use gridbuddy, etc to achieve the same.

    I ran into a problem:

    System.SObjectException: Invalid field Name for Lead

    Class.TestFactory.createSObjectList: line 51, column 1
    Class.TestFactory.createSObjectList: line 28, column 1
    Class.CRL_Controller00005_Test.Test_getFilteredList: line 35, column 1

    And the reason behind it makes sense – ‘Name’ is not accessible on lead. LastName and Company are required in my org.

    I’m going to make a hack just for sObject of type Lead but I’m not going to pull down the repo and modify because it’s really a hack. I think the proper technique is looking at required fields on the object. There might be something here (but I don’t have time to experiment):
    https://developer.salesforce.com/forums/?id=906F00000008x86IAA

    Regardless, thanks for this!

  7. After more investigation I’m not quite sure how the generated tests would ever pass. The criteria used in the crl are not used as initializers for the test.

  8. Is it possible to remove the “Link” column that is generated by the app? I would prefer to just put my own formula field in there, I’ve tested this and it works fine.

Leave a Reply

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