Default field values

Adding default values to your fields improves the usability of your application and can reduce the number of fields needed on the screen, as users can remove fields with acceptable defaults from the layouts.

Default values defined on Custom Fields apply in the native user interfaces and Visualforce UIs (providing the apex:inputField component is used), and in some cases, through the APIs. You can define a default value based on a formula using either literal values and/or variables such as $User, $Organization, and $Setup.

Let's try this out. Create a Year text field on the Season object, as per the following screenshot. Make sure that you select the External ID checkbox as this cannot be changed on the field once the package is uploaded at the end of this chapter. This will become important in the next chapter:

The default value you define cannot be overridden through customization in the subscriber org; however, you can reference a Custom Setting (hierarchy type only) in a default value formula using a $Setup reference. This allows some customization by editing the Custom Setting at an organization, profile, or individual user level.

To create a record in the Season object, we need to first create a tab for it. Perform the following steps in the package org to try out this process:

  1. Create a tab for the Season object.
  2. Go to the Season tab and click on New.
  1. This results in the current year being displayed in the Year field, as shown in the following screenshot:

Unfortunately, by default, the Apex code does not apply default values when you construct an SObject in a direct manner via new Season(); however, if you utilize the SObjectType.newSObject method, you can request that defaults are applied as follows:

Season__c season = (Season__c) 
     Season__c.SObjectType.newSObject(null, true); 
System.assertEquals('2019', season.Year__c); 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.36.249