Chapter 115% of the exam12 min
Advanced Developer Fundamentals
How locale, time zone and multiple currencies change what Apex, SOQL and Lightning web components return, when and how to grant access with Apex managed sharing, and how to choose between custom metadata types and custom settings.
By the end of this chapter you can
- Predict how a user's locale, language and time zone change the values that Apex, SOQL and Lightning web components produce
- Query, filter and display currency fields correctly in a multi-currency org, with and without advanced currency management
- Work with address and geolocation compound fields and translated custom labels in code
- Create, change and recalculate Apex managed sharing, and justify it over sharing rules and manual sharing
- Choose the right sharing keyword and access mode for each class and database operation
- Choose between custom metadata types, list custom settings and hierarchy custom settings, and read each one efficiently
Localisation and multiple currencies
Scenario: A UK company's org gains users in Germany and Japan. A Lightning web component shows opportunity amounts and close dates, a scheduled job writes a file for a finance system, and managers want pipeline figures in their own currency. Users expect familiar formats, but the file must look the same whoever runs the job.
Four settings that change what code returns
Administrators set company defaults on the Company Information page, and users can override them on their Language & Time Zone settings page. Locale sets the format of dates, times, numbers, names, addresses and phone numbers; language sets interface text and translations; time zone sets how date/time values are shown; and in a multi-currency org the personal currency is the default for the user's opportunities, quotes and reports. Apex reads them with UserInfo.getLocale(), getLanguage(), getTimeZone(), getDefaultCurrency() and isMultiCurrencyOrganization().
Dates, times and numbers in Apex and SOQL
Datetime.now() is based on a GMT calendar, and SOQL from a client application returns date/time values in UTC. Conversion to local time happens only in methods that do it:
| Apex | Time zone and format used |
|---|---|
hour(), date(), day(), format(), formatLong() |
The context user's time zone; format() also uses their locale |
hourGmt(), dateGMT(), formatGmt(pattern) |
GMT |
format(pattern, 'Europe/Berlin') |
The zone you name (use full IDs, not three-letter abbreviations) |
Decimal.format() |
The context user's locale |
Output for people can rely on user settings; output for another system should name its pattern and zone:
Datetime closes = Datetime.newInstanceGmt(2026, 7, 15, 14, 30, 0);
String forFinance = closes.format('yyyy-MM-dd HH:mm', 'Europe/Berlin'); // 2026-07-15 16:30
String forUser = closes.format(); // the running user's locale and time zoneIn SOQL, FORMAT(field) returns number, date, time and currency values formatted for the user's locale, convertTimezone(CreatedDate) converts to the user's time zone but only inside a date function such as HOUR_IN_DAY(), and toLabel(field) returns picklist values in the user's language. Both FORMAT() and toLabel() need an alias when the plain field is also selected.
Formatting in Lightning web components
Base components such as lightning-formatted-number, lightning-formatted-date-time and lightning-input follow the user's language, locale and time zone without code. For your own formatting, import properties such as locale, currency and timeZone from @salesforce/i18n and pass them to the JavaScript Intl API.
<lightning-formatted-number value={amount} format-style="currency"
currency-code={record.CurrencyIsoCode}></lightning-formatted-number>@salesforce/i18n/currency is the user's currency code, so label a record's amount with the record's own CurrencyIsoCode, as above. The component shows two decimal places for currency unless minimum-fraction-digits says otherwise. On LWR sites, timeZone comes from the browser and the currency properties aren't supported.
Multiple currencies
Multiple currencies can't be turned off once enabled. Each active currency has a conversion rate to the corporate currency, stored in CurrencyType. Each record's CurrencyIsoCode field says which currency its amounts are in. Deactivating a currency leaves existing amounts alone, stops new amounts in it and moves users who had it as their personal currency to the corporate currency.
List<Opportunity> bigDeals = [
SELECT Name, convertCurrency(Amount)
FROM Opportunity
WHERE Amount > EUR100000
WITH USER_MODE
];convertCurrency()belongs in SELECT only. A WHERE clause uses an ISO-coded literal, which compares each record against the equivalent amount in its own currency; a bare number is compared as it is.- It can't be used in ORDER BY (sorting already uses converted values) or around an aggregate. With GROUP BY or HAVING, aggregate currency results come back in the corporate currency.
| Static conversion rates | Advanced currency management | |
|---|---|---|
| Stored in | CurrencyType |
DatedConversionRate (StartDate, NextStartDate, ConversionRate) |
| Used for | All currency fields (all other fields once advanced management is on) | Opportunities, opportunity products and opportunity history, using a date on the record such as CloseDate |
| History | Old rates aren't kept: a new rate changes every conversion | Each rate applies from its start date until the next one |
When advanced currency management is first enabled, the existing rates become the first dated set, valid for all time. Visualforce apex:inputField and apex:outputField then can't display currency fields.
Compound fields
Address fields such as BillingAddress and geolocation fields group several component fields. They're read-only: read them through an Address or Location variable, and write the components, such as BillingCity or Location__latitude__s. Dot notation on the parent, as in acc.BillingAddress.City, isn't allowed.
for (Account acc : [SELECT Name, BillingAddress FROM Account
WHERE DISTANCE(BillingAddress, GEOLOCATION(51.5072, -0.1276), 'km') < 50
WITH USER_MODE]) {
Address addr = acc.BillingAddress; // then addr.getCity(), addr.getDistance(...)
}DISTANCE() takes the field first and GEOLOCATION() second, supports only < and >, works in WHERE, ORDER BY and SELECT but not GROUP BY, and its unit ('mi' or 'km') can't be a bind variable. Apart from distance conditions, address fields can't be filtered in WHERE, and formulas can use only ISBLANK, ISCHANGED and ISNULL on compound fields.
Translated text: custom labels
Custom labels hold text of up to 1,000 characters, translated with Translation Workbench.
| Where | Syntax |
|---|---|
| Apex, user's language | System.Label.Order_Confirmed |
| Apex, chosen language | Label.get('', 'Order_Confirmed', 'de'), where an empty namespace means the org's own |
| Lightning web component | import ORDER_CONFIRMED from '@salesforce/label/c.Order_Confirmed'; |
| Visualforce | {!$Label.Order_Confirmed} |
Exam tip:
convertCurrency()appears only in SELECT; filters use literals such asUSD5000, and aggregates return the corporate currency. Dated exchange rates apply only to opportunities, opportunity products and opportunity history. Datetime methods such ashour()andformat()use the running user's time zone; theirGmttwins don't.
Sharing objects and Apex managed sharing
Scenario: A recruiting app stores jobs in Job__c with a Private org-wide default. Each job names a recruiter in a lookup to User, who needs edit access that follows the field when it changes and survives changes of owner. Sharing rules share with groups and roles, not with whoever a field names, so the developer writes Apex managed sharing.
Share objects
Explicit record access lives in a share object: AccountShare, ContactShare and, for custom objects, Job__Share. Each row says which record, who, how much and why.
| Field | Meaning |
|---|---|
ParentId |
The record shared. Can't be updated |
UserOrGroupId |
A user, public group, role group or territory group (never an unauthenticated guest user). Can't be updated |
AccessLevel |
Read or Edit (standard share objects prefix the object name, as in LeadAccessLevel). All is internal and can't be granted |
RowCause |
Why the access exists, which decides who can change the row. Can't be updated |
Access from the org-wide default, the role hierarchy (worked out at run time) and View All or Modify All permissions isn't stored as share rows. Detail objects in a master-detail relationship have no share object: the master's sharing decides. A share must grant more than the org-wide default, so the object can't be Public Read/Write; a share that adds nothing fails with FIELD_FILTER_VALIDATION_EXCEPTION naming AccessLevel, which code can treat as harmless.
Row causes
| Kind | RowCause | Created by | When the owner changes |
|---|---|---|---|
| Managed sharing | Owner, Rule, Team, ImplicitChild, ImplicitParent, TerritoryRule |
The platform; can't be changed directly | Maintained by the platform |
| Manual sharing | Manual (the default) |
Record owner, users with full access, or code | Removed |
| Apex managed sharing | An Apex sharing reason, such as Recruiter__c |
Apex or SOAP API; only users with Modify All Data can add or change it | Kept, also when the owner is deactivated |
For a custom object, Apex sharing reasons are created in its Apex Sharing Reasons related list. Code refers to one as Schema.Job__Share.RowCause.Recruiter__c, and its translatable label appears in the Reason column. Separate reasons let one user hold several shares for different reasons, and let code delete only its own rows.
Writing shares from a trigger
Because UserOrGroupId and RowCause can't be updated, reassigning access means deleting the old row and inserting a new one. Filtering on your own reason guarantees you never remove manual or rule-based access.
trigger JobSharing on Job__c (after insert, after update) {
Set<Id> reassigned = new Set<Id>();
List<Job__Share> grants = new List<Job__Share>();
for (Job__c job : Trigger.new) {
Job__c old = Trigger.isUpdate ? (Job__c) Trigger.oldMap.get(job.Id) : null;
if (old != null && old.Recruiter__c == job.Recruiter__c) continue;
if (old != null) reassigned.add(job.Id);
if (job.Recruiter__c != null) {
grants.add(new Job__Share(ParentId = job.Id, UserOrGroupId = job.Recruiter__c,
AccessLevel = 'Edit', RowCause = Schema.Job__Share.RowCause.Recruiter__c));
}
}
List<Job__Share> stale = [SELECT Id FROM Job__Share WHERE ParentId IN :reassigned
AND RowCause = :Schema.Job__Share.RowCause.Recruiter__c WITH SYSTEM_MODE];
delete as system stale;
Database.insert(grants, false, AccessLevel.SYSTEM_MODE); // then check each SaveResult
}In a real org this logic belongs in a handler class.
Recalculation
When an object's org-wide default changes, Salesforce recalculates sharing and deletes shares that have become redundant. To rebuild your own rows, write a class that implements Database.Batchable and select it in the custom object's Apex Sharing Recalculations related list: it then runs every time the org-wide default changes. Administrators can also run it from the object, and Database.executeBatch() starts it from code. Its execute method typically deletes the rows with the app's reasons for the batch's records and inserts fresh ones.
Sharing keywords and access modes
| Declaration | Record access |
|---|---|
with sharing |
The user's sharing applies. Classes with no declaration run this way in API version 67.0 and later |
without sharing |
Sharing is ignored. Use it for targeted elevation only |
inherited sharing |
The caller's mode; with sharing when the class is the entry point (Aura controller, @AuraEnabled method called from a Lightning web component, Visualforce controller, Apex REST service, asynchronous Apex) |
- Sharing keywords don't enforce object or field permissions; access modes do. From API version 67.0, database operations run in user mode by default (system mode at 66.0 and earlier). Set it with
WITH USER_MODEorWITH SYSTEM_MODE,insert as useroras system, andAccessLevel.USER_MODEin Database methods. - User mode always applies the user's sharing. In system mode, the class's sharing keyword decides.
- Triggers run without sharing, but at API version 67.0 and later their queries and DML default to user mode.
- A method keeps the sharing of the class that defines it (except in
inherited sharingclasses), and inner classes don't inherit the outer class's mode.
When Apex managed sharing is justified
| Requirement | Best fit |
|---|---|
| Records owned by one group, or matching field criteria, shared with a group or role | Sharing rule |
| Access follows a user named in a field or logic rules can't express, and must survive owner changes | Apex managed sharing |
| A packaged app that must bring its own sharing logic | Apex managed sharing: sharing rules can't be packaged |
| Code that must read records the user can't see, for one narrow task | A without sharing class or system mode, not new share rows |
Apex managed sharing costs code for every relevant change, a recalculation class and tests. Criteria-based sharing can't be created or tested in Apex.
Exam tip: "Share with the user in a lookup field and keep it when the owner changes" is Apex managed sharing with an Apex sharing reason, never
RowCause = Manual. "Rebuild shares after the org-wide default changes" is aDatabase.Batchableclass registered for Apex sharing recalculation.
Custom metadata types and custom settings
Scenario: An app calculates discounts from bands that differ by country, needs a switch that stops its triggers for the integration user during nightly loads, and must install in new orgs with its configuration already in place.
Custom settings
Custom settings are like custom objects whose data sits in the application cache, so Apex reads it without database queries.
- List custom settings hold one org-wide set of named data sets, such as country codes, that doesn't vary by user.
getAll()returns a map keyed by data set name;getInstance(name)andgetValues(name)return the same record, or null. - Hierarchy custom settings hold values at org, profile and user level, and the most specific value wins.
| Hierarchy method | Returns |
|---|---|
getInstance() |
The running user's values, with empty fields filled from the profile, then the org. With no user-level record, a new record with a null Id |
getInstance(userOrProfileId) |
The same for a named user or profile |
getOrgDefaults() |
The org-level record (an empty record if there's none) |
getValues(userOrProfileId) |
Only the values stored at that level, with nothing merged |
public with sharing class TriggerSwitch {
public static Boolean isOff() {
return Integration_Switches__c.getInstance().Disable_Triggers__c == true;
}
}- A SOQL query on a custom setting skips the cache and behaves like a custom object query. Apex can create, update and delete records with DML.
- Records don't deploy: packages, change sets and the Metadata API carry only the definition, so data is entered by hand or by Apex after installation.
- Apex tests treat custom setting data as data: create it in
@testSetup(recommended) or useSeeAllData=true. - Protected visibility protects only a setting installed from a managed package: the subscriber can't edit it or read it from Apex. Otherwise settings are public, readable by every profile including guest users, so secrets belong in Named Credentials or encrypted fields.
Custom metadata types
A custom metadata type (suffix __mdt) defines a structure, and its records are metadata too. Records therefore travel with the type in change sets, the Metadata API and packages, and creating them needs the Customize Application permission. Besides the usual field types, a metadata relationship field links to another custom metadata type, but never to records of the same type.
| Where | How to read records |
|---|---|
| Apex | Discount_Band__mdt.getAll() (map keyed by DeveloperName), getInstance(developerName), getInstance(qualifiedApiName) or getInstance(recordId): cached, null when nothing matches, and only the first 255 characters of each field |
| SOQL | Full field values, and custom metadata queries have no limit in a transaction |
| Formulas, validation rules, default values | $CustomMetadata.Discount_Band__mdt.Large.Max_Discount__c |
| Flow | A Get Records element on the type |
Apex can create and update records, but not delete them, through the Metadata API classes. The deployment is asynchronous, can report back to a class that implements Metadata.DeployCallback, and the number of enqueued deployments is limited.
Metadata.CustomMetadata band = new Metadata.CustomMetadata();
band.fullName = 'Discount_Band.Large';
Metadata.CustomMetadataValue pct = new Metadata.CustomMetadataValue();
pct.field = 'Max_Discount__c';
pct.value = 15;
band.values.add(pct);
Metadata.DeployContainer container = new Metadata.DeployContainer();
container.addMetadata(band);
Id jobId = Metadata.Operations.enqueueDeployment(container, null);In a managed package, protected records can be read only by code in the same package as the records or their type. Subscriber code, SOQL, the APIs and Setup can't see them, subscribers can't create records of a protected type, and the developer changes them through package upgrades.
Choosing
| Custom metadata type | List custom setting | Hierarchy custom setting | |
|---|---|---|---|
| Records deploy and package | Yes | No | No |
| Values by user or profile | No | No | Yes |
| Relationship fields | Metadata relationships | No | No |
| Changed from Apex | Metadata API deployment, asynchronous, no delete | DML | DML |
Choose a custom metadata type for configuration that must move between orgs with the code, such as rates, mappings and routing rules. Choose a hierarchy custom setting for values that differ by user or profile, such as a trigger bypass for one integration user. A list custom setting suits simple org-wide data that never needs deploying, though custom metadata types often serve better.
Exam tip: "Deploy the configuration records with the code" points to custom metadata types; "different for this user or profile" points to a hierarchy custom setting.
getValues()never merges levels, and protected visibility protects nothing outside a managed package.
Hands-on exercise
Configure an app with custom metadata and a hierarchy custom setting
Store discount bands in a custom metadata type, add a per-user switch in a hierarchy custom setting, and read both, with locale-aware formatting, from Apex.
Use a free Salesforce Developer Edition org — never a production org.
0 of 8 steps done
How to check your work: getInstance() returns true for you while getOrgDefaults() returns false, getAll() returns the keys Standard and Large, and the formatted number changes its separators after you change your locale.
Domain quiz: Advanced Developer Fundamentals
10 questions from the 41 in this domain, different each time and checked as you go. Anything you miss is saved to Mistakes review.
- Questions
- 10
- Time
- Untimed
- Feedback
- After each answer
New questions each time you start, drawn from the bank, unseen ones first.