0% found this document useful (0 votes)
350 views4,295 pages

Salesforce Apex Reference Guide

The Apex Reference Guide, version 64.0 for Summer '25, provides comprehensive information on Apex programming, including DML operations, namespaces, and various classes and interfaces. It includes detailed sections on the Apex DML Statements, ApexPages Namespace, AppLauncher Namespace, and Auth Namespace, among others. The document is intended for developers using Salesforce and was last updated on August 15, 2025.

Uploaded by

Heinlinaung Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
350 views4,295 pages

Salesforce Apex Reference Guide

The Apex Reference Guide, version 64.0 for Summer '25, provides comprehensive information on Apex programming, including DML operations, namespaces, and various classes and interfaces. It includes detailed sections on the Apex DML Statements, ApexPages Namespace, AppLauncher Namespace, and Auth Namespace, among others. The document is intended for developers using Salesforce and was last updated on August 15, 2025.

Uploaded by

Heinlinaung Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Apex Reference Guide

Version 64.0, Summer ’25

Last updated: August 15, 2025


© Copyright 2000–2025 Salesforce, Inc. All rights reserved. Salesforce is a registered trademark of Salesforce, Inc., as are other

names and marks. Other marks appearing herein may be trademarks of their respective owners.
CONTENTS

Apex Reference Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


Release Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Apex DML Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Apex DML Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
ApexPages Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Action Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Component Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
IdeaStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
IdeaStandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
KnowledgeArticleVersionStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Message Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
StandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
StandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
AppLauncher Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
AppMenu Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
ChangePasswordController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
CommunityLogoController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
EmployeeLoginLinkController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
ForgotPasswordController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
IdentityHeaderController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
LoginFormController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
SelfRegisterController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
SocialLoginController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Approval Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
LockResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
ProcessRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
ProcessResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
ProcessSubmitRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
ProcessWorkitemRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
UnlockResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Auth Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
AuthConfiguration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
AuthProviderCallbackState Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
AuthProviderPlugin Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
AuthProviderPluginClass Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
AuthProviderTokenResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
AuthToken Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
CommunitiesUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
ConfigurableSelfRegHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Contents

ConfirmUserRegistrationHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106


ConnectedAppPlugin Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
CustomOneTimePasswordDeliveryHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . 115
CustomOneTimePasswordDeliveryResult Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
ExternalClientAppOauthHandler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
GeneratedUserData Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
HeadlessSelfRegistrationHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
HeadlessUserDiscoveryHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
HeadlessUserDiscoveryResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
HttpCalloutMockUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
IntegratingAppType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
InvocationContext Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
JsonValueOutput Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
JWS Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
JWT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
JWTBearerTokenExchange Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
JWTUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
LightningLoginEligibility Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
LoginDiscoveryHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
LoginDiscoveryMethod Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
MyDomainLoginDiscoveryHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Oauth2TokenExchangeHandler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
OAuth2TokenExchangeType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
OAuthRefreshResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
OauthToken Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
OauthTokenType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
RegistrationHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
SamlJitHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
SessionManagement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
SessionLevel Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
TokenValidationResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
UserData Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
VerificationAction Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
VerificationMethod Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
VerificationPolicy Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
VerificationResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Auth Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Cache Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
CacheBuilder Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Org Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
OrgPartition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Partition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Session Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
SessionPartition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Contents

Cache Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277


Visibility Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Canvas Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
ApplicationContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
CanvasLifecycleHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
ContextTypeEnum Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
EnvironmentContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
RenderContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Canvas Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
ChatterAnswers Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
AccountCreator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
CommerceBuyGrp Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
BuyerGroupEvaluationService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
BuyerGroupRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
BuyerGroupResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
CommerceExtension Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
ExtensionInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Resolution Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
ResolutionException Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
ResolutionStates Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
ResolutionStrategy Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
CommerceOrders Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
CommercePayments Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
AbstractResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
AbstractTransactionResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
AddressRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
AlternativePaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
AlternativePaymentMethodResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
AuditParamsRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
AuthApiPaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
AuthorizationRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
AuthorizationResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
AuthorizationReversalRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
AuthorizationReversalResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
BaseApiPaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
BaseNotification Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
BasePaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
BaseRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
CaptureNotification Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
CaptureRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
CaptureResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
CardCategory Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
CardPaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Contents

CardPaymentMethodResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391


CardType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
CustomMetadataTypeInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
GatewayErrorResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
GatewayNotificationResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
GatewayResponse Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
NotificationClient Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
NotificationSaveResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
NotificationStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
PaymentGatewayAdapter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
PaymentGatewayAsyncAdapter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
PaymentGatewayContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
PaymentGatewayNotificationContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
PaymentGatewayNotificationRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
PaymentMethodDetailsResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
PaymentMethodTokenizationRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
PaymentMethodTokenizationResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
PaymentsHttp Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
PostAuthApiPaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
PostAuthorizationRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
PostAuthorizationResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
ReferencedRefundNotification Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
ReferencedRefundRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
ReferencedRefundResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
RefundRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
RequestType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
SaleApiPaymentMethodRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
SaleRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
SaleResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
SalesforceResultCode Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
SalesforceResultCodeInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
CommerceTax Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
AbstractTransactionResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
AddressesResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
AddressResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
AmountDetailsResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
CalculateTaxRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
CalculateTaxResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
CalculateTaxType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
ErrorResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
HeaderTaxAddressesRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
ImpositionResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
JurisdictionResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
LineItemResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
Contents

LineTaxAddressesRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508


RequestType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
ResultCode Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
RuleDetailsResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
TaxAddressesRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
TaxAddressRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
TaxApiException Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
TaxCustomerDetailsRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
TaxDetailsResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
TaxEngineAdapter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
TaxEngineContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
TaxLineItemRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
TaxSellerDetailsRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
TaxTransactionRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
TaxTransactionStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
TaxTransactionType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
ComplianceMgmt Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Compression Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Level Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
Method Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
ZipEntry Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
ZipReader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
ZipWriter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
Compression Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
ConnectApi Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
ActionLinks Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
Announcements Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
BotVersionActivation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
CdpActivation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
CdpActivationTarget Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
CdpAudienceDMO Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
CdpCalculatedInsight Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
CdpConnection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
CdpDataSpace Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
CdpDataStreams Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
CdpIdentityResolution Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
CdpMachineLearning Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
CdpQuery Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
CdpSegment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
Chatter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
ChatterFavorites Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
ChatterFeeds Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
ChatterGroups Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1123
ChatterMessages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1168
Contents

ChatterUsers Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1192


Clm Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1228
CommerceBuyerExperience Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1229
CommerceCart Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1287
CommerceCatalog Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1337
CommerceCatalogManagement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1361
CommercePromotions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1363
CommerceSearch Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1366
CommerceSearchConnectFamily Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1370
CommerceSearchSettings Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1372
CommerceStorePricing Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375
CommerceWishlist Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1378
Communities Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1396
CommunityModeration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1398
ContentHub Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1427
ConversationApplicationDefinition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1501
Datacloud Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1502
EinsteinLLM Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1507
EmailMergeFieldService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1511
EmployeeProfiles Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1512
Exchanges Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1521
ExtendedCommerceDelivery Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1522
ExternalEmailServices Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1524
ExternalManagedAccount Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1525
FieldService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1527
FulfillmentOrder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1529
IBusinessObjectivesAndRecsFamily Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1534
Knowledge Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1539
LightningScheduler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544
ManagedContent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1549
ManagedContentChannels Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1579
ManagedContentDelivery Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1582
ManagedContentSpaces Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1607
ManagedTopics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1612
MarketingIntegration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1626
Mentions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1629
Missions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1635
NamedCredentials Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1640
NavigationMenu Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1655
NextBestAction Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1659
OmnichannelInventoryService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1665
OMSAnalytics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1673
Orchestration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1678
OrderPaymentSummary Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1680
Contents

OrderSummary Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1681


OrderSummaryCreation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1694
Organization Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1695
PardotBusinessUnitContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1696
Payments Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1697
Personalization Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1703
PickTicket Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1715
QuestionAndAnswers Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1716
Recommendations Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1720
RecordFilterCriteriaFamily Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1780
Records Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1781
RegisterGuestBuyer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1783
Repricing Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1784
ReturnOrder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1787
Routing Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1789
SalesforceInbox Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1794
Search Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1795
Sites Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1805
SmartDataDiscovery Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1807
SocialEngagement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1807
Surveys Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1818
TaxPlatform Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1819
Topics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1820
UserProfiles Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1857
Zones Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1867
ConnectApi Input Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1877
ConnectApi Output Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2060
ConnectApi Enums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2485
ConnectApi Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2526
ConnectApi Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2527
ConnectApi Release Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2528
Context Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2528
Database Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2528
Batchable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2529
BatchableContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2531
Cursor Class (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2532
DeletedRecord Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2534
DeleteFilter Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2535
DeleteResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2536
DMLOptions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2537
DmlOptions.AssignmentRuleHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2540
DMLOptions.DuplicateRuleHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2542
DmlOptions.EmailHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2544
DuplicateError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2546
Contents

EmptyRecycleBinResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2549


Error Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2550
GetDeletedResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2551
GetUpdatedResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2553
LeadConvert Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2554
LeadConvertResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2565
MergeResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2567
QueryLocator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2569
QueryLocatorIterator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2570
SaveResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2572
UndeleteResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2574
UpsertResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2576
Datacloud Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2577
AdditionalInformationMap Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2578
DuplicateResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2579
FieldDiff Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2584
FindDuplicates Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2585
FindDuplicatesByIds Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2587
FindDuplicatesResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2588
MatchRecord Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2591
MatchResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2593
DataRetrieval Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2595
DataSource Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2595
AsyncDeleteCallback Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2598
AsyncSaveCallback Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2599
AuthenticationCapability Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2599
AuthenticationProtocol Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2600
Capability Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2600
Column Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2602
ColumnSelection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2625
Connection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2627
ConnectionParams Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2632
DataSourceUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2636
DataType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2637
DeleteContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2638
DeleteResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2639
Filter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2642
FilterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2644
IdentityType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2645
Order Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2645
OrderDirection Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2648
Provider Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2648
QueryAggregation Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2650
QueryContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2650
Contents

QueryUtils Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2652


ReadContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2655
SearchContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2656
SearchUtils Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2658
Table Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2659
TableResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2663
TableSelection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2669
UpsertContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2670
UpsertResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2671
DataSource Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2674
DataWeave Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2675
Result Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2675
Script Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2676
Dom Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2679
Document Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2679
XmlNode Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2682
XmlNodeType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2692
embeddedai Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2693
ApexMap Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2693
RecordApexRepresentation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2695
EventBus Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2697
ChangeEventHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2697
EventPublishFailureCallback Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2703
EventPublishSuccessCallback Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2704
FailureResult Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2705
SuccessResult Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2706
TestBroker Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2706
TriggerContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2708
ExternalService Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2711
Flow Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2711
Interview Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2711
Flowtesting Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2716
FormulaEval Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2716
FormulaBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2717
FormulaGlobal Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2721
FormulaInstance Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2722
FormulaReturnType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2724
fsccashflow Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2725
FSCCashFlowUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2725
Functions Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2735
Function Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2736
FunctionCallback Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2740
FunctionErrorType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2742
FunctionInvocation Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2742
Contents

FunctionInvocationError Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2745


FunctionInvocationStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2746
FunctionInvokeMock Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2747
MockFunctionInvocationFactory Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2750
ise_bots_apex Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2751
DynamicMenuItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2752
industriesNlpSvc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2755
NlpResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2756
NlpSummarizationResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2757
IndustriesDigitalLending Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2757
Invocable Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2758
Action Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2758
Action.Error Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2763
Action.Result Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2765
InvoiceWriteOff Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2767
IsvPartners Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2767
AppAnalytics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2767
KbManagement Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2770
PublishingService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2770
LxScheduler Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2781
GetAppointmentCandidatesInput Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2782
GetAppointmentCandidatesInputBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2784
GetAppointmentSlotsInput Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2792
GetAppointmentSlotsInputBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2794
SchedulerResources Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2801
SkillRequirement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2806
SkillRequirementBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2806
WorkType Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2808
WorkTypeBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2808
ServiceResourceScheduleHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2812
ServiceAppointmentRequestInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2815
ServiceResourceInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2819
ServiceResourceSchedule Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2822
UnavailableTimeslot Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2824
Messaging Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2826
AttachmentRetrievalOption Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2827
Email Class (Base Email Methods) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2827
EmailFileAttachment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2831
InboundEmail Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2833
InboundEmail.AuthenticationResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2839
InboundEmail.AuthenticationResultField Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2841
InboundEmail.BinaryAttachment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2842
InboundEmail.TextAttachment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
InboundEmailResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2847
Contents

InboundEnvelope Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2848


MassEmailMessage Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2849
InboundEmail.Header Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2851
PushNotification Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2852
PushNotificationPayload Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2856
CustomNotification Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2858
RenderEmailTemplateBodyResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2865
RenderEmailTemplateError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2867
SendEmailError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2868
SendEmailResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2870
SingleEmailMessage Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2871
Metadata Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2887
AnalyticsCloudComponentLayoutItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2890
ConsoleComponent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2894
Container Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2896
CustomConsoleComponents Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2899
CustomMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2901
CustomMetadataValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2903
DeployCallback Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2905
DeployCallbackContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2907
DeployContainer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2908
DeployDetails Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2911
DeployMessage Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2912
DeployProblemType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2917
DeployResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2918
DeployStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2926
FeedItemTypeEnum Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2926
FeedLayout Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2928
FeedLayoutComponent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2931
FeedLayoutComponentType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2933
FeedLayoutFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2934
FeedLayoutFilterPosition Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2936
FeedLayoutFilterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2936
Layout Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2936
LayoutColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2944
LayoutHeader Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2946
LayoutItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2946
LayoutSection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2951
LayoutSectionStyle Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2954
Metadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2954
MetadataType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2955
MetadataValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2956
MiniLayout Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2956
Operations Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2958
Contents

PlatformActionList Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2962


PlatformActionListContextEnum Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2964
PlatformActionListItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2965
PlatformActionTypeEnum Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2967
PrimaryTabComponents Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2967
QuickActionList Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2969
QuickActionListItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2970
RelatedContent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2971
RelatedContentItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2972
RelatedList Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2974
RelatedListItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2975
ReportChartComponentLayoutItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2978
ReportChartComponentSize Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2982
SidebarComponent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2982
SortOrder Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2986
StatusCode Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2987
SubtabComponents Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2987
SummaryLayoutStyleEnum Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2989
SummaryLayout Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2989
SummaryLayoutItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2992
UiBehavior Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2994
PlaceQuote Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2995
Pref_center Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2995
LoadFormData Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2995
LoadParameters Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3002
PreferenceCenterApexHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3003
SubmitFormData Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3004
SubmitParameters Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3008
TokenType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3009
TokenUtility Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3009
ValidationResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3012
Process Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3012
Plugin Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3013
PluginDescribeResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3015
PluginDescribeResult.InputParameter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3017
PluginDescribeResult.OutputParameter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3021
PluginDescribeResult.ParameterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3023
PluginRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3024
PluginResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3025
QuickAction Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3025
DescribeAvailableQuickActionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3026
DescribeLayoutComponent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3028
DescribeLayoutItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3029
DescribeLayoutRow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3032
Contents

DescribeLayoutSection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3033


DescribeQuickActionDefaultValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3036
DescribeQuickActionParameter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3037
DescribeQuickActionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3040
QuickActionDefaults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3057
QuickActionDefaultsHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3059
QuickActionRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3064
QuickActionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3067
SendEmailQuickActionDefaults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3069
Reports Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3071
AggregateColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3075
BucketField Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3076
BucketFieldValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3084
BucketType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3087
ColumnDataType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3088
ColumnSortOrder Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3089
CrossFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3089
CsfGroupType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3094
DateGranularity Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3095
DetailColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3095
Dimension Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3097
EvaluatedCondition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3097
EvaluatedConditionOperator Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3101
FilterOperator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3101
FilterValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3102
FormulaType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3103
GroupingColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3104
GroupingInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3105
GroupingValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3107
NotificationAction Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3108
NotificationActionContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110
ReportCsf Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3111
ReportCurrency Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3121
ReportDataCell Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3122
ReportDescribeResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3123
ReportDetailRow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3124
ReportDivisionInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3124
ReportExtendedMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3125
ReportFact Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3127
ReportFactWithDetails Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3128
ReportFactWithSummaries Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3129
ReportFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3130
ReportFormat Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3136
ReportFilterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3137
Contents

ReportInstance Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3137


ReportManager Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3139
ReportMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3145
ReportResults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3164
ReportScopeInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3167
ReportScopeValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3168
ReportType Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3169
ReportTypeColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3170
ReportTypeColumnCategory Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3172
ReportTypeMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3173
SortColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3175
StandardDateFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3177
StandardDateFilterDuration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3180
StandardDateFilterDurationGroup Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3182
StandardFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3183
StandardFilterInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3185
StandardFilterInfoPicklist Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3186
StandardFilterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3187
SummaryValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3188
ThresholdInformation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3189
TopRows Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3190
Reports Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3193
RevSignaling Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3194
RevSalesTrxn Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3194
RichMessaging Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3194
AbstractTiming Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3196
AddressableContact Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3196
AuthRequestHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3199
AuthRequestResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3202
AuthRequestResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3204
AuthRequestResultStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3206
DeferredTiming Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3206
MessageDefinitionInputParameter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3208
PaymentItemStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3212
PaymentLineItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3212
PaymentMethod Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3218
PostalAddress Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3219
ProcessPaymentHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3223
ProcessPaymentRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3224
ProcessPaymentResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3228
ProcessPaymentResultStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3230
RecurringTiming Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3230
ShippingMethod Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3234
TimeSlotOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3238
Contents

TimingIntervalUnit Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3241


TimingType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3242
Salesforce_Backup Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3242
SalesforceBackupIntegrationUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3242
Schema Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3242
ChildRelationship Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3244
DataCategory Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3246
DataCategoryGroupSobjectTypePair Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3247
DescribeColorResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3249
DescribeDataCategoryGroupResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3251
DescribeDataCategoryGroupStructureResult Class . . . . . . . . . . . . . . . . . . . . . . . . . 3253
DescribeFieldResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3256
DescribeIconResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3273
DescribeSObjectResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3276
DescribeTabResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3298
DescribeTabSetResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3301
DisplayType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3304
FieldDescribeOptions Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3305
FieldSet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3306
FieldSetMember Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3310
PicklistEntry Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3312
RecordTypeInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3314
SOAPType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3317
SObjectDescribeOptions Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3317
SObjectField Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3318
SObjectType Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3319
Search Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3323
KnowledgeSuggestionFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3323
QuestionSuggestionFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3328
SearchResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3332
SearchResults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3333
SuggestionOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3334
SuggestionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3336
SuggestionResults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3337
Sfc Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3338
ContentDownloadContext Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3338
ContentDownloadHandler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3339
ContentDownloadHandlerFactory Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3340
Sfdc_Checkout Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3342
AsyncCartProcessor Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3342
B2BCheckoutController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3343
IntegrationInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3344
IntegrationStatus Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3346
IntegrationStatus.Status Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3346
Contents

Sfdc_Enablement Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3347


LearningEvaluation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3347
LearningEvaluationResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3349
LearningItemEvaluationHandler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3351
LearningItemProgressStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3353
LearningItemSerializeDeserializer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3354
sfdc_surveys Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3357
SurveyInvitationLinkShortener Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3357
Example Implementation to Associate SurveySubjects with SurveyInvitation and
SurveyResponses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3359
Site Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3360
UrlRewriter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3361
Site Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3362
Slack Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3362
Support Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3364
EmailTemplateSelector Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3364
MilestoneTriggerTimeCalculator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3366
System Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3368
AccessLevel Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3375
AccessType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3379
Address Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3379
Answers Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3384
ApexPages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3386
Approval Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3389
Assert Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3401
AsyncInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3413
AsyncOptions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3415
Blob Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3416
Boolean Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3419
BusinessHours Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3421
CallbackStatus Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3424
Callable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3424
Cases Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3427
Collator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3430
Comparable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3432
Comparator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3435
Continuation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3437
Cookie Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3441
Crypto Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3449
Custom Metadata Type Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3475
Custom Settings Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3479
Database Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3489
Date Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3584
Datetime Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3595
Contents

Decimal Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3618


Domain Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3632
DomainCreator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3634
DomainParser Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3639
DomainType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3640
Double Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3641
EmailMessages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3645
EncodingUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3648
Enum Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3652
EventBus Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3653
Exception Class and Built-In Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3658
ExternalServiceTest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3663
FlexQueue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3664
FeatureManagement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3667
Formula Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3672
FormulaRecalcFieldError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3674
FormulaRecalcResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3675
Http Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3676
HttpCalloutMock Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3677
HttpRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3678
HttpResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3688
Id Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3694
Ideas Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3701
InstallHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3706
Integer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3709
JSON Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3711
JSONGenerator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3718
JSONParser Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3732
JSONToken Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3744
Label Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3745
Limits Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3748
List Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3762
Location Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3777
LoggingLevel Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3780
Long Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3781
Map Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3783
Matcher Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3795
Math Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3808
Messaging Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3833
MultiStaticResourceCalloutMock Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3841
Network Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3844
Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3850
OrgLimit Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3852
OrgLimits Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3854
Contents

PageReference Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3855


Packaging Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3868
Pattern Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3869
Queueable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3873
QueueableContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3875
QueueableDuplicateSignature Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3876
QueueableDuplicateSignature.Builder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3876
QuickAction Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3880
Quiddity Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3884
RemoteObjectController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3885
Request Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3889
ResetPasswordResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3890
RestContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3891
RestRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3892
RestResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3898
SandboxPostCopy Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3902
Schedulable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3904
SchedulableContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3905
Schema Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3906
Search Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3911
Security Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3916
SelectOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3920
Set Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3926
Site Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3937
SObject Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3959
SObjectAccessDecision Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3984
SoqlStubProvider Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3987
StaticResourceCalloutMock Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3990
String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3992
StubProvider Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4068
System Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4070
Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4096
Time Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4117
TimeZone Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4122
Trigger Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4125
TriggerOperation Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4128
Type Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4128
UninstallHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4136
URL Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4139
UserInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4149
UserManagement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4158
UUID Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4178
Version Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4180
WebServiceCallout Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4184
Contents

WebServiceMock Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4185


XmlStreamReader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4187
XmlStreamWriter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4201
TerritoryMgmt Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4208
OpportunityTerritory2AssignmentFilter Global Interface . . . . . . . . . . . . . . . . . . . . . . 4208
TxnSecurity Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4212
Event Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4212
EventCondition Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4216
AsyncCondition Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4218
PolicyCondition Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4219
UserProvisioning Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4221
ConnectorTestUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4221
UserProvisioningLog Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4223
UserProvisioningPlugin Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4225
VisualEditor Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4229
DataRow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4230
DesignTimePageContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4233
DynamicPickList Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4235
DynamicPickListRows Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4238
Wave Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4243
QueryBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4243
QueryNode Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4247
ProjectionNode Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4251
Templates Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4254
TemplatesSearchOptions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4257
Appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4259
Shipping Invoice Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4259
Reserved Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4271
Documentation Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4272
APEX REFERENCE GUIDE

Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Salesforce Platform server, in conjunction with calls to the API. This reference guide includes built-in Apex classes,
interfaces, enums, and exceptions, grouped by namespace. It also includes Apex DML statements to insert, update, merge, delete, and
restore data in Salesforce.
For information on the Apex development process, see Apex Developer Guide.

Note: In API version 51.0 and earlier, Apex Reference information was included in the Apex Developer Guide in the Apex Language
Reference section.

IN THIS SECTION:
Apex Release Notes
Use the Salesforce Release Notes to learn about the most recent updates and changes to Apex.
Apex DML Operations
You can perform DML operations using the Apex DML statements or the methods of the Database class. For lead conversion,
use the convertLead method of the Database class. There is no DML counterpart for it.
ApexPages Namespace
The ApexPages namespace provides classes used in Visualforce controllers.
AppLauncher Namespace
The AppLauncher namespace provides methods for managing the appearance of apps in the App Launcher, including their
visibility and sort order.
Approval Namespace
The Approval namespace provides classes and methods for approval processes.
Auth Namespace
The Auth namespace provides an interface and classes for single sign-on into Salesforce and session security management.
Cache Namespace
The Cache namespace contains methods for managing the platform cache.
Canvas Namespace
The Canvas namespace provides an interface and classes for canvas apps in Salesforce.
ChatterAnswers Namespace
The ChatterAnswers namespace provides an interface for creating Account records.
CommerceBuyGrp Namespace
The CommerceBuyGrp namespace provides classes and methods for retrieving information about the buyer groups associated
with a user.
CommerceExtension Namespace
Use the CommerceExtension namespace to define resolution strategies for registered Commerce extensions.
CommerceOrders Namespace
The CommerceOrders namespace provides classes and methods to place orders with integrated pricing, configuration, and
validation.

1
Apex Reference Guide

CommercePayments Namespace
Use the CommercePayments namespace to provide a safe and customizable platform for managing customer payments and
refunds.
CommerceTax Namespace
Manage the communication between Salesforce and an external tax engine.
ComplianceMgmt Namespace
The ComplianceMgmt namespace provides classes and methods to implement rule processors for compliance control.
Compression Namespace
The Compression namespace provides classes and methods to create and extract zip files.
ConnectApi Namespace
The ConnectApi namespace (also called Connect in Apex) provides classes for accessing the same data available in Connect
REST API. Use Connect in Apex to create custom experiences in Salesforce.
Context Namespace
The Context namespace provides classes and methods to manage the sharing and consumption of business application data
by using Context Service.
Database Namespace
The Database namespace provides classes used with DML operations.
Datacloud Namespace
The Datacloud namespace provides classes and methods for retrieving information about duplicate rules. Duplicate rules let
you control whether and when users can save duplicate records within Salesforce.
DataRetrieval Namespace
The DataRetrieval namespace provides classes and methods to record details of customer-agent engagements, as well as
transcripts of their conversations.
DataSource Namespace
The DataSource namespace provides the classes for the Apex Connector Framework. Use the Apex Connector Framework to
develop a custom adapter for Salesforce Connect. Then connect your Salesforce organization to any data anywhere via the Salesforce
Connect custom adapter.
DataWeave Namespace
The DataWeave namespace provides classes and methods to support the invocation of DataWeave scripts from Apex.
Dom Namespace
The Dom namespace provides classes and methods for parsing and creating XML content.
embeddedai Namespace
The embeddedai namespace provides classes and methods to manage and represent records and data in Apex to support
embedded AI features.
EventBus Namespace
The EventBus namespace provides classes and methods for platform events and Change Data Capture events.
ExternalService Namespace
The ExternalService namespace provides dynamically generated Apex service interfaces and Apex classes for complex
object data types.
Flow Namespace
The Flow namespace provides a class for advanced access to flows from Apex such as from Visualforce controllers and asynchronous
Apex.

2
Apex Reference Guide

Flowtesting Namespace
The flowtesting namespace provides dynamically generated Apex classes for flow tests that are created in Flow Builder.
FormulaEval Namespace
The FormulaEval namespace provides classes and methods to evaluate dynamic formulas for SObjects and Apex objects. Use the
methods to avoid unnecessary DML statements to recalculate formula field values or evaluate dynamic formula expressions.
fsccashflow Namespace
The fsccashflow namespace provides classes used in the FSCCashFlow Flexcards and its child Flexcards.
Functions Namespace
The Functions namespace provides classes and methods used to invoke and manage Salesforce Functions.
ise_bots_apex Namespace
The ise_bots_apex namespace provides classes and properties to facilitate dynamic content generation and data handling for
menu-driven bot interactions. Create and manage dynamic menu items that adapt to user inputs, context, and underlying object
data.
industriesNlpSvc
Stores the objects used in Industries Einstein Natural Language Processing (NLP) services.
IndustriesDigitalLending Namespace
The industriesDigitalLending namespace provides classes used in the Digital Lending OmniScripts and Integration
Procedures.
Invocable Namespace
The Invocable namespace provides classes for calling invocable actions from Apex.
InvoiceWriteOff Namespace
The InvoiceWriteOff namespace provides classes to create credit memos with the total charge amount on the invoice as
the write-off amount.
IsvPartners Namespace
The IsvPartners namespace provides a class associated with Salesforce ISV partner use cases, such as optimizing code, providing
great customer trial experiences, and driving feature adoption.
KbManagement Namespace
The KbManagement namespace provides a class for managing knowledge articles.
LxScheduler Namespace
The LxScheduler namespace provides an interface and classes for integrating Salesforce Scheduler with external calendars.
Messaging Namespace
The Messaging namespace provides classes and methods for Salesforce outbound and inbound email functionality.
Metadata Namespace
The Metadata namespace provides classes and methods for working with custom metadata in Salesforce
PlaceQuote Namespace
The PlaceQuote namespace provides classes and methods to create or update quotes with pricing preferences and configuration
options.
Pref_center Namespace
The Pref_center namespace provides an interface, classes, and methods to create and retrieve data in forms in Preference Manager.
Preference Manager, previously called Preference Center, is a feature within the Privacy Center app.
Process Namespace
The Process namespace provides an interface and classes for passing data between your organization and a flow.

3
Apex Reference Guide

QuickAction Namespace
The QuickAction namespace provides classes and methods for quick actions.
Reports Namespace
The Reports namespace provides classes for accessing the same data as is available in the Salesforce Reports and Dashboards
REST API.
RevSignaling Namespace
The RevSignaling namespace provides classes to extend the standard procedure plan implementation through custom logic.
A procedure plan helps you set up your procedures, configure the procedure execution settings, and relate them to a context
definition in one centralized location based on your requirements.
RevSalesTrxn Namespace
The RevSalesTrxn namespace provides classes and methods to create a sales transaction, such as a quote or an order, with
integrated pricing and configuration.
RichMessaging Namespace
Provides objects and methods for handling content in enhanced Messaging channels.
Salesforce_Backup Namespace
The Salesforce_Backup namespace provides classes and methods for Salesforce Backup.
Schema Namespace
The Schema namespace provides classes and methods for schema metadata information.
Search Namespace
The Search namespace provides classes for getting search results and suggestion results.
Sfc Namespace
The Sfc namespace contains classes used in Salesforce Files.
Sfdc_Checkout Namespace
The Sfdc_Checkout namespace provides an interface and classes for B2B Commerce apps in Salesforce.
Sfdc_Enablement Namespace
The sfdc_enablement namespace provides classes for creating custom learning items to implement custom exercise types
in Enablement programs. Lightning web components are used to render the custom exercises on Program Builder.
sfdc_surveys Namespace
The sfdc_surveys namespace provides an interface for shortening survey invitations.
Site Namespace
The Site namespace provides an interface for rewriting Sites URLs.
Slack Namespace
The Slack Namespace provides tools designed to accelerate and ease the process of developing Slack apps on the Salesforce
platform.
Support Namespace
The Support namespace provides an interface used for Case Feed.
System Namespace
The System namespace provides classes and methods for core Apex functionality.
TerritoryMgmt Namespace
The TerritoryMgmt namespace provides an interface used for territory management.

4
Apex Reference Guide Apex Release Notes

TxnSecurity Namespace
The TxnSecurity namespace provides an interface used for transaction security.
UserProvisioning Namespace
The UserProvisioning namespace provides methods for monitoring outbound user provisioning requests.
VisualEditor Namespace
The VisualEditor namespace provides classes and methods for interacting with the Lightning App Builder. The classes and
methods in this namespace operate on Lightning components, which include Lightning web components and Aura components.
Wave Namespace
The classes in the Wave namespace are part of the CRM Analytics Analytics SDK, designed to facilitate querying CRM Analytics data
from Apex code.
Appendices

Apex Release Notes


Use the Salesforce Release Notes to learn about the most recent updates and changes to Apex.
For Apex updates and changes that impact the Salesforce Platform, see the Apex Release Notes.
For new and changed Apex classes, methods, exceptions and interfaces, see Apex: New and Changed Items in the Salesforce Release
Notes.

Apex DML Operations


You can perform DML operations using the Apex DML statements or the methods of the Database class. For lead conversion, use
the convertLead method of the Database class. There is no DML counterpart for it.

SEE ALSO:
Apex Developer Guide: Working with Data in Apex
Database Class

Apex DML Statements


Use Data Manipulation Language (DML) statements to insert, update, merge, delete, and restore data in Salesforce.
The following Apex DML statements are available:

Insert Statement
The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to your organization’s data. insert
is analogous to the INSERT statement in SQL.

Syntax
insert sObject
insert sObject[]

5
Apex Reference Guide Apex DML Statements

Example
The following example inserts an account named 'Acme':
Account newAcct = new Account(name = 'Acme');
try {
insert newAcct;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.

Update Statement
The update DML operation modifies one or more existing sObject records, such as individual accounts or contacts, in your organization’s
data. update is analogous to the UPDATE statement in SQL.

Syntax
update sObject
update sObject[]

Example
The following example updates the BillingCity field on a single account named 'Acme':
Account a = new Account(Name='Acme2');
insert(a);

Account myAcct = [SELECT Id, Name, BillingCity FROM Account WHERE Id = :a.Id];
myAcct.BillingCity = 'San Francisco';

try {
update myAcct;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.

Upsert Statement
The upsert DML operation creates new records and updates sObject records within a single statement, using a specified field to
determine the presence of existing objects, or the ID field if no field is specified.

Syntax
upsert sObject [opt_field]
upsert sObject[] [opt_field]

6
Apex Reference Guide Apex DML Statements

The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when
calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce. Alternatively,
you can specify a field to use for matching. For custom objects, specify a custom field marked as external ID. For standard objects, you
can specify any field that has the idLookup attribute set to true. For example, the Email field of Contact or User has the idLookup
attribute set. To check a field’s attribute, see the Object Reference for Salesforce.
Also, you can use foreign keys to upsert sObject records if they have been set as reference fields. For more information, see Field Types
in the Object Reference for Salesforce.
The optional field parameter, opt_field, is a field token (of type Schema.SObjectField). For example, to specify the
MyExternalID custom field, the statement is:
upsert sObjectList Account.Fields.MyExternalId__c;

If the field used for matching doesn’t have the Unique attribute set, the context user must have the “View All Records” object-level
permission for the target object or the “View All Data” permission so that upsert doesn’t accidentally insert a duplicate record.

Note: Custom field matching is case-insensitive only if the custom field has the Unique and Treat "ABC" and "abc" as duplicate
values (case insensitive) attributes selected as part of the field definition. If so, “ABC123” is matched with “abc123.” For more
information, see “Create Custom Fields” in the Salesforce online help.

How Upsert Chooses to Insert or Update


Upsert uses the sObject record's primary key (the ID), an idLookup field, or an external ID field to determine whether it should create a
record or update an existing one:
• If the key isn’t matched, a new object record is created.
• If the key is matched once, the existing object record is updated.
• If the key is matched multiple times, an error is generated and the object record isn’t inserted or updated.

Example
This example performs an upsert of a list of accounts.
List<Account> acctList = new List<Account>();
// Fill the accounts list with some accounts

try {
upsert acctList;
} catch (DmlException e) {

This next example performs an upsert of a list of accounts using a foreign key for matching existing records, if any.
List<Account> acctList = new List<Account>();
// Fill the accounts list with some accounts

try {
// Upsert using an external ID field
upsert acctList myExtIDField__c;
} catch (DmlException e) {

7
Apex Reference Guide Apex DML Statements

Delete Statement
The delete DML operation deletes one or more existing sObject records, such as individual accounts or contacts, from your organization’s
data. delete is analogous to the delete() statement in the SOAP API.

Syntax
delete sObject
delete sObject[]

Example
The following example deletes all accounts that are named 'DotCom':
Account[] doomedAccts = [SELECT Id, Name FROM Account
WHERE Name = 'DotCom'];
try {
delete doomedAccts;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.

Undelete Statement
The undelete DML operation restores one or more existing sObject records, such as individual accounts or contacts, from your
organization’s Recycle Bin. undelete is analogous to the UNDELETE statement in SQL.

Syntax
undelete sObject | ID
undelete sObject[] | ID[]

Example
The following example undeletes an account named 'Universal Containers’. The ALL ROWS keyword queries all rows for both top
level and aggregate relationships, including deleted records and archived activities.
Account[] savedAccts = [SELECT Id, Name FROM Account WHERE Name = 'Universal Containers'
ALL ROWS];
try {
undelete savedAccts;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.

8
Apex Reference Guide ApexPages Namespace

Merge Statement
The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting
any related records.

Note: This DML operation does not have a matching Database system method.

Syntax
merge sObject sObject
merge sObject sObject[]
merge sObject ID
merge sObject ID[]
The first parameter represents the master record into which the other records are to be merged. The second parameter represents the
one or two other records that should be merged and then deleted. You can pass these other records into the merge statement as a
single sObject record or ID, or as a list of two sObject records or IDs.

Example
The following example merges two accounts named 'Acme Inc.' and 'Acme' into a single record:
List<Account> ls = new List<Account>{new Account(name='Acme Inc.'),new Account(name='Acme')};
insert ls;
Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1];
Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
try {
merge masterAcct mergeAcct;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.

ApexPages Namespace
The ApexPages namespace provides classes used in Visualforce controllers.
The following are the classes in the ApexPages namespace.

IN THIS SECTION:
Action Class
You can use ApexPages.Action to create an action method that you can use in a Visualforce custom controller or controller
extension.
Component Class
Represents a dynamic Visualforce component in Apex.

9
Apex Reference Guide Action Class

IdeaStandardController Class
IdeaStandardController objects offer Ideas-specific functionality in addition to what is provided by the
StandardController.
IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specific functionality in addition to what is provided by the
StandardSetController.
KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specific functionality in addition to what is
provided by the StandardController.
Message Class
Contains validation errors that occur when the user saves the page that uses a standard controller.
StandardController Class
Use a StandardController when defining an extension for a standard controller.
StandardSetController Class
StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce
list controllers provided by Salesforce.

Action Class
You can use ApexPages.Action to create an action method that you can use in a Visualforce custom controller or controller
extension.

Namespace
ApexPages

Usage
For example, you could create a saveOver method on a controller extension that performs a custom save.

Instantiation
The following code snippet illustrates how to instantiate a new ApexPages.Action object that uses the save action:
ApexPages.Action saveAction = new ApexPages.Action('{!save}');

IN THIS SECTION:
Action Constructors
Action Methods

Action Constructors
The following are constructors for Action.

10
Apex Reference Guide Action Class

IN THIS SECTION:
Action(action)
Creates a new instance of the ApexPages.Action class using the specified action.

Action(action)
Creates a new instance of the ApexPages.Action class using the specified action.

Signature
public Action(String action)

Parameters
action
Type: String
The action.

Action Methods
The following are methods for Action. All are instance methods.

IN THIS SECTION:
getExpression()
Returns the expression that is evaluated when the action is invoked.
invoke()
Invokes the action.

getExpression()
Returns the expression that is evaluated when the action is invoked.

Signature
public String getExpression()

Return Value
Type: String

invoke()
Invokes the action.

Signature
public System.PageReference invoke()

11
Apex Reference Guide Component Class

Return Value
Type: System.PageReference

Component Class
Represents a dynamic Visualforce component in Apex.

Namespace
ApexPages

Dynamic Component Properties


The following are properties for Component.

IN THIS SECTION:
childComponents
Returns a reference to the child components for the component.
expressions
Sets the content of an attribute using the expression language notation. The notation for this is
expressions.name_of_attribute.
facets
Sets the content of a facet to a dynamic component. The notation is facet.name_of_facet.

childComponents
Returns a reference to the child components for the component.

Signature
public List <ApexPages.Component> childComponents {get; set;}

Property Value
Type: List<ApexPages.Component>

Example
Component.Apex.PageBlock pageBlk = new Component.Apex.PageBlock();

Component.Apex.PageBlockSection pageBlkSection = new


Component.Apex.PageBlockSection(title='dummy header');

pageBlk.childComponents.add(pageBlkSection);

12
Apex Reference Guide IdeaStandardController Class

expressions
Sets the content of an attribute using the expression language notation. The notation for this is expressions.name_of_attribute.

Signature
public String expressions {get; set;}

Property Value
Type: String

Example
Component.Apex.InputField inpFld = new
Component.Apex.InputField();
inpField.expressions.value = '{!Account.Name}';
inpField.expressions.id = '{!$User.FirstName}';

facets
Sets the content of a facet to a dynamic component. The notation is facet.name_of_facet.

Signature
public String facets {get; set;}

Property Value
Type: String

Usage
Note: This property is only accessible by components that support facets.

Example
Component.Apex.DataTable myDT = new
Component.Apex.DataTable();
Component.Apex.OutputText footer = new
Component.Apex.OutputText(value='Footer Copyright');
myDT.facets.footer = footer;

IdeaStandardController Class
IdeaStandardController objects offer Ideas-specific functionality in addition to what is provided by the
StandardController.

13
Apex Reference Guide IdeaStandardController Class

Namespace
ApexPages

Usage
A method in the IdeaStandardController object is called by and operated on a particular instance of an IdeaStandardController.

Note: The IdeaStandardSetController and IdeaStandardController classes are currently available through
a limited release program. For information on enabling these classes for your organization, contact your Salesforce representative.
In addition to the methods listed in this class, the IdeaStandardController class inherits all the methods associated with the
StandardController class.

Instantiation
An IdeaStandardController object cannot be instantiated. An instance can be obtained through a constructor of a custom extension
controller when using the standard ideas controller.

Example
The following example shows how an IdeaStandardController object can be used in the constructor for a custom list controller. This
example provides the framework for manipulating the comment list data before displaying it on a Visualforce page.
public class MyIdeaExtension {

private final ApexPages.IdeaStandardController ideaController;

public MyIdeaExtension(ApexPages.IdeaStandardController controller) {


ideaController = (ApexPages.IdeaStandardController)controller;
}

public List<IdeaComment> getModifiedComments() {


IdeaComment[] comments = ideaController.getCommentList();
// modify comments here
return comments;
}

The following Visualforce markup shows how the IdeaStandardController example shown above can be used in a page. This page must
be named detailPage for this example to work.

Note: For the Visualforce page to display the idea and its comments, in the following example you need to specify the ID of a
specific idea (for example, /apex/detailPage?id=<ideaID>) whose comments you want to view.
<!-- page named detailPage -->
<apex:page standardController="Idea" extensions="MyIdeaExtension">
<apex:pageBlock title="Idea Section">
<ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}">{!idea.title}
</ideas:detailOutputLink>
<br/><br/>
<apex:outputText >{!idea.body}</apex:outputText>
</apex:pageBlock>

14
Apex Reference Guide IdeaStandardSetController Class

<apex:pageBlock title="Comments Section">


<apex:dataList var="a" value="{!modifiedComments}" id="list">
{!a.commentBody}
</apex:dataList>
<ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}"
pageOffset="-1">Prev</ideas:detailOutputLink>
|
<ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}"
pageOffset="1">Next</ideas:detailOutputLink>
</apex:pageBlock>
</apex:page>

SEE ALSO:
StandardController Class

IdeaStandardController Methods
The following are instance methods for IdeaStandardController.

IN THIS SECTION:
getCommentList()
Returns the list of read-only comments from the current page.

getCommentList()
Returns the list of read-only comments from the current page.

Signature
public IdeaComment[] getCommentList()

Return Value
Type: IdeaComment[]
This method returns the following comment properties:
• id
• commentBody
• createdDate
• createdBy.Id
• createdBy.communityNickname

IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specific functionality in addition to what is provided by the
StandardSetController.

15
Apex Reference Guide IdeaStandardSetController Class

Namespace
ApexPages

Usage
Note: The IdeaStandardSetController and IdeaStandardController classes are currently available through
a limited release program. For information on enabling these classes for your organization, contact your Salesforce representative.
In addition to the method listed above, the IdeaStandardSetController class inherits the methods associated with the
StandardSetController.

Note: The methods inherited from the StandardSetController cannot be used to affect the list of ideas returned by
the getIdeaList method.

Instantiation
An IdeaStandardSetController object cannot be instantiated. An instance can be obtained through a constructor of a custom extension
controller when using the standard list controller for ideas.

Example: Displaying a Profile Page


The following example shows how an IdeaStandardSetController object can be used in the constructor for a custom list controller:
public class MyIdeaProfileExtension {
private final ApexPages.IdeaStandardSetController ideaSetController;

public MyIdeaProfileExtension(ApexPages.IdeaStandardSetController controller) {


ideaSetController = (ApexPages.IdeaStandardSetController)controller;
}

public List<Idea> getModifiedIdeas() {


Idea[] ideas = ideaSetController.getIdeaList();
// modify ideas here
return ideas;
}

The following Visualforce markup shows how the IdeaStandardSetController example shown above and the
<ideas:profileListOutputLink> component can display a profile page that lists the recent replies, submitted ideas, and
votes associated with a user. Because this example does not identify a specific user ID, the page automatically shows the profile page
for the current logged in user. This page must be named profilePage in order for this example to work:
<!-- page named profilePage -->
<apex:page standardController="Idea" extensions="MyIdeaProfileExtension"
recordSetVar="ideaSetVar">
<apex:pageBlock >
<ideas:profileListOutputLink sort="recentReplies" page="profilePage">
Recent Replies</ideas:profileListOutputLink>
|
<ideas:profileListOutputLink sort="ideas" page="profilePage">Ideas Submitted
</ideas:profileListOutputLink>

16
Apex Reference Guide IdeaStandardSetController Class

|
<ideas:profileListOutputLink sort="votes" page="profilePage">Ideas Voted
</ideas:profileListOutputLink>
</apex:pageBlock>
<apex:pageBlock >
<apex:dataList value="{!modifiedIdeas}" var="ideadata">
<ideas:detailoutputlink ideaId="{!ideadata.id}" page="viewPage">
{!ideadata.title}</ideas:detailoutputlink>
</apex:dataList>
</apex:pageBlock>
</apex:page>

In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that displays
the detail page for a specific idea. This page must be named viewPage in order for this example to work:
<!-- page named viewPage -->
<apex:page standardController="Idea">
<apex:pageBlock title="Idea Section">
<ideas:detailOutputLink page="viewPage" ideaId="{!idea.id}">{!idea.title}
</ideas:detailOutputLink>
<br/><br/>
<apex:outputText>{!idea.body}</apex:outputText>
</apex:pageBlock>
</apex:page>

Example: Displaying a List of Top, Recent, and Most Popular Ideas and Comments
The following example shows how an IdeaStandardSetController object can be used in the constructor for a custom list controller:

Note: You must have created at least one idea for this example to return any ideas.

public class MyIdeaListExtension {


private final ApexPages.IdeaStandardSetController ideaSetController;

public MyIdeaListExtension (ApexPages.IdeaStandardSetController controller) {


ideaSetController = (ApexPages.IdeaStandardSetController)controller;
}

public List<Idea> getModifiedIdeas() {


Idea[] ideas = ideaSetController.getIdeaList();
// modify ideas here
return ideas;
}
}

The following Visualforce markup shows how the IdeaStandardSetController example shown above can be used with the
<ideas:listOutputLink> component to display a list of recent, top, and most popular ideas and comments. This page must
be named listPage in order for this example to work:
<!-- page named listPage -->
<apex:page standardController="Idea" extensions="MyIdeaListExtension"
recordSetVar="ideaSetVar">
<apex:pageBlock >

17
Apex Reference Guide IdeaStandardSetController Class

<ideas:listOutputLink sort="recent" page="listPage">Recent Ideas


</ideas:listOutputLink>
|
<ideas:listOutputLink sort="top" page="listPage">Top Ideas
</ideas:listOutputLink>
|
<ideas:listOutputLink sort="popular" page="listPage">Popular Ideas
</ideas:listOutputLink>
|
<ideas:listOutputLink sort="comments" page="listPage">Recent Comments
</ideas:listOutputLink>
</apex:pageBlock>
<apex:pageBlock >
<apex:dataList value="{!modifiedIdeas}" var="ideadata">
<ideas:detailoutputlink ideaId="{!ideadata.id}" page="viewPage">
{!ideadata.title}</ideas:detailoutputlink>
</apex:dataList>
</apex:pageBlock>
</apex:page>

In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that displays
the detail page for a specific idea. This page must be named viewPage.
<!-- page named viewPage -->
<apex:page standardController="Idea">
<apex:pageBlock title="Idea Section">
<ideas:detailOutputLink page="viewPage" ideaId="{!idea.id}">{!idea.title}
</ideas:detailOutputLink>
<br/><br/>
<apex:outputText>{!idea.body}</apex:outputText>
</apex:pageBlock>
</apex:page>

SEE ALSO:
StandardSetController Class

IdeaStandardSetController Methods
The following are instance methods for IdeaStandardSetController.

IN THIS SECTION:
getIdeaList()
Returns the list of read-only ideas in the current page set.

getIdeaList()
Returns the list of read-only ideas in the current page set.

Signature
public Idea[] getIdeaList()

18
Apex Reference Guide KnowledgeArticleVersionStandardController Class

Return Value
Type: Idea[]

Usage
You can use the <ideas:listOutputLink>, <ideas:profileListOutputLink>, and
<ideas:detailOutputLink> components to display profile pages as well as idea list and detail pages (see the examples below).
The following is a list of properties returned by this method:
• Body
• Categories
• Category
• CreatedBy.CommunityNickname
• CreatedBy.Id
• CreatedDate
• Id
• LastCommentDate
• LastComment.Id
• LastComment.CommentBody
• LastComment.CreatedBy.CommunityNickname
• LastComment.CreatedBy.Id
• NumComments
• Status
• Title
• VoteTotal

KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specific functionality in addition to what is provided
by the StandardController.

Namespace
ApexPages

Usage
In addition to the method listed above, the KnowledgeArticleVersionStandardController class inherits all the methods
associated with StandardController.

Note: Though inherited, the edit, delete, and save methods don't serve a function when used with the
KnowledgeArticleVersionStandardController class.

19
Apex Reference Guide KnowledgeArticleVersionStandardController Class

Example
The following example shows how a KnowledgeArticleVersionStandardController object can be used to create a
custom extension controller. In this example, you create a class named AgentContributionArticleController that allows
customer-support agents to see pre-populated fields on the draft articles they create while closing cases.
Prerequisites:
1. Create an article type called FAQ. For instructions, see “Create Article Types” in the Salesforce online help.
2. Create a text custom field called Details. For instructions, see “Add Custom Fields to Article Types” in the Salesforce online help.
3. Create a category group called Geography and assign it to a category called USA. For instructions, see “Create and Modify
Category Groups” and “Add Data Categories to Category Groups” in the Salesforce online help.
4. Create a category group called Topics and assign it a category called Maintenance.
/** Custom extension controller for the simplified article edit page that
appears when an article is created on the close-case page.
*/
public class AgentContributionArticleController {
// The constructor must take a ApexPages.KnowledgeArticleVersionStandardController as
an argument
public AgentContributionArticleController(
ApexPages.KnowledgeArticleVersionStandardController ctl) {
// This is the SObject for the new article.
//It can optionally be cast to the proper article type.
// For example, FAQ__kav article = (FAQ__kav) ctl.getRecord();
SObject article = ctl.getRecord();
// This returns the ID of the case that was closed.
String sourceId = ctl.getSourceId();
Case c = [SELECT Subject, Description FROM Case WHERE Id=:sourceId];

// This overrides the default behavior of pre-filling the


// title of the article with the subject of the closed case.
article.put('title', 'From Case: '+c.subject);
article.put('details__c',c.description);

// Only one category per category group can be specified.


ctl.selectDataCategory('Geography','USA');
ctl.selectDataCategory('Topics','Maintenance');
}
}

/** Test class for the custom extension controller.


*/
@isTest
private class AgentContributionArticleControllerTest {
static testMethod void testAgentContributionArticleController() {
String caseSubject = 'my test';
String caseDesc = 'my test description';

Case c = new Case();


c.subject= caseSubject;
c.description = caseDesc;
insert c;
String caseId = c.id;

20
Apex Reference Guide KnowledgeArticleVersionStandardController Class

System.debug('Created Case: ' + caseId);

ApexPages.currentPage().getParameters().put('sourceId', caseId);
ApexPages.currentPage().getParameters().put('sfdc.override', '1');

ApexPages.KnowledgeArticleVersionStandardController ctl =
new ApexPages.KnowledgeArticleVersionStandardController(new FAQ__kav());

new AgentContributionArticleController(ctl);

System.assertEquals(caseId, ctl.getSourceId());
System.assertEquals('From Case: '+caseSubject, ctl.getRecord().get('title'));
System.assertEquals(caseDesc, ctl.getRecord().get('details__c'));
}
}

If you created the custom extension controller for the purpose described in the previous example (that is, to modify submitted-via-case
articles), complete the following steps after creating the class:
1. Log into your Salesforce organization and from Setup, enter Knowledge Settings in the Quick Find box, then select
Knowledge Settings.
2. Click Edit.
3. Assign the class to the Use Apex customization field. This associates the article type specified in the new class with the
article type assigned to closed cases.
4. Click Save.

IN THIS SECTION:
KnowledgeArticleVersionStandardController Constructors
KnowledgeArticleVersionStandardController Methods

SEE ALSO:
StandardController Class

KnowledgeArticleVersionStandardController Constructors
The following are constructors for KnowledgeArticleVersionStandardController.

IN THIS SECTION:
KnowledgeArticleVersionStandardController(article)
Creates a new instance of the ApexPages.KnowledgeArticleVersionStandardController class using the
specified knowledge article.

KnowledgeArticleVersionStandardController(article)
Creates a new instance of the ApexPages.KnowledgeArticleVersionStandardController class using the specified
knowledge article.

21
Apex Reference Guide KnowledgeArticleVersionStandardController Class

Signature
public KnowledgeArticleVersionStandardController(SObject article)

Parameters
article
Type: SObject
The knowledge article, such as FAQ_kav.

KnowledgeArticleVersionStandardController Methods
The following are instance methods for KnowledgeArticleVersionStandardController.

IN THIS SECTION:
getSourceId()
Returns the ID for the source object record when creating a new article from another object.
setDataCategory(categoryGroup, category)
Specifies a default data category for the specified data category group when creating a new article.

getSourceId()
Returns the ID for the source object record when creating a new article from another object.

Signature
public String getSourceId()

Return Value
Type: String

setDataCategory(categoryGroup, category)
Specifies a default data category for the specified data category group when creating a new article.

Signature
public Void setDataCategory(String categoryGroup, String category)

Parameters
categoryGroup
Type: String
category
Type: String

22
Apex Reference Guide Message Class

Return Value
Type: Void

Message Class
Contains validation errors that occur when the user saves the page that uses a standard controller.

Namespace
ApexPages

Usage
When using a standard controller, all validation errors, both custom and standard, that occur when the user saves the page are automatically
added to the page error collections. If an inputField component is bound to the field with an error, the message is added to the
component’s error collection. All messages are added to the page’s error collection. For more information, see Validation Rules and
Standard Controllers in the Visualforce Developer's Guide.
If your application uses a custom controller or extension, you must use the message class for collecting errors.

Instantiation
In a custom controller or controller extension, you can instantiate a Message in one of these ways:
• ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity, summary);

where ApexPages.severity is the enum that determines how severe a message is, and summary is the String used to
summarize the message. For example:
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, 'my error
msg');

• ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity, summary, detail);

where ApexPages. severity is the enum that determines how severe a message is, summary is the String used to
summarize the message, and detail is the String used to provide more detailed information about the error.

ApexPages.Severity Enum
To specify the severity of the message, use the ApexPages.Severity enum values. The following are the valid values:
• CONFIRM
• ERROR
• FATAL
• INFO
• WARNING
All enums have access to standard methods, such as name and value.

23
Apex Reference Guide Message Class

IN THIS SECTION:
Message Constructors
Message Methods

Message Constructors
The following are constructors for Message.

IN THIS SECTION:
Message(severity, summary)
Creates a new instance of the ApexPages.Message class using the specified message severity and summary.
Message(severity, summary, detail)
Creates a new instance of the ApexPages.Message class using the specified message severity, summary, and message detail.
Message(severity, summary, detail, id)
Creates a new instance of the ApexPages.Message class using the specified severity, summary, detail, and component ID.

Message(severity, summary)
Creates a new instance of the ApexPages.Message class using the specified message severity and summary.

Signature
public Message(ApexPages.Severity severity, String summary)

Parameters
severity
Type: ApexPages.Severity
The severity of a Visualforce message.
summary
Type: String
The summary Visualforce message.

Message(severity, summary, detail)


Creates a new instance of the ApexPages.Message class using the specified message severity, summary, and message detail.

Signature
public Message(ApexPages.Severity severity, String summary, String detail)

Parameters
severity
Type: ApexPages.Severity
The severity of a Visualforce message.

24
Apex Reference Guide Message Class

summary
Type: String
The summary Visualforce message.
detail
Type: String
The detailed Visualforce message.

Message(severity, summary, detail, id)


Creates a new instance of the ApexPages.Message class using the specified severity, summary, detail, and component ID.

Signature
public Message(ApexPages.Severity severity, String summary, String detail, String id)

Parameters
severity
Type: ApexPages.Severity
The severity of a Visualforce message.
summary
Type: String
The summary Visualforce message.
detail
Type: String
The detailed Visualforce message.
id
Type: String
The ID of the Visualforce component to associate with the message, for example, a form field with an error.

Message Methods
The following are methods for Message. All are instance methods.

IN THIS SECTION:
getComponentLabel()
Returns the label of the associated inputField component. If no label is defined, this method returns null.
getDetail()
Returns the value of the detail parameter used to create the message. If no detail String was specified, this method returns null.
getSeverity()
Returns the severity enum used to create the message.
getSummary()
Returns the summary String used to create the message.

25
Apex Reference Guide StandardController Class

getComponentLabel()
Returns the label of the associated inputField component. If no label is defined, this method returns null.

Signature
public String getComponentLabel()

Return Value
Type: String

getDetail()
Returns the value of the detail parameter used to create the message. If no detail String was specified, this method returns null.

Signature
public String getDetail()

Return Value
Type: String

getSeverity()
Returns the severity enum used to create the message.

Signature
public ApexPages.Severity getSeverity()

Return Value
Type: ApexPages.Severity

getSummary()
Returns the summary String used to create the message.

Signature
public String getSummary()

Return Value
Type: String

StandardController Class
Use a StandardController when defining an extension for a standard controller.

26
Apex Reference Guide StandardController Class

Namespace
ApexPages

Usage
StandardController objects reference the pre-built Visualforce controllers provided by Salesforce. The only time it is necessary to refer
to a StandardController object is when defining an extension for a standard controller. StandardController is the data type of the single
argument in the extension class constructor.

Instantiation
You can instantiate a StandardController in the following way:
ApexPages.StandardController sc = new ApexPages.StandardController(sObject);

Example
The following example shows how a StandardController object can be used in the constructor for a standard controller extension:
public class myControllerExtension {

private final Account acct;

// The extension constructor initializes the private member


// variable acct by using the getRecord method from the standard
// controller.
public myControllerExtension(ApexPages.StandardController stdController) {
this.acct = (Account)stdController.getRecord();
}

public String getGreeting() {


return 'Hello ' + acct.name + ' (' + acct.id + ')';
}
}

The following Visualforce markup shows how the controller extension from above can be used in a page:
<apex:page standardController="Account" extensions="myControllerExtension">
{!greeting} <p/>
<apex:form>
<apex:inputField value="{!account.name}"/> <p/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>

IN THIS SECTION:
StandardController Constructors
StandardController Methods

27
Apex Reference Guide StandardController Class

StandardController Constructors
The following are constructors for StandardController.

IN THIS SECTION:
StandardController(controllerSObject)
Creates a new instance of the ApexPages.StandardController class for the specified standard or custom object.

StandardController(controllerSObject)
Creates a new instance of the ApexPages.StandardController class for the specified standard or custom object.

Signature
public StandardController(SObject controllerSObject)

Parameters
controllerSObject
Type: SObject
A standard or custom object.

StandardController Methods
The following are methods for StandardController. All are instance methods.

IN THIS SECTION:
addFields(fieldNames)
When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup.
This method adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as
well.
cancel()
Returns the PageReference of the cancel page.
delete()
Deletes record and returns the PageReference of the delete page.
edit()
Returns the PageReference of the standard edit page.
getId()
Returns the ID of the record that is currently in context, based on the value of the id query string parameter in the Visualforce page
URL.
getRecord()
Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL.
reset()
Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are
discarded.

28
Apex Reference Guide StandardController Class

save()
Saves changes and returns the updated PageReference.
view()
Returns the PageReference object of the standard detail page.

addFields(fieldNames)
When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. This
method adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well.

Signature
public Void addFields(List<String> fieldNames)

Parameters
fieldNames
Type: List<String>

Return Value
Type: Void

Usage
This method should be called before a record has been loaded—typically, it's called by the controller's constructor. If this method is
called outside of the constructor, you must use the reset() method before calling addFields().
The strings in fieldNames can either be the API name of a field, such as AccountId, or they can be explicit relationships to fields,
such as something__r.myField__c.
This method is only for controllers used by dynamicVisualforce bindings.

cancel()
Returns the PageReference of the cancel page.

Signature
public System.PageReference cancel()

Return Value
Type: System.PageReference

delete()
Deletes record and returns the PageReference of the delete page.

29
Apex Reference Guide StandardController Class

Signature
public System.PageReference delete()

Return Value
Type: System.PageReference

edit()
Returns the PageReference of the standard edit page.

Signature
public System.PageReference edit()

Return Value
Type: System.PageReference

getId()
Returns the ID of the record that is currently in context, based on the value of the id query string parameter in the Visualforce page
URL.

Signature
public String getId()

Return Value
Type: String

getRecord()
Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL.

Signature
public SObject getRecord()

Return Value
Type: sObject

Usage
Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other
fields, including fields from any related objects, must be queried using a SOQL expression.

Tip: You can work around this restriction by including a hidden component that references any additional fields that you want
to query. Hide the component from display by setting the component's rendered attribute to false.

30
Apex Reference Guide StandardController Class

Example
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>

reset()
Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are
discarded.

Signature
public Void reset()

Return Value
Type: Void

Usage
This method is only used if addFields is called outside the constructor, and it must be called directly before addFields.
This method is only for controllers used by dynamicVisualforce bindings.

save()
Saves changes and returns the updated PageReference.

Signature
public System.PageReference save()

Return Value
Type: System.PageReference

view()
Returns the PageReference object of the standard detail page.

Signature
public System.PageReference view()

Return Value
Type: System.PageReference

31
Apex Reference Guide StandardSetController Class

StandardSetController Class
StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list
controllers provided by Salesforce.

Namespace
ApexPages

Usage
The StandardSetController class also contains a prototype object. This is a single sObject contained within the Visualforce
StandardSetController class. If the prototype object's fields are set, those values are used during the save action, meaning that the values
are applied to every record in the set controller's collection. This is useful for writing pages that perform mass updates (applying identical
changes to fields within a collection of objects).

Note: Fields that are required in other Salesforce objects will keep the same requiredness when used by the prototype object.

Instantiation
You can instantiate a StandardSetController in either of the following ways:
• From a list of sObjects:
List<account> accountList = [SELECT Name FROM Account LIMIT 20];
ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);

• From a query locator:


ApexPages.StandardSetController ssc =
new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Name,CloseDate FROM
Opportunity]));

Note: The maximum record limit for StandardSetController is 10,000 records. Instantiating StandardSetController using a query
locator returning more than 10,000 records causes a LimitException to be thrown. However, instantiating StandardSetController
with a list of more than 10,000 records doesn’t throw an exception, and instead truncates the records to the limit.

Example
The following example shows how a StandardSetController object can be used in the constructor for a custom list controller:
public class opportunityList2Con {
// ApexPages.StandardSetController must be instantiated
// for standard list controllers
public ApexPages.StandardSetController setCon {
get {
if(setCon == null) {
setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
[SELECT Name, CloseDate FROM Opportunity]));
}
return setCon;
}

32
Apex Reference Guide StandardSetController Class

set;
}

// Initialize setCon and return a list of records


public List<Opportunity> getOpportunities() {
return (List<Opportunity>) setCon.getRecords();
}
}

The following Visualforce markup shows how the controller above can be used in a page:
<apex:page controller="opportunityList2Con">
<apex:pageBlock>
<apex:pageBlockTable value="{!opportunities}" var="o">
<apex:column value="{!o.Name}"/>
<apex:column value="{!o.CloseDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

IN THIS SECTION:
StandardSetController Constructors
StandardSetController Methods

StandardSetController Constructors
The following are constructors for StandardSetController.

IN THIS SECTION:
StandardSetController(queryLocator)
Creates an instance of the ApexPages.StandardSetController class for the list of objects returned by the query locator.
StandardSetController(controllerSObjects)
Creates an instance of the ApexPages.StandardSetController class for the specified list of standard or custom objects.

StandardSetController(queryLocator)
Creates an instance of the ApexPages.StandardSetController class for the list of objects returned by the query locator.

Signature
public StandardSetController(Database.QueryLocator queryLocator)

Parameters
queryLocator
Type: Database.QueryLocator
A query locator representing a list of sObjects.

33
Apex Reference Guide StandardSetController Class

StandardSetController(controllerSObjects)
Creates an instance of the ApexPages.StandardSetController class for the specified list of standard or custom objects.

Signature
public StandardSetController(List<sObject> controllerSObjects)

Parameters
controllerSObjects
Type: List on page 3762<sObject on page 3959>
A List of standard or custom objects.

Example
List<account> accountList = [SELECT Name FROM Account LIMIT 20];
ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);

StandardSetController Methods
The following are methods for StandardSetController. All are instance methods.

IN THIS SECTION:
cancel()
Returns the PageReference of the original page, if known, or the home page.
first()
Changes the set of records that the controller returns to the first page of records.
getCompleteResult()
Indicates whether there are more records in the set than the maximum record limit. If this is false, there are more records than you
can process using the list controller. The maximum record limit is 10,000 records.
getFilterId()
Returns the ID of the filter that is currently in context.
getHasNext()
Indicates whether there are more records after the current page set.
getHasPrevious()
Indicates whether there are more records before the current page set.
getListViewOptions()
Returns a list of the listviews available to the current user.
getPageNumber()
Returns the page number of the current page set. Note that the first page returns 1.
getPageSize()
Returns the number of records included in each page set.

34
Apex Reference Guide StandardSetController Class

getRecord()
Returns the sObject that represents the changes to the selected records. This retrieves the prototype object contained within the
class, and is used for performing mass updates.
getRecords()
Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it.
getResultSize()
Returns the number of records in the set.
getSelected()
Returns the list of sObjects that have been selected.
last()
Changes the set of records that the controller returns to the last page of records.
next()
Changes the set of records that the controller returns to the next page of records.
previous()
Changes the set of records that the controller returns to the previous page of records.
save()
Inserts new records or updates existing records that have been changed. After this operation is finished, it returns a PageReference
to the original page, if known, or the home page.
setFilterID(filterId)
Sets the filter ID of the controller.
setpageNumber(pageNumber)
Sets the page number.
setPageSize(pageSize)
Sets the number of records in each page set.
setSelected(selectedRecords)
Set the selected records to the records specified in the selectedRecords argument.

cancel()
Returns the PageReference of the original page, if known, or the home page.

Signature
public System.PageReference cancel()

Return Value
Type: System.PageReference

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions

35
Apex Reference Guide StandardSetController Class

first()
Changes the set of records that the controller returns to the first page of records.

Signature
public Void first()

Return Value
Type: Void

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions

getCompleteResult()
Indicates whether there are more records in the set than the maximum record limit. If this is false, there are more records than you can
process using the list controller. The maximum record limit is 10,000 records.

Signature
public Boolean getCompleteResult()

Return Value
Type: Boolean

getFilterId()
Returns the ID of the filter that is currently in context.

Note: The getFilterID() method doesn’t support list views without filter IDs, such as the Recently Viewed list view. In
these cases, the method returns the first filter ID of the object’s available list views. If called within an <apex:enhancedList>
component, the method returns the filter ID of the last used list view.

Signature
public String getFilterId()

Return Value
Type: String

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions
Visualforce Developer Guide: List Views with Standard List Controllers

36
Apex Reference Guide StandardSetController Class

getHasNext()
Indicates whether there are more records after the current page set.

Signature
public Boolean getHasNext()

Return Value
Type: Boolean

getHasPrevious()
Indicates whether there are more records before the current page set.

Signature
public Boolean getHasPrevious()

Return Value
Type: Boolean

getListViewOptions()
Returns a list of the listviews available to the current user.

Signature
public System.SelectOption getListViewOptions()

Return Value
Type: System.SelectOption[]

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions
Visualforce Developer Guide: List Views with Standard List Controllers

getPageNumber()
Returns the page number of the current page set. Note that the first page returns 1.

Signature
public Integer getPageNumber()

37
Apex Reference Guide StandardSetController Class

Return Value
Type: Integer

getPageSize()
Returns the number of records included in each page set.

Signature
public Integer getPageSize()

Return Value
Type: Integer

getRecord()
Returns the sObject that represents the changes to the selected records. This retrieves the prototype object contained within the class,
and is used for performing mass updates.

Signature
public sObject getRecord()

Return Value
Type: sObject

SEE ALSO:
Visualforce Developer Guide: Building a Custom List Controller

getRecords()
Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it.

Signature
public sObject[] getRecords()

Return Value
Type: sObject[]

SEE ALSO:
Visualforce Developer Guide: Building a Custom List Controller

getResultSize()
Returns the number of records in the set.

38
Apex Reference Guide StandardSetController Class

Signature
public Integer getResultSize()

Return Value
Type: Integer

getSelected()
Returns the list of sObjects that have been selected.

Signature
public sObject[] getSelected()

Return Value
Type: sObject[]

last()
Changes the set of records that the controller returns to the last page of records.

Signature
public Void last()

Return Value
Type: Void

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions

next()
Changes the set of records that the controller returns to the next page of records.

Signature
public Void next()

Return Value
Type: Void

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions

39
Apex Reference Guide StandardSetController Class

previous()
Changes the set of records that the controller returns to the previous page of records.

Signature
public Void previous()

Return Value
Type: Void

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions

save()
Inserts new records or updates existing records that have been changed. After this operation is finished, it returns a PageReference to
the original page, if known, or the home page.

Signature
public System.PageReference save()

Return Value
Type: System.PageReference

SEE ALSO:
Visualforce Developer Guide: Standard List Controller Actions

setFilterID(filterId)
Sets the filter ID of the controller.

Signature
public Void setFilterID(String filterId)

Parameters
filterId
Type: String

Return Value
Type: Void

40
Apex Reference Guide StandardSetController Class

setpageNumber(pageNumber)
Sets the page number.

Signature
public Void setpageNumber(Integer pageNumber)

Parameters
pageNumber
Type: Integer

Return Value
Type: Void

setPageSize(pageSize)
Sets the number of records in each page set.

Signature
public Void setPageSize(Integer pageSize)

Parameters
pageSize
Type: Integer

Return Value
Type: Void

setSelected(selectedRecords)
Set the selected records to the records specified in the selectedRecords argument.

Signature
public Void setSelected(sObject[] selectedRecords)

Parameters
selectedRecords
Type: sObject[]

Return Value
Type: Void

41
Apex Reference Guide AppLauncher Namespace

Usage
Use the setSelected() method in your Apex controller or controller extension to manually set the records displayed on a Visualforce
page. The setSelected() method overwrites any previously selected records with the records specified in the selectedRecords
argument.

Example
AccountNamePage shows a table of account names. MyControllerExtension’s constructor contains a SOQL query that
returns a list of accounts. This list is passed into setSelected() so that the account records in the list are selected and displayed
in the table.
<!-- AccountNamePage.page -->
<apex:page standardController="Account" recordSetVar="accounts"
extensions="MyControllerExtension">
<apex:pageBlock>
<apex:pageBlockTable value="{!accounts}" var="acc">
<apex:column value="{!acc.name}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

// MyControllerExtension.cls
public with sharing class MyControllerExtension {
private ApexPages.StandardSetController setController;

public MyControllerExtension(ApexPages.StandardSetController setController) {


this.setController = setController;

Account [] records = [SELECT Id, Name FROM Account LIMIT 30];


setController.setSelected(records);
}
}

SEE ALSO:
Visualforce Developer Guide: Accessing Data with List Controllers

AppLauncher Namespace
The AppLauncher namespace provides methods for managing the appearance of apps in the App Launcher, including their visibility
and sort order.
The following class is in the AppLauncher namespace.

IN THIS SECTION:
AppMenu Class
Contains methods to set the appearance of apps in the App Launcher.
ChangePasswordController Class
This class and its methods are for internal use only.

42
Apex Reference Guide AppMenu Class

CommunityLogoController Class
This class and its methods are for internal use only.
EmployeeLoginLinkController Class
This class and its methods are for internal use only.
ForgotPasswordController Class
This class and its methods are for internal use only.
IdentityHeaderController Class
This class and its methods are for internal use only.
LoginFormController Class
This class and its methods are for internal use only.
SelfRegisterController Class
This class and its methods are for internal use only.
SocialLoginController Class
This class and its methods are for internal use only.

AppMenu Class
Contains methods to set the appearance of apps in the App Launcher.

Namespace
AppLauncher

IN THIS SECTION:
AppMenu Methods

AppMenu Methods
The following are methods for AppMenu.

IN THIS SECTION:
setAppVisibility(appMenuItemId, isVisible)
Shows or hides specific apps in the App Launcher.
setOrgSortOrder(appIds)
Sets the organization-wide default sort order for the App Launcher based on a List of app menu item IDs in the desired order.
setUserSortOrder(appIds)
Sets an individual user’s default sort order for the App Launcher based on a List of app menu item IDs in the desired order.

setAppVisibility(appMenuItemId, isVisible)
Shows or hides specific apps in the App Launcher.

43
Apex Reference Guide AppMenu Class

Signature
public static void setAppVisibility(Id appMenuItemId, Boolean isVisible)

Parameters
appMenuItemId
Type: Id
The 15-character application ID value for an app. For more information, see the ApplicationId field for AppMenuItem or the
AppMenuItemId field for UserAppMenuItem in the Salesforce Object Reference
isVisible
Type: Boolean
If true, the app is visible.

Return Value
Type: void

setOrgSortOrder(appIds)
Sets the organization-wide default sort order for the App Launcher based on a List of app menu item IDs in the desired order.

Signature
public static void setOrgSortOrder(List<Id> appIds)

Parameters
appIds
Type: List<Id>
A list of application ID values. For more information, see the ApplicationId field for AppMenuItem in the Salesforce Object
Reference.

Return Value
Type: void

setUserSortOrder(appIds)
Sets an individual user’s default sort order for the App Launcher based on a List of app menu item IDs in the desired order.

Signature
public static void setUserSortOrder(List<Id> appIds)

Parameters
appIds
Type: List<Id>

44
Apex Reference Guide ChangePasswordController Class

A list of application ID values. For more information, see the AppMenuItemId field for UserAppMenuItem in the Salesforce Object
Reference.

Return Value
Type: void

ChangePasswordController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

CommunityLogoController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

EmployeeLoginLinkController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

ForgotPasswordController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

IdentityHeaderController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

45
Apex Reference Guide LoginFormController Class

LoginFormController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

SelfRegisterController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

SocialLoginController Class
This class and its methods are for internal use only.

Namespace
AppLauncher

Approval Namespace
The Approval namespace provides classes and methods for approval processes.
The following are the classes in the Approval namespace.

IN THIS SECTION:
LockResult Class
The result of a record lock returned by a System.Approval.lock() method.
ProcessRequest Class
The ProcessRequest class is the parent class for the ProcessSubmitRequest and ProcessWorkitemRequest
classes. Use the ProcessRequest class to write generic Apex that can process objects from either class.
ProcessResult Class
After you submit a record for approval, use the ProcessResult class to process the results of an approval process.
ProcessSubmitRequest Class
Use the ProcessSubmitRequest class to submit a record for approval.
ProcessWorkitemRequest Class
Use the ProcessWorkitemRequest class for processing an approval request after it is submitted.
UnlockResult Class
The result of a record unlock, returned by a System.Approval.unlock() method.

46
Apex Reference Guide LockResult Class

LockResult Class
The result of a record lock returned by a System.Approval.lock() method.

Namespace
Approval

Usage
The System.Approval.lock() methods return Approval.LockResult objects. Each element in a LockResult array corresponds
to an element in the ID or sObject array passed as a parameter to a lock method. The first element in the LockResult array corresponds
to the first element in the ID or sObject array, the second element corresponds to the second element, and so on. If only one ID or sObject
is passed in, the LockResult array contains a single element.

Example
The following example obtains and iterates through the returned Approval.LockResult objects. It locks some queried accounts using
Approval.lock with a false second parameter to allow partial processing of records on failure. Next, it iterates through the
results to determine whether the operation was successful for each record. It writes the ID of every record that was processed successfully
to the debug log, or writes error messages and failed fields of the failed records.
// Query the accounts to lock
Account[] accts = [SELECT Id from Account WHERE Name LIKE 'Acme%'];
// Lock the accounts
Approval.LockResult[] lrList = Approval.lock(accts, false);

// Iterate through each returned result


for(Approval.LockResult lr : lrList) {
if (lr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully locked account with ID: ' + lr.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : lr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}

IN THIS SECTION:
LockResult Methods

SEE ALSO:
Approval Class

47
Apex Reference Guide LockResult Class

LockResult Methods
The following are methods for LockResult.

IN THIS SECTION:
getErrors()
If an error occurred, returns an array of one or more database error objects, providing the error code and description.
getId()
Returns the ID of the sObject you are trying to lock.
isSuccess()
A Boolean value that is set to true if the lock operation is successful for this object, or false otherwise.

getErrors()
If an error occurred, returns an array of one or more database error objects, providing the error code and description.

Signature
public List<Database.Error> getErrors()

Return Value
Type: List<Database.Error>

getId()
Returns the ID of the sObject you are trying to lock.

Signature
public Id getId()

Return Value
Type: Id

Usage
If the field contains a value, the object was locked. If the field is empty, the operation was not successful.

isSuccess()
A Boolean value that is set to true if the lock operation is successful for this object, or false otherwise.

Signature
public Boolean isSuccess()

48
Apex Reference Guide ProcessRequest Class

Return Value
Type: Boolean

ProcessRequest Class
The ProcessRequest class is the parent class for the ProcessSubmitRequest and ProcessWorkitemRequest
classes. Use the ProcessRequest class to write generic Apex that can process objects from either class.

Namespace
Approval

Usage
The request must be instantiated via the child classes, ProcessSubmitRequest and ProcessWorkItemRequest.

ProcessRequest Methods
The following are methods for ProcessRequest. All are instance methods.

IN THIS SECTION:
getComments()
Returns the comments that have been added previously to the approval request.
getNextApproverIds()
Returns the list of user IDs of user specified as approvers.
setComments(comments)
Sets the comments to be added to the approval request.
setNextApproverIds(nextApproverIds)
If the next step in your approval process is another Apex approval process, you specify exactly one user ID as the next approver. If
not, you cannot specify a user ID and this method must be null. This method sets the ActorId field of the associated
ProcessInstanceWorkItem.

getComments()
Returns the comments that have been added previously to the approval request.

Signature
public String getComments()

Return Value
Type: String

49
Apex Reference Guide ProcessRequest Class

getNextApproverIds()
Returns the list of user IDs of user specified as approvers.

Signature
public ID[] getNextApproverIds()

Return Value
Type: ID[]

setComments(comments)
Sets the comments to be added to the approval request.

Signature
public Void setComments(String comments)

Parameters
comments
Type: String

Return Value
Type: Void

setNextApproverIds(nextApproverIds)
If the next step in your approval process is another Apex approval process, you specify exactly one user ID as the next approver. If not,
you cannot specify a user ID and this method must be null. This method sets the ActorId field of the associated ProcessInstanceWorkItem.

Signature
public Void setNextApproverIds(ID[] nextApproverIds)

Parameters
nextApproverIds
Type: ID[]
Must be a single-entry list.

Return Value
Type: Void

50
Apex Reference Guide ProcessResult Class

ProcessResult Class
After you submit a record for approval, use the ProcessResult class to process the results of an approval process.

Namespace
Approval

Usage
A ProcessResult object is returned by the process method. You must specify the Approval namespace when creating an instance of
this class. For example:
Approval.ProcessResult result = Approval.process(req1);

ProcessResult Methods
The following are methods for ProcessResult. All are instance methods.

IN THIS SECTION:
getEntityId()
The ID of the record being processed.
getErrors()
If an error occurred, returns an array of one or more database error objects including the error code and description.
getInstanceId()
The ID of the approval process that has been submitted for approval.
getInstanceStatus()
The status of the current approval process. Valid values are: Approved, Rejected, Removed or Pending.
getNewWorkitemIds()
The IDs of the new items submitted to the approval process. There can be 0 or 1 approval processes.
isSuccess()
A Boolean value that is set to true if the approval process completed successfully; otherwise, it is set to false.

getEntityId()
The ID of the record being processed.

Signature
public String getEntityId()

Return Value
Type: String

51
Apex Reference Guide ProcessResult Class

getErrors()
If an error occurred, returns an array of one or more database error objects including the error code and description.

Signature
public Database.Error[] getErrors()

Return Value
Type: Database.Error[]

getInstanceId()
The ID of the approval process that has been submitted for approval.

Signature
public String getInstanceId()

Return Value
Type: String

getInstanceStatus()
The status of the current approval process. Valid values are: Approved, Rejected, Removed or Pending.

Signature
public String getInstanceStatus()

Return Value
Type: String

getNewWorkitemIds()
The IDs of the new items submitted to the approval process. There can be 0 or 1 approval processes.

Signature
public ID[] getNewWorkitemIds()

Return Value
Type: ID[]

isSuccess()
A Boolean value that is set to true if the approval process completed successfully; otherwise, it is set to false.

52
Apex Reference Guide ProcessSubmitRequest Class

Signature
public Boolean isSuccess()

Return Value
Type: Boolean

ProcessSubmitRequest Class
Use the ProcessSubmitRequest class to submit a record for approval.

Namespace
Approval

Usage
You must specify the Approval namespace when creating an instance of this class. The constructor for this class takes no arguments.
For example:
Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();

Inherited Methods
In addition to the methods listed, the ProcessSubmitRequest class has access to all the methods in its parent class, ProcessRequest
Class.
• getComments()
• getNextApproverIds()
• setComments(comments)
• setNextApproverIds(nextApproverIds)

Example
To view sample code, refer to Approval Processing Example.

ProcessSubmitRequest Methods
The following are methods for ProcessSubmitRequest. All are instance methods.

IN THIS SECTION:
getObjectId()
Returns the ID of the record that has been submitted for approval. For example, it can return an account, contact, or custom object
record.
getProcessDefinitionNameOrId()
Returns the developer name or ID of the process definition.

53
Apex Reference Guide ProcessSubmitRequest Class

getSkipEntryCriteria()
If getProcessDefinitionNameOrId() returns a value other than null, getSkipEntryCriteria() determines
whether to evaluate the entry criteria for the process (true) or not (false).
getSubmitterId()
Returns the user ID of the submitter requesting the approval record. The user must be one of the allowed submitters in the process
definition setup.
setObjectId(recordId)
Sets the ID of the record to be submitted for approval. For example, it can specify an account, contact, or custom object record.
setProcessDefinitionNameOrId(nameOrId)
Sets the developer name or ID of the process definition to be evaluated.
setSkipEntryCriteria(skipEntryCriteria)
If the process definition name or ID is not null, setSkipEntryCriteria() determines whether to evaluate the entry criteria
for the process (true) or not (false).
setSubmitterId(userID)
Sets the user ID of the submitter requesting the approval record. The user must be one of the allowed submitters in the process
definition setup. If you don’t set a submitter ID, the process uses the current user as the submitter.

getObjectId()
Returns the ID of the record that has been submitted for approval. For example, it can return an account, contact, or custom object
record.

Signature
public String getObjectId()

Return Value
Type: String

getProcessDefinitionNameOrId()
Returns the developer name or ID of the process definition.

Signature
public String getProcessDefinitionNameOrId()

Return Value
Type: String

Usage
The default is null. If the return value is null, when a user submits a record for approval Salesforce evaluates the entry criteria for all
processes applicable to the user.

54
Apex Reference Guide ProcessSubmitRequest Class

getSkipEntryCriteria()
If getProcessDefinitionNameOrId() returns a value other than null, getSkipEntryCriteria() determines
whether to evaluate the entry criteria for the process (true) or not (false).

Signature
public Boolean getSkipEntryCriteria()

Return Value
Type: Boolean

getSubmitterId()
Returns the user ID of the submitter requesting the approval record. The user must be one of the allowed submitters in the process
definition setup.

Signature
public String getSubmitterId()

Return Value
Type: String

setObjectId(recordId)
Sets the ID of the record to be submitted for approval. For example, it can specify an account, contact, or custom object record.

Signature
public Void setObjectId(String recordId)

Parameters
recordId
Type: String

Return Value
Type: Void

setProcessDefinitionNameOrId(nameOrId)
Sets the developer name or ID of the process definition to be evaluated.

Signature
public Void setProcessDefinitionNameOrId(String nameOrId)

55
Apex Reference Guide ProcessSubmitRequest Class

Parameters
nameOrId
Type: String
The process definition developer name or process definition ID. The record is submitted to this specific process. If set to null,
submission of a record approval follows standard evaluation; that is, every entry criteria of the process definition in the process order
is evaluated and the one that satisfies is picked and submitted.

Return Value
Type: Void

Usage
If the process definition name or ID is not set via this method, then by default it is null. If it is null, the submission of a record for approval
evaluates entry criteria for all processes applicable to the submitter. The order of evaluation is based on the process order of the setup.

setSkipEntryCriteria(skipEntryCriteria)
If the process definition name or ID is not null, setSkipEntryCriteria() determines whether to evaluate the entry criteria for
the process (true) or not (false).

Signature
public Void setSkipEntryCriteria(Boolean skipEntryCriteria)

Parameters
skipEntryCriteria
Type: Boolean
If set to true, request submission skips the evaluation of entry criteria for the process set in setProcessDefinitionNameOrId(nameOrId).
If the process definition name or ID is not specified, this parameter is ignored and standard evaluation is followed based on process
order. If set to false, or if this method isn’t called, the entry criteria is not skipped.

Return Value
Type: Void

setSubmitterId(userID)
Sets the user ID of the submitter requesting the approval record. The user must be one of the allowed submitters in the process definition
setup. If you don’t set a submitter ID, the process uses the current user as the submitter.

Signature
public Void setSubmitterId(String userID)

56
Apex Reference Guide ProcessWorkitemRequest Class

Parameters
userID
Type: String
The user ID on behalf of which the record is submitted. If set to null, the current user is the submitter. If the submitter is not set
with this method, the default submitter is null (the current user).

Return Value
Type: Void

ProcessWorkitemRequest Class
Use the ProcessWorkitemRequest class for processing an approval request after it is submitted.

Namespace
Approval

Usage
You must specify the Approval namespace when creating an instance of this class. The constructor for this class takes no arguments.
For example:
Approval.ProcessWorkitemRequest pwr = new Approval.ProcessWorkitemRequest();

Inherited Methods
In addition to the methods listed, the ProcessWorkitemRequest class has access to all the methods in its parent class,
ProcessRequest Class:
• getComments()
• getNextApproverIds()
• setComments(comments)
• setNextApproverIds(nextApproverIds)

ProcessWorkitemRequest Methods
The following are methods for ProcessWorkitemRequest. All are instance methods.

IN THIS SECTION:
getAction()
Returns the type of action already associated with the approval request. Valid values are: Approve, Reject, or Removed.
getWorkitemId()
Returns the ID of the approval request that is in the process of being approved, rejected, or removed.
setAction(actionType)
Sets the type of action to take for processing an approval request.

57
Apex Reference Guide ProcessWorkitemRequest Class

setWorkitemId(id)
Sets the ID of the approval request that is being approved, rejected, or removed.

getAction()
Returns the type of action already associated with the approval request. Valid values are: Approve, Reject, or Removed.

Signature
public String getAction()

Return Value
Type: String

getWorkitemId()
Returns the ID of the approval request that is in the process of being approved, rejected, or removed.

Signature
public String getWorkitemId()

Return Value
Type: String

setAction(actionType)
Sets the type of action to take for processing an approval request.

Signature
public Void setAction(String actionType)

Parameters
actionType
Type: String
Valid values are: Approve, Reject, or Removed. Only system administrators can specify Removed.

Return Value
Type: Void

setWorkitemId(id)
Sets the ID of the approval request that is being approved, rejected, or removed.

58
Apex Reference Guide UnlockResult Class

Signature
public Void setWorkitemId(String id)

Parameters
id
Type: String

Return Value
Type: Void

UnlockResult Class
The result of a record unlock, returned by a System.Approval.unlock() method.

Namespace
Approval

Usage
The System.Approval.unlock() methods return Approval.UnlockResult objects. Each element in an UnlockResult array
corresponds to an element in the ID or sObject array passed as a parameter to an unlock method. The first element in the UnlockResult
array corresponds to the first element in the ID or sObject array, the second element corresponds to the second element, and so on. If
only one ID or sObject is passed in, the UnlockResult array contains a single element.

Example
The following example shows how to obtain and iterate through the returned Approval.UnlockResult objects. It locks some queried
accounts using Approval.unlock with a false second parameter to allow partial processing of records on failure. Next, it
iterates through the results to determine whether the operation was successful for each record. It writes the ID of every record that was
processed successfully to the debug log, or writes error messages and failed fields of the failed records.
// Query the accounts to unlock
Account[] accts = [SELECT Id from Account WHERE Name LIKE 'Acme%'];

for(Account acct:accts) {
// Create an approval request for the account
Approval.ProcessSubmitRequest req1 =
new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(acct.id);

// Submit the record to specific process and skip the criteria evaluation
req1.setProcessDefinitionNameOrId('PTO_Request_Process');
req1.setSkipEntryCriteria(true);

// Submit the approval request for the account


Approval.ProcessResult result = Approval.process(req1);

59
Apex Reference Guide UnlockResult Class

// Verify the result


System.assert(result.isSuccess());
}

// Unlock the accounts


Approval.UnlockResult[] urList = Approval.unlock(accts, false);

// Iterate through each returned result


for(Approval.UnlockResult ur : urList) {
if (ur.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully unlocked account with ID: ' + ur.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : ur.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}

IN THIS SECTION:
UnlockResult Methods

SEE ALSO:
Approval Class

UnlockResult Methods
The following are methods for UnlockResult.

IN THIS SECTION:
getErrors()
If an error occurred, returns an array of one or more database error objects, providing the error code and description.
getId()
Returns the ID of the sObject you are trying to unlock.
isSuccess()
A Boolean value that is set to true if the unlock operation is successful for this object, or false otherwise.

getErrors()
If an error occurred, returns an array of one or more database error objects, providing the error code and description.

60
Apex Reference Guide Auth Namespace

Signature
public List<Database.Error> getErrors()

Return Value
Type: List<Database.Error>

getId()
Returns the ID of the sObject you are trying to unlock.

Signature
public Id getId()

Return Value
Type: Id

Usage
If the field contains a value, the object was unlocked. If the field is empty, the operation was not successfult.

isSuccess()
A Boolean value that is set to true if the unlock operation is successful for this object, or false otherwise.

Signature
public Boolean isSuccess()

Return Value
Type: Boolean

Auth Namespace
The Auth namespace provides an interface and classes for single sign-on into Salesforce and session security management.
The following is the interface in the Auth namespace.

IN THIS SECTION:
AuthConfiguration Class
Contains methods for configuring settings for users to log in to a Salesforce org using their authentication provider credentials
instead of their Salesforce credentials. The authentication provider can be any authentication provider that supports the OpenID
Connect protocol, such as Google, Facebook, or Twitter. Users log in to either an Experience Cloud site
(https://MyDomainName.my.site.com) or your My Domain login URL
(https://MyDomainName.my.salesforce.com).

61
Apex Reference Guide Auth Namespace

AuthProviderCallbackState Class
Provides request HTTP headers, body, and query parameters to the AuthProviderPlugin.handleCallback method
for user authentication. This class allows you to group the information passed in rather than passing headers, body, and query
parameters individually.
AuthProviderPlugin Interface
This interface is deprecated. For new development, use the abstract class Auth.AuthProviderPluginClass to create a
custom OAuth-based authentication provider plug-in for single sign-on in to Salesforce.
AuthProviderPluginClass Class
Contains methods to create a custom OAuth-based authentication provider plug-in for single sign-on in to Salesforce. Use this class
to create a custom authentication provider plug-in if you can’t use one of the authentication providers that Salesforce provides.
AuthProviderTokenResponse Class
Stores the response from the AuthProviderPlugin.handleCallback method.
AuthToken Class
Contains methods for getting and revoking access and refresh tokens that are issued when a user logs in via a single sign-on (SSO)
flow that uses an authentication provider, such as Facebook.
CommunitiesUtil Class
Contains methods for getting information about an Experience Cloud user.
ConfigurableSelfRegHandler Interface
Gives you more control over how customers or partners self-register for your Experience Cloud site by creating a class that implements
Auth.ConfigurableSelfRegHandler. You choose the user information to collect, and how users identify themselves—with
their email address, phone number, or another identifier. When verified, you create a customer or partner user and log in the user
to your Experience Cloud site.
ConfirmUserRegistrationHandler Interface
Manages single sign-on (SSO) user mappings between Salesforce and a third-party identity provider. Use this interface to confirm
user mappings before updating them.
ConnectedAppPlugin Class
Contains methods for extending the behavior of a connected app, for example, customizing how a connected app is invoked
depending on the protocol used. This class gives you more control over the interaction between Salesforce and your connected
app.
CustomOneTimePasswordDeliveryHandler Interface
To use a custom SMS provider to send one-time passwords (OTPs) for Experience Cloud identity verification, create a class that
implements the Auth.CustomOneTimePasswordDeliveryHandler interface.
CustomOneTimePasswordDeliveryResult Enum
Indicates the status of an attempt to send a one-time password (OTP) to an external user via a custom messaging provider.
ExternalClientAppOauthHandler Class
Contains methods for extending the behavior of an external client app. For example, customize how an external client app is invoked
depending on the protocol used. This class gives you more control over the interaction between Salesforce and your external client
app.
GeneratedUserData Class
Stores the output of the Generate User Data invocable action, which you can access in Flow Builder.
HeadlessSelfRegistrationHandler Interface
Creates customer and partner users during the Headless Registration Flow.

62
Apex Reference Guide Auth Namespace

HeadlessUserDiscoveryHandler Interface
Use this interface to create a headless user discovery handler that you implement during headless login, passwordless login, and
forgot password flows.
HeadlessUserDiscoveryResponse Class
Contains methods to describe the result of headless user discovery using a handler that implements the
Auth.HeadlessUserDiscoveryHandler interface during headless login, passwordless login, and forgot password flows.
HttpCalloutMockUtil Class
Contains a method to send fake HTTP callouts for classes in the Auth namespace.
IntegratingAppType Enum
Specifies whether you’re integrating your app as a connected app or as an external client app in methods used in your customized
Apex token exchange handler, which extends the Auth.Oauth2TokenExchangeHandler class.
InvocationContext Enum
The context in which the connected app is invoked, such as the protocol flow used and the token type issued, if any. Developers
can use the context information to write code that is unique to the type of invocation.
JsonValueOutput Class
Stores the output of the Get User Data from JSON String invocable action, which you can access in Flow Builder..
JWS Class
Contains methods that apply a digital signature to a JSON Web Token (JWT), using a JSON Web Signature (JWS) data structure. This
class creates the signed JWT bearer token, which can be used to request an OAuth access token in the OAuth 2.0 JWT bearer token
flow.
JWT Class
Generates the JSON Claims Set in a JSON Web Token (JWT). The resulting Base64-encoded payload can be passed as an argument
to create an instance of the Auth.JWS class.
JWTBearerTokenExchange Class
Contains methods that POST the signed JWT bearer token to a token endpoint to request an access token, in the OAuth 2.0 JWT
bearer token flow.
JWTUtil Class
Contains methods for validating a JSON Web Token (JWT) from an external identity provider as part of the OAuth 2.0 token exchange
flow. Use these methods as part of the validateIncomingToken method in the
Auth.Oauth2TokenExchangeHandler class.
LightningLoginEligibility Enum
Contains a Lightning Login eligibility value used by the Auth.SessionManagement.getLightningLoginEligibility
method.
LoginDiscoveryHandler Interface
Salesforce gives you the ability to log in users based on other verification methods than username and password. For example, it
can prompt users to log in with their email, phone number, or another identifier like a Federation ID or device identifier. Login
Discovery is available to these licenses: Customer Community, Customer Community Plus, External Identity, Partner Community,
and Partner Community Plus.
LoginDiscoveryMethod Enum
Contains methods used to verify the user’s identity when the My Domain login process uses Login Discovery.

63
Apex Reference Guide Auth Namespace

MyDomainLoginDiscoveryHandler Interface
The handler used to implement the My Domain Login Discovery page, which is an interview-based (two-step) login process. First
the user is prompted for a unique identifier such as an email address or phone number. Then the handler determines (discovers)
how to authenticate the user. Either the user enters a password or is directed to an identity provider’s login page.
Oauth2TokenExchangeHandler Class
Use this class to create a token exchange handler that validates tokens from an external identity provider and maps the token’s
subject to a Salesforce user during the OAuth 2.0 token exchange flow. The handler can also be used to create users by setting up
a new User object and returning it to Salesforce for automatic insertion.
OAuth2TokenExchangeType Enum
Used during the OAuth 2.0 token exchange flow to specify the type of token that’s being exchanged for a Salesforce token.
OAuthRefreshResult Class
Stores the result of an AuthProviderPluginClass refresh method. OAuth authentication flow provides a refresh token that
can be used to get a new access token. Access tokens have a limited lifetime as specified by the session timeout value. When an
access token expires, use a refresh token to get a new access token.
OauthToken Class
Contains a method to revoke OAuth access tokens and refresh tokens. This method supports opaque tokens and JSON Web Token
(JWT)-based access tokens, including guest and named user JWT-based access tokens.
OauthTokenType Enum
Specifies the type of Salesforce-issued OAuth 2.0 token being revoked in the OauthToken.revokeToken method.
RegistrationHandler Interface
Salesforce provides the ability to use an authentication provider, such as Facebook© or Janrain©, for single sign-on into Salesforce.
SamlJitHandler Interface
Use this interface to control and customize Just-in-Time user provisioning logic during SAML single sign-on.
SessionManagement Class
Contains methods for verifying users’ identity, creating custom login flows, customizing security levels, and defining trusted IP ranges
for a current session.
SessionLevel Enum
An Auth.SessionLevel enum value is used by the SessionManagement.setSessionLevel method.
TokenValidationResult Class
Contains methods that describe the result of the token validation performed by a token exchange handler using the
validateIncomingToken method in the Auth.Oauth2TokenExchangeHandler class during the OAuth 2.0 token
exchange flow.
UserData Class
Stores user information for authentication provider registration handlers, including handlers that implement the
Auth.RegistrationHandler interface and handlers built using Flow Builder.
VerificationAction Enum
Indicates the method that you use to send a one-time password (OTP) to a user during the headless passwordless login flow.
VerificationMethod Enum
Contains the different ways users can identify themselves when logging in. You can use it to implement mobile-centric passwordless
login pages and to self-register (and deregister) verification methods.
VerificationPolicy Enum
The Auth.VerificationPolicy enum contains an identity verification policy value used by the
SessionManagement.generateVerificationUrl method.

64
Apex Reference Guide AuthConfiguration Class

VerificationResult Class
Contains the result of a verification challenge that you invoke when you create your own Verify page. The challenge can be initiated
by either the System.UserManagement.verifyPasswordlessLogin or
System.UserManagement.verifySelfRegistration method.
Auth Exceptions
The Auth namespace contains some exception classes.

AuthConfiguration Class
Contains methods for configuring settings for users to log in to a Salesforce org using their authentication provider credentials instead
of their Salesforce credentials. The authentication provider can be any authentication provider that supports the OpenID Connect protocol,
such as Google, Facebook, or Twitter. Users log in to either an Experience Cloud site (https://MyDomainName.my.site.com)
or your My Domain login URL (https://MyDomainName.my.salesforce.com).

Namespace
Auth

Example
This example shows how to call some methods on the Auth.AuthConfiguration class. Before you can run this sample, you
must provide valid values for the URLs and developer name.

String communityUrl = 'MyDomainName.my.site.com';


String startUrl = '<Add URL>';
Auth.AuthConfiguration authConfig = new Auth.AuthConfiguration(communityUrl,startUrl);
List<AuthProvider> authPrvs = authConfig.getAuthProviders();
String bColor = authConfig.getBackgroundColor();
String fText = authConfig.getFooterText();

String sso = Auth.AuthConfiguration.getAuthProviderSsoUrl(communityUrl, startUrl,


'developerName');

AuthConfiguration Constructors
The following are constructors for AuthConfiguration.

Note: The AuthConfiguration (networkId, startUrl) constructor is deprecated in API version 56.0 and later.

AuthConfiguration(communityOrCustomUrl, startUrl)
Creates an instance of the AuthConfiguration class using the specified URL for an Experience Cloud site or a My Domain subdomain
and the start URL for authenticated users.

Signature
public AuthConfiguration(String communityOrCustomUrl, String startUrl)

65
Apex Reference Guide AuthConfiguration Class

Parameters
communityOrCustomUrl
Type: String
The URL for the domain, which can be a Salesforce subdomain created with My Domain (my.salesforce.com) or a subdomain
of an Experience Cloud site (force.com).
startUrl
Type: String
The page users see after successfully logging in to the Experience Cloud site or My Domain subdomain.

AuthConfiguration Methods
The following are methods for AuthConfiguration. Use these methods to manage and customize authentication for a Salesforce
community.

IN THIS SECTION:
getAllowInternalUserLoginEnabled()
Indicates whether the Experience Cloud site allows internal users to log in using the Experience Cloud site login page. To enable,
admins configure the setting Allow internal users to log in directly to the experience on the Login & Registration page in
Experience Workspaces. It’s disabled by default.
getAuthConfig()
Returns the AuthConfig sObject, which represents the authentication options for an Experience Cloud site or Salesforce My Domain
subdomain.
getAuthConfigProviders()
Returns the list of authentication providers configured for an Experience Cloud site or Salesforce My Domain subdomain.
getAuthProviders()
Returns the list of authentication providers available for an Experience Cloud site or Salesforce My Domain subdomain.
getAuthProviderSsoDomainUrl(communityUrl, startUrl, developerName)
Returns the single sign-on URL for an Experience Cloud site subdomain.
getAuthProviderSsoUrl(communityUrl, startUrl, developerName)
Returns the single sign-on URL for an Experience Cloud site or Salesforce My Domain subdomain.
getBackgroundColor()
Returns the color for the background of the login page for a community.
getCertificateLoginEnabled(domainUrl)
Returns true if certificate-based authentication is enabled for the My Domain URL.
getCertificateLoginUrl(domainUrl, startUrl)
Returns the certificate-based authentication endpoint for the My Domain URL if the org has certificate-based authentication enabled.
getDefaultProfileForRegistration()
Returns the profile ID assigned to new community users.
getFooterText()
Returns the text at the bottom of the login page for a community.

66
Apex Reference Guide AuthConfiguration Class

getForgotPasswordUrl()
Returns the URL for the standard or custom Forgot Password page that is specified for an Experience Cloud site or portal by the
administrator.
getHeadlessForgotPasswordEnabled()
Returns true if the Headless Forgot Password Flow is enabled.
getHeadlessFrgtPswEnabled()
This method will be deprecated in a future release. Use the getHeadlessForgotPasswordEnabled() method in this
class instead.
getHeadlessPasswordlessLoginEnabled()
Determines if headless passwordless login is enabled.
getHeadlessRegistrationEnabled()
Determines if the Headless Registration Flow is enabled.
getLogoUrl()
Returns the location of the icon image at the bottom of the login page for a community.
getRightFrameUrl()
Returns the URL for the right-frame content to display on the right side of the Experience Cloud site login page. The admin supplies
the URL.
getSamlProviders()
Returns the list of SAML-based authentication providers available for an Experience Cloud site or Salesforce My Domain subdomain.
getSamlSsoUrl(communityUrl, startURL, samlId)
Returns the single sign-on URL for an Experience Cloud site or Salesforce My Domain subdomain.
getSelfRegistrationEnabled()
Indicates whether the current community allows new users to create their own account by filling out a registration form.
getSelfRegistrationUrl()
Returns the location of the self-registration page for new users to sign up for an account with a community.
getStartUrl()
Returns the start page of an Experience Cloud site or Salesforce My Domain subdomain. This URL is the first page that users see when
they log in.
getUsernamePasswordEnabled()
Indicates whether the current community is set to display a login form asking for a username and password. You can configure the
community not to request a username and password if it is for unauthenticated users or users logging in with a third-party
authentication provider.
isCommunityUsingSiteAsContainer()
Returns true if the Experience Cloud site uses Site.com pages; otherwise, returns false.

getAllowInternalUserLoginEnabled()
Indicates whether the Experience Cloud site allows internal users to log in using the Experience Cloud site login page. To enable, admins
configure the setting Allow internal users to log in directly to the experience on the Login & Registration page in Experience
Workspaces. It’s disabled by default.

67
Apex Reference Guide AuthConfiguration Class

Signature
public Boolean getAllowInternalUserLoginEnabled()

Return Value
Type: Boolean

Usage
If true, internal users log in to an Experience Cloud site from the site’s login page with their internal credentials. If they navigate to their
internal org from the Experience Cloud site, they don't have to log in again.

getAuthConfig()
Returns the AuthConfig sObject, which represents the authentication options for an Experience Cloud site or Salesforce My Domain
subdomain.

Signature
public AuthConfig getAuthConfig()

Return Value
Type: AuthConfig
The AuthConfig sObject for the Experience Cloud site or Salesforce My Domain subdomain.

getAuthConfigProviders()
Returns the list of authentication providers configured for an Experience Cloud site or Salesforce My Domain subdomain.

Signature
public List<AuthConfigProviders> getAuthConfigProviders()

Return Value
Type: List<AuthConfigProviders>
A list of authentication providers (AuthConfigProviders sObjects), which are children of the AuthProvider sObject.

getAuthProviders()
Returns the list of authentication providers available for an Experience Cloud site or Salesforce My Domain subdomain.

Signature
public List<AuthProvider> getAuthProviders()

Return Value
Type: List<AuthProvider>

68
Apex Reference Guide AuthConfiguration Class

A list of authentication providers (AuthProvider sObjects) for the Experience Cloud site or My Domain subdomain.

getAuthProviderSsoDomainUrl(communityUrl, startUrl, developerName)


Returns the single sign-on URL for an Experience Cloud site subdomain.

Note: For better performance, we recommend using this method instead of getAuthProviderSsoUrl. If the authentication
provider has User Subdomain for Callback enabled, changing the single sign-on URL also changes the callback URL
to use the Experience Cloud site subdomain. Before switching to this method, update the callback URL in your third-party applications
to avoid getting an invalid callback URL error during single sign-on.

Signature
public static String getAuthProviderSsoDomainUrl(String communityUrl, String startUrl,
String developerName)

Parameters
communityUrl
Type: String
The URL for the Experience Cloud site subdomain. If null or specified as an empty string, you get the single sign-on URL for the org’s
My Domain.
startUrl
Type: String
The page that users see after logging in to the Experience Cloud site subdomain.
developerName
Type: String
The unique name of the authentication provider.

Return Value
Type: String
The Single Sign-On Initialization URL for the Experience Cloud site subdomain.

getAuthProviderSsoUrl(communityUrl, startUrl, developerName)


Returns the single sign-on URL for an Experience Cloud site or Salesforce My Domain subdomain.

Signature
public static String getAuthProviderSsoUrl(String communityUrl, String startUrl, String
developerName)

Parameters
communityUrl
Type: String

69
Apex Reference Guide AuthConfiguration Class

The URL for the Experience Cloud site or My Domain subdomain. If not null and not specified as an empty string, you get the URL
for the Experience Cloud site. If null or specified as an empty string, you get the URL for a custom domain.
startUrl
Type: String
The page that users see after logging in to the Experience Cloud site or My Domain subdomain.
developerName
Type: String
The unique name of the authentication provider.

Return Value
Type: String
The Single Sign-On Initialization URL for the Experience Cloud site or Salesforce My Domain subdomain.

getBackgroundColor()
Returns the color for the background of the login page for a community.

Signature
public String getBackgroundColor()

Return Value
Type: String

getCertificateLoginEnabled(domainUrl)
Returns true if certificate-based authentication is enabled for the My Domain URL.

Signature
public Boolean getCertificateLoginEnabled(String domainUrl)

Parameters
domainUrl
Type: String
The My Domain URL that is being checked for certificate-based authentication.

Return Value
Type: Boolean

getCertificateLoginUrl(domainUrl, startUrl)
Returns the certificate-based authentication endpoint for the My Domain URL if the org has certificate-based authentication enabled.

70
Apex Reference Guide AuthConfiguration Class

Signature
public static String getCertificateLoginUrl(String domainUrl, String startUrl)

Parameters
domainUrl
Type: String
The My Domain URL being checked for its certificate-based authentication endpoint .
startUrl
Type: String
The page that the user is directed to after logging in to the My Domain with certificate-based authentication.

Return Value
Type: String
The certificate-based authentication endpoint for the My Domain URL:
mydomainURL:8443/services/certauth?startURL=startURLParam

getDefaultProfileForRegistration()
Returns the profile ID assigned to new community users.

Signature
public String getDefaultProfileForRegistration()

Return Value
Type: String
The profile ID.

getFooterText()
Returns the text at the bottom of the login page for a community.

Signature
public String getFooterText()

Return Value
Type: String
The text string displayed at the bottom of the login page, for example “Log in with an existing account.”

getForgotPasswordUrl()
Returns the URL for the standard or custom Forgot Password page that is specified for an Experience Cloud site or portal by the
administrator.

71
Apex Reference Guide AuthConfiguration Class

Signature
public String getForgotPasswordUrl()

Return Value
Type: String
URL for the standard or custom Forgot Password page.

getHeadlessForgotPasswordEnabled()
Returns true if the Headless Forgot Password Flow is enabled.

Signature
public Boolean getHeadlessForgotPasswordEnabled()

Return Value
Type: Boolean

getHeadlessFrgtPswEnabled()
This method will be deprecated in a future release. Use the getHeadlessForgotPasswordEnabled() method in this class
instead.

Signature
public Boolean getHeadlessFrgtPswEnabled()

Return Value
Type: Boolean

getHeadlessPasswordlessLoginEnabled()
Determines if headless passwordless login is enabled.

Signature
public Boolean getHeadlessPasswordlessLoginEnabled()

Return Value
Type: Boolean
Returns true if headless passwordless login is enabled.

getHeadlessRegistrationEnabled()
Determines if the Headless Registration Flow is enabled.

72
Apex Reference Guide AuthConfiguration Class

Signature
public Boolean getHeadlessRegistrationEnabled()

Return Value
Type: Boolean
Returns true if headless registration is enabled.

getLogoUrl()
Returns the location of the icon image at the bottom of the login page for a community.

Signature
public String getLogoUrl()

Return Value
Type: String
The path to the icon image.

getRightFrameUrl()
Returns the URL for the right-frame content to display on the right side of the Experience Cloud site login page. The admin supplies the
URL.

Signature
public String getLoginRightFrameUrl()

Return Value
Type: String
URL for the right-frame content of the Experience Cloud site login page. Salesforce creates an inline (iframe) on the right side of the login
page to display the contents specified by the URL.

getSamlProviders()
Returns the list of SAML-based authentication providers available for an Experience Cloud site or Salesforce My Domain subdomain.

Signature
public List<SamlSsoConfig> getSamlProviders()

Return Value
Type: List<SamlSsoConfig>
A list of SAML-based authentication providers, which are SamlSsoConfig sObjects.

73
Apex Reference Guide AuthConfiguration Class

getSamlSsoUrl(communityUrl, startURL, samlId)


Returns the single sign-on URL for an Experience Cloud site or Salesforce My Domain subdomain.

Signature
public static String getSamlSsoUrl(String communityUrl, String startURL, String samlId)

Parameters
communityUrl
Type: String
The URL for the Experience Cloud site or My Domain subdomain. If not null and not specified as an empty string, you get the URL
for the Experience Cloud site. If null or specified as an empty string, you get the URL for a My Domain subdomain.
startUrl
Type: String
The page users see after successfully logging in to the Experience Cloud site or My Domain subdomain
samlId
Type: String
The unique identifier of the SamlSsoConfig standard object for the Experience Cloud site or My Domain subdomain

Return Value
Type: String
The Single Sign-On Initialization URL for the Experience Cloud site or Salesforce My Domain subdomain.

getSelfRegistrationEnabled()
Indicates whether the current community allows new users to create their own account by filling out a registration form.

Signature
public Boolean getSelfRegistrationEnabled()

Return Value
Type: Boolean

getSelfRegistrationUrl()
Returns the location of the self-registration page for new users to sign up for an account with a community.

Signature
public String getSelfRegistrationUrl()

Return Value
Type: String

74
Apex Reference Guide AuthProviderCallbackState Class

The location of the self-registration page.

getStartUrl()
Returns the start page of an Experience Cloud site or Salesforce My Domain subdomain. This URL is the first page that users see when
they log in.

Signature
public String getStartUrl()

Return Value
Type: String
The location of the start page for the Experience Cloud site or My Domain subdomain.

getUsernamePasswordEnabled()
Indicates whether the current community is set to display a login form asking for a username and password. You can configure the
community not to request a username and password if it is for unauthenticated users or users logging in with a third-party authentication
provider.

Signature
public Boolean getUsernamePasswordEnabled()

Return Value
Type: Boolean

isCommunityUsingSiteAsContainer()
Returns true if the Experience Cloud site uses Site.com pages; otherwise, returns false.

Signature
public Boolean isCommunityUsingSiteAsContainer()

Return Value
Type: Boolean

AuthProviderCallbackState Class
Provides request HTTP headers, body, and query parameters to the AuthProviderPlugin.handleCallback method for
user authentication. This class allows you to group the information passed in rather than passing headers, body, and query parameters
individually.

75
Apex Reference Guide AuthProviderCallbackState Class

Namespace
Auth

IN THIS SECTION:
AuthProviderCallbackState Constructors
AuthProviderCallbackState Properties

SEE ALSO:
handleCallback(authProviderConfiguration, callbackState)

AuthProviderCallbackState Constructors
The following are constructors for AuthProviderCallbackState.

IN THIS SECTION:
AuthProviderCallbackState(headers, body, queryParameters)
Creates an instance of the AuthProviderCallbackState class using the specified HTTP headers, body, and query parameters
of the authentication request.

AuthProviderCallbackState(headers, body, queryParameters)


Creates an instance of the AuthProviderCallbackState class using the specified HTTP headers, body, and query parameters
of the authentication request.

Signature
public AuthProviderCallbackState(Map<String,String> headers, String body,
Map<String,String> queryParameters)

Parameters
headers
Type: Map<String,String>
The HTTP headers of the authentication request.
body
Type: String
The HTTP body of the authentication request.
queryParameters
Type: Map<String,String>
The HTTP query parameters of the authentication request.

AuthProviderCallbackState Properties
The following are properties for AuthProviderCallbackState.

76
Apex Reference Guide AuthProviderPlugin Interface

IN THIS SECTION:
body
The HTTP body of the authentication request.
headers
The HTTP headers of the authentication request.
queryParameters
The HTTP query parameters of the authentication request.

body
The HTTP body of the authentication request.

Signature
public String body {get; set;}

Property Value
Type: String

headers
The HTTP headers of the authentication request.

Signature
public Map<String,String> headers {get; set;}

Property Value
Type: Map<String,String>

queryParameters
The HTTP query parameters of the authentication request.

Signature
public Map<String,String> queryParameters {get; set;}

Property Value
Type: Map<String,String>

AuthProviderPlugin Interface
This interface is deprecated. For new development, use the abstract class Auth.AuthProviderPluginClass to create a custom
OAuth-based authentication provider plug-in for single sign-on in to Salesforce.

77
Apex Reference Guide AuthProviderPlugin Interface

Namespace
Auth

Usage
Deprecated. Existing implementations that use Auth.AuthProviderPlugin still work. For new development, use
Auth.AuthProviderPluginClass.

IN THIS SECTION:
AuthProviderPlugin Methods
AuthProviderPlugin Example Implementation

AuthProviderPlugin Methods
The following methods are for AuthProviderPlugin, which, as of API version 39.0, is deprecated. Use themethods in
AuthProviderPluginClass instead.

IN THIS SECTION:
getCustomMetadataType()
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.
getUserInfo(authProviderConfiguration, response)
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.
handleCallback(authProviderConfiguration, callbackState)
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.
initiate(authProviderConfiguration, stateToPropagate)
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.

SEE ALSO:
Salesforce Help: Create a Custom External Authentication Provider

getCustomMetadataType()
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.

Signature
public String getCustomMetadataType()

Return Value
Type: String
The custom metadata type API name for the authentication provider.

78
Apex Reference Guide AuthProviderPlugin Interface

Usage
Returns the custom metadata type API name for a custom OAuth-based authentication provider for single sign-on to Salesforce. The
getCustomMetatadaType() method returns only custom metadata type names. It does not return custom metadata record
names.

getUserInfo(authProviderConfiguration, response)
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.

Signature
public Auth.UserData getUserInfo(Map<String,String> authProviderConfiguration,
Auth.AuthProviderTokenResponse response)

Parameters
authProviderConfiguration
Type: Map<String,String>
The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates with the custom metadata type default values. Or you can set the configuration with values you enter when you create
the custom provider in Auth. Providers in Setup.
response
Type: Auth.AuthProviderTokenResponse
The OAuth access token, OAuth secret or refresh token, and state provided by the authentication provider to authenticate the current
user.

Return Value
Type: Auth.UserData
Creates a new instance of the Auth.UserData class.

Usage
Returns information from the custom authentication provider about the current user. The registration handler and other authentication
provider flows use this information.

handleCallback(authProviderConfiguration, callbackState)
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.

Signature
public Auth.AuthProviderTokenResponse handleCallback(Map<String,String>
authProviderConfiguration, Auth.AuthProviderCallbackState callbackState)

Parameters
authProviderConfiguration
Type: Map<StringString>

79
Apex Reference Guide AuthProviderPlugin Interface

The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates with the custom metadata type default values. Or you can set the configuration with values you enter when you create
the custom provider in Auth. Providers in Setup.
callbackState
Type: Auth.AuthProviderCallbackState
The class that contains the HTTP headers, body, and queryParams of the authentication request.

Return Value
Type: Auth.AuthProviderTokenResponse
Creates an instance of the AuthProviderTokenResponse class.

Usage
Uses the authentication provider’s supported authentication protocol to return an OAuth access token, OAuth secret or refresh token,
and the state passed in when the request for the current user was initiated.

initiate(authProviderConfiguration, stateToPropagate)
Deprecated as of API version 39.0. Use the corresponding method in Auth.AuthProviderPluginClass.

Signature
public System.PageReference initiate(Map<String,String> authProviderConfiguration,
String stateToPropagate)

Parameters
authProviderConfiguration
Type: Map<StringString>
The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates with the custom metadata type default values. Or you can set the configuration with values you enter when you create
the custom provider in Auth. Providers in Setup.
stateToPropagate
Type: String
The state passed in to initiate the authentication request for the user.

Return Value
Type: System.PageReference
The URL of the page where the user is redirected for authentication.

Usage
Returns the URL where the user is redirected for authentication.

80
Apex Reference Guide AuthProviderPluginClass Class

AuthProviderPlugin Example Implementation


We’ve removed the example implementation for the Auth.AuthProviderPlugin interface because we’ve deprecated the
interface and replaced it with an abstract class. See AuthProviderPluginClass Class.

AuthProviderPluginClass Class
Contains methods to create a custom OAuth-based authentication provider plug-in for single sign-on in to Salesforce. Use this class to
create a custom authentication provider plug-in if you can’t use one of the authentication providers that Salesforce provides.

Namespace
Auth

Usage
To create a custom authentication provider for single sign-on, create a class that extends Auth.AuthProviderPluginClass.
This class allows you to store the custom configuration for your authentication provider and handle authentication protocols when users
log in to Salesforce with their login credentials for an external service provider. In Salesforce, the class that implements this interface
appears in the Provider Type drop-down list in Auth. Providers in Setup. Make sure that the user you specify to run the class has
“Customize Application” and “Manage Auth. Providers” permissions.
As of API version 39.0, use the abstract class AuthProviderPluginClass to create a custom external authentication provider.
This class replaces the AuthProviderPlugin interface. If you’ve already implemented a custom authentication provider plug-in
using the interface, it still works. However, use AuthProviderPluginClass to extend your plug-in. If you haven’t created an
interface, create a custom authentication provider plug-in by extending this abstract class. For more information, see
AuthProviderPluginClass Code Example.

IN THIS SECTION:
AuthProviderPluginClass Methods
AuthProviderPluginClass Code Example

AuthProviderPluginClass Methods
The AuthProviderPluginClass methods don’t support DML options.

IN THIS SECTION:
getCustomMetadataType()
Returns the custom metadata type API name for a custom OAuth-based authentication provider for single sign-on to Salesforce.
getUserInfo(authProviderConfiguration, response)
Returns information from the custom authentication provider about the current user. This information is used by the registration
handler and in other authentication provider flows.
handleCallback(authProviderConfiguration, callbackState)
Uses the authentication provider’s supported authentication protocol to return an OAuth access token, OAuth secret or refresh token,
and the state passed in when the request for the current user was initiated.

81
Apex Reference Guide AuthProviderPluginClass Class

initiate(authProviderConfiguration, stateToPropagate)
Returns the URL where the user is redirected for authentication.
refresh(authProviderConfiguration, refreshToken)
Returns a new access token, which is used to update an expired access token.

getCustomMetadataType()
Returns the custom metadata type API name for a custom OAuth-based authentication provider for single sign-on to Salesforce.

Signature
public String getCustomMetadataType()

Return Value
Type: String
The custom metadata type API name for the authentication provider.

Usage
The getCustomMetatadaType() method returns only custom metadata type names. It does not return custom metadata record
names. As of API version 39.0, use this method when extending Auth.AuthProviderPluginClass to create a custom external
authentication provider.

getUserInfo(authProviderConfiguration, response)
Returns information from the custom authentication provider about the current user. This information is used by the registration handler
and in other authentication provider flows.

Signature
public Auth.UserData getUserInfo(Map<String,String> authProviderConfiguration,
Auth.AuthProviderTokenResponse response)

Parameters
authProviderConfiguration
Type: Map<String,String>
The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates it with the custom metadata type default values. Or you can set the configuration with values that you enter when you
create the custom provider in Auth. Providers in Setup.
response
Type: Auth.AuthProviderTokenResponse
The OAuth access token, OAuth secret or refresh token, and state provided by the authentication provider to authenticate the current
user.

82
Apex Reference Guide AuthProviderPluginClass Class

Return Value
Type: Auth.UserData
Creates a new instance of the Auth.UserData class.

Usage
As of API version 39.0, use this method when extending Auth.AuthProviderPluginClass to create a custom authentication
provider.

Note: You might choose to get user information in the response from the handleCallback method or by another method.
However, you must still call getUserInfo in the custom authentication handler to avoid getting errors about mixing objects.
For example, if you don’t call getUserInfo, and then try to insert a contact in the
Auth.RegistrationHandler.createUser method, you get the error, “You cannot mix EntityObjects with different
UddInfos within one transaction.”
To avoid this error, call getUserInfo with dummy user information as follows.

HttpRequest req = new HttpRequest();


String url = 'https://login.salesforce.com/';
req.setEndpoint(url);
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);

handleCallback(authProviderConfiguration, callbackState)
Uses the authentication provider’s supported authentication protocol to return an OAuth access token, OAuth secret or refresh token,
and the state passed in when the request for the current user was initiated.

Signature
public Auth.AuthProviderTokenResponse handleCallback(Map<String,String>
authProviderConfiguration, Auth.AuthProviderCallbackState callbackState)

Parameters
authProviderConfiguration
Type: Map<StringString>
The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates with the custom metadata type default values. Or you can set the configuration with values you enter when you create
the custom provider in Auth. Providers in Setup.
callbackState
Type: Auth.AuthProviderCallbackState
The class that contains the HTTP headers, body, and queryParams of the authentication request.

Return Value
Type: Auth.AuthProviderTokenResponse
Creates an instance of the AuthProviderTokenResponse class.

83
Apex Reference Guide AuthProviderPluginClass Class

Usage
As of API version 39.0, use this method when extending Auth.AuthProviderPluginClass to create a custom authentication
provider.

initiate(authProviderConfiguration, stateToPropagate)
Returns the URL where the user is redirected for authentication.

Signature
public System.PageReference initiate(Map<String,String> authProviderConfiguration,
String stateToPropagate)

Parameters
authProviderConfiguration
Type: Map<StringString>
The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates with the custom metadata type default values. Or you can set the configuration with values you enter when you create
the custom provider in Auth. Providers in Setup.
stateToPropagate
Type: String
The state passed in to initiate the authentication request for the user.

Return Value
Type: System.PageReference
The URL of the page where the user is redirected for authentication.

Usage
As of API version 39.0, use this method when extending Auth.AuthProviderPluginClass to create a custom authentication
provider.

refresh(authProviderConfiguration, refreshToken)
Returns a new access token, which is used to update an expired access token.

Signature
public Auth.OAuthRefreshResult refresh(Map<String,String> authProviderConfiguration,
String refreshToken)

Parameters
authProviderConfiguration
Type: Map<String,String>

84
Apex Reference Guide AuthProviderPluginClass Class

The configuration for the custom authentication provider. When you create a custom metadata type in Salesforce, the configuration
populates with the custom metadata type default values. Or you can set the configuration with values you enter when you create
the custom provider in Auth. Providers in Setup.
refreshToken
Type: String
The refresh token for the user who is logged in.

Return Value
Type: Auth.OAuthRefreshResult
Returns the new access token, or an error message if an error occurs.

Usage
A successful request returns a Auth.OAuthRefreshResult with the access token and refresh token in the response. If you receive
an error, make sure that you set the error string to the error message. A NULL error string indicates no error.
The refresh method works only with named credentials; it doesn’t respect the standard OAuth refresh flow. The refresh method with
named credentials works only if the earlier request returns a 401.

AuthProviderPluginClass Code Example


The following example demonstrates how to implement a custom Auth. provider plug-in using the abstract class,
Auth.AuthProviderPluginClass.

global class Concur extends Auth.AuthProviderPluginClass {

// Use this URL for the endpoint that the


// authentication provider calls back to for configuration.
public String redirectUrl;
private String key;
private String secret;

// Application redirection to the Concur website for


// authentication and authorization.
private String authUrl;

// URI to get the new access token from concur using the GET verb.
private String accessTokenUrl;

// Api name for the custom metadata type created for this auth provider.
private String customMetadataTypeApiName;

// Api URL to access the user in Concur


private String userAPIUrl;

// Version of the user api URL to access data from Concur


private String userAPIVersionUrl;

global String getCustomMetadataType() {


return customMetadataTypeApiName;

85
Apex Reference Guide AuthProviderPluginClass Class

global PageReference initiate(Map<string,string>


authProviderConfiguration, String stateToPropagate)
{
authUrl = authProviderConfiguration.get('Auth_Url__c');
key = authProviderConfiguration.get('Key__c');

// Here the developer can build up a request of some sort.


// Ultimately, they return a URL where we will redirect the user.
String url = authUrl + '?client_id='+ key
+'&scope=USER,EXPRPT,LIST&redirect_uri='+ redirectUrl + '&state=' + stateToPropagate;
return new PageReference(url);
}

global Auth.AuthProviderTokenResponse handleCallback(Map<string,string>


authProviderConfiguration, Auth.AuthProviderCallbackState state )
{
// Here, the developer will get the callback with actual protocol.
// Their responsibility is to return a new object called
// AuthProviderTokenResponse.
// This will contain an optional accessToken and refreshToken
key = authProviderConfiguration.get('Key__c');
secret = authProviderConfiguration.get('Secret__c');
accessTokenUrl = authProviderConfiguration.get('Access_Token_Url__c');

Map<String,String> queryParams = state.queryParameters;


String code = queryParams.get('code');
String sfdcState = queryParams.get('state');

HttpRequest req = new HttpRequest();


String url = accessTokenUrl+'?code=' + code + '&client_id=' + key +
'&client_secret=' + secret;
req.setEndpoint(url);
req.setHeader('Content-Type','application/xml');
req.setMethod('GET');

Http http = new Http();


HTTPResponse res = http.send(req);
String responseBody = res.getBody();
String token = getTokenValueFromResponse(responseBody, 'Token', null);

return new Auth.AuthProviderTokenResponse('Concur', token,


'refreshToken', sfdcState);
}

global Auth.UserData getUserInfo(Map<string,string>


authProviderConfiguration,
Auth.AuthProviderTokenResponse response)
{
//Here the developer is responsible for constructing an
//Auth.UserData object
String token = response.oauthToken;
HttpRequest req = new HttpRequest();

86
Apex Reference Guide AuthProviderPluginClass Class

userAPIUrl = authProviderConfiguration.get('API_User_Url__c');
userAPIVersionUrl = authProviderConfiguration.get
('API_User_Version_Url__c');
req.setHeader('Authorization', 'OAuth ' + token);
req.setEndpoint(userAPIUrl);
req.setHeader('Content-Type','application/xml');
req.setMethod('GET');

Http http = new Http();


HTTPResponse res = http.send(req);
String responseBody = res.getBody();
String id = getTokenValueFromResponse(responseBody,
'LoginId',userAPIVersionUrl);
String fname = getTokenValueFromResponse(responseBody,
'FirstName', userAPIVersionUrl);
String lname = getTokenValueFromResponse(responseBody,
'LastName', userAPIVersionUrl);
String flname = fname + ' ' + lname;
String uname = getTokenValueFromResponse(responseBody,
'EmailAddress', userAPIVersionUrl);
String locale = getTokenValueFromResponse(responseBody,
'LocaleName', userAPIVersionUrl);
Map<String,String> provMap = new Map<String,String>();
provMap.put('what1', 'noidea1');
provMap.put('what2', 'noidea2');
return new Auth.UserData(id, fname, lname, flname,
uname, 'what', locale, null, 'Concur', null, provMap);
}

private String getTokenValueFromResponse(String response,


String token, String ns)
{
Dom.Document docx = new Dom.Document();
docx.load(response);
String ret = null;

dom.XmlNode xroot = docx.getrootelement() ;


if(xroot != null){ ret = xroot.getChildElement(token, ns).getText();
}
return ret;
}

Sample Test Classes


The following example contains test classes for the Concur class.

@IsTest
public class ConcurTestClass {

private static final String OAUTH_TOKEN = 'testToken';


private static final String STATE = 'mocktestState';

87
Apex Reference Guide AuthProviderPluginClass Class

private static final String REFRESH_TOKEN = 'refreshToken';


private static final String LOGIN_ID = 'testLoginId';
private static final String USERNAME = 'testUsername';
private static final String FIRST_NAME = 'testFirstName';
private static final String LAST_NAME = 'testLastName';
private static final String EMAIL_ADDRESS = 'testEmailAddress';
private static final String LOCALE_NAME = 'testLocalName';
private static final String FULL_NAME = FIRST_NAME + ' ' + LAST_NAME;
private static final String PROVIDER = 'Concur';
private static final String REDIRECT_URL =
'http://localhost/services/authcallback/orgId/Concur';
private static final String KEY = 'testKey';
private static final String SECRET = 'testSecret';
private static final String STATE_TO_PROPOGATE = 'testState';
private static final String ACCESS_TOKEN_URL =
'http://www.dummyhost.com/accessTokenUri';
private static final String API_USER_VERSION_URL =
'http://www.dummyhost.com/user/20/1';
private static final String AUTH_URL =
'http://www.dummy.com/authurl';
private static final String API_USER_URL =
'www.concursolutions.com/user/api';

// In the real world scenario, the key and value would be read
// from the (custom fields in) custom metadata type record.
private static Map<String,String> setupAuthProviderConfig ()
{
Map<String,String> authProviderConfiguration = new Map<String,String>();

authProviderConfiguration.put('Key__c', KEY);
authProviderConfiguration.put('Auth_Url__c', AUTH_URL);
authProviderConfiguration.put('Secret__c', SECRET);
authProviderConfiguration.put('Access_Token_Url__c', ACCESS_TOKEN_URL);
authProviderConfiguration.put('API_User_Url__c',API_USER_URL);
authProviderConfiguration.put('API_User_Version_Url__c',
API_USER_VERSION_URL);
authProviderConfiguration.put('Redirect_Url__c',REDIRECT_URL);
return authProviderConfiguration;

static testMethod void testInitiateMethod()


{
String stateToPropogate = 'mocktestState';
Map<String,String> authProviderConfiguration = setupAuthProviderConfig();

Concur concurCls = new Concur();


concurCls.redirectUrl = authProviderConfiguration.get('Redirect_Url__c');

PageReference expectedUrl = new


PageReference(authProviderConfiguration.get('Auth_Url__c') + '?client_id='+
authProviderConfiguration.get('Key__c') +'&scope=USER,EXPRPT,LIST&redirect_uri='+

authProviderConfiguration.get('Redirect_Url__c') + '&state=' +

88
Apex Reference Guide AuthProviderPluginClass Class

STATE_TO_PROPOGATE);
PageReference actualUrl = concurCls.initiate(authProviderConfiguration,
STATE_TO_PROPOGATE);
System.assertEquals(expectedUrl.getUrl(), actualUrl.getUrl());
}

static testMethod void testHandleCallback()


{
Map<String,String> authProviderConfiguration =
setupAuthProviderConfig();
Concur concurCls = new Concur();
concurCls.redirectUrl = authProviderConfiguration.get
('Redirect_Url_c');

Test.setMock(HttpCalloutMock.class, new
ConcurMockHttpResponseGenerator());

Map<String,String> queryParams = new Map<String,String>();


queryParams.put('code','code');
queryParams.put('state',authProviderConfiguration.get('State_c'));
Auth.AuthProviderCallbackState cbState =
new Auth.AuthProviderCallbackState(null,null,queryParams);
Auth.AuthProviderTokenResponse actualAuthProvResponse =
concurCls.handleCallback(authProviderConfiguration, cbState);
Auth.AuthProviderTokenResponse expectedAuthProvResponse =
new Auth.AuthProviderTokenResponse(
'Concur', OAUTH_TOKEN, REFRESH_TOKEN, null);

System.assertEquals(expectedAuthProvResponse.provider,
actualAuthProvResponse.provider);
System.assertEquals(expectedAuthProvResponse.oauthToken,
actualAuthProvResponse.oauthToken);
System.assertEquals(expectedAuthProvResponse.oauthSecretOrRefreshToken,
actualAuthProvResponse.oauthSecretOrRefreshToken);
System.assertEquals(expectedAuthProvResponse.state,
actualAuthProvResponse.state);

static testMethod void testGetUserInfo()


{
Map<String,String> authProviderConfiguration =
setupAuthProviderConfig();
Concur concurCls = new Concur();

Test.setMock(HttpCalloutMock.class, new
ConcurMockHttpResponseGenerator());

Auth.AuthProviderTokenResponse response =
new Auth.AuthProviderTokenResponse(
PROVIDER, OAUTH_TOKEN ,'sampleOauthSecret', STATE);
Auth.UserData actualUserData = concurCls.getUserInfo(
authProviderConfiguration, response) ;

89
Apex Reference Guide AuthProviderPluginClass Class

Map<String,String> provMap = new Map<String,String>();


provMap.put('key1', 'value1');
provMap.put('key2', 'value2');

Auth.UserData expectedUserData = new Auth.UserData(LOGIN_ID,


FIRST_NAME, LAST_NAME, FULL_NAME, EMAIL_ADDRESS,
null, LOCALE_NAME, null, PROVIDER, null, provMap);

System.assertNotEquals(expectedUserData,null);
System.assertEquals(expectedUserData.firstName,
actualUserData.firstName);
System.assertEquals(expectedUserData.lastName,
actualUserData.lastName);
System.assertEquals(expectedUserData.fullName,
actualUserData.fullName);
System.assertEquals(expectedUserData.email,
actualUserData.email);
System.assertEquals(expectedUserData.username,
actualUserData.username);
System.assertEquals(expectedUserData.locale,
actualUserData.locale);
System.assertEquals(expectedUserData.provider,
actualUserData.provider);
System.assertEquals(expectedUserData.siteLoginUrl,
actualUserData.siteLoginUrl);
}

// Implement a mock http response generator for Concur.


public class ConcurMockHttpResponseGenerator implements HttpCalloutMock
{
public HTTPResponse respond(HTTPRequest req)
{
String namespace = API_USER_VERSION_URL;
String prefix = 'mockPrefix';

Dom.Document doc = new Dom.Document();


Dom.XmlNode xmlNode = doc.createRootElement(
'mockRootNodeName', namespace, prefix);
xmlNode.addChildElement('LoginId', namespace, prefix)
.addTextNode(LOGIN_ID);
xmlNode.addChildElement('FirstName', namespace, prefix)
.addTextNode(FIRST_NAME);
xmlNode.addChildElement('LastName', namespace, prefix)
.addTextNode(LAST_NAME);
xmlNode.addChildElement('EmailAddress', namespace, prefix)
.addTextNode(EMAIL_ADDRESS);
xmlNode.addChildElement('LocaleName', namespace, prefix)
.addTextNode(LOCALE_NAME);
xmlNode.addChildElement('Token', null, null)
.addTextNode(OAUTH_TOKEN);
System.debug(doc.toXmlString());
// Create a fake response
HttpResponse res = new HttpResponse();

90
Apex Reference Guide AuthProviderTokenResponse Class

res.setHeader('Content-Type', 'application/xml');
res.setBody(doc.toXmlString());
res.setStatusCode(200);
return res;
}

}
}

AuthProviderTokenResponse Class
Stores the response from the AuthProviderPlugin.handleCallback method.

Namespace
Auth

IN THIS SECTION:
AuthProviderTokenResponse Constructors
AuthProviderTokenResponse Properties

AuthProviderTokenResponse Constructors
The following are constructors for AuthProviderTokenResponse.

IN THIS SECTION:
AuthProviderTokenResponse(provider, oauthToken, oauthSecretOrRefreshToken, state)
Creates an instance of the AuthProviderTokenResponse class for a custom authentication provider plug-in using the
specified arguments.
AuthProviderTokenResponse(provider, oauthToken, oauthSecretOrRefreshToken, state, idToken)
Creates an instance of the AuthProviderTokenResponse class for a custom authentication provider plug-in using the specified
arguments. This constructor includes a parameter for the ID token.

AuthProviderTokenResponse(provider, oauthToken, oauthSecretOrRefreshToken,


state)
Creates an instance of the AuthProviderTokenResponse class for a custom authentication provider plug-in using the specified
arguments.

Signature
public AuthProviderTokenResponse(String provider, String oauthToken, String
oauthSecretOrRefreshToken, String state)

91
Apex Reference Guide AuthProviderTokenResponse Class

Parameters
provider
Type: String
The custom authentication provider.
oauthToken
Type: String
The OAuth access token.
oauthSecretOrRefreshToken
Type: String
The OAuth secret or refresh token for the currently logged-in user.
state
Type: String
The state passed in to initiate the authentication request for the user.

AuthProviderTokenResponse(provider, oauthToken, oauthSecretOrRefreshToken,


state, idToken)
Creates an instance of the AuthProviderTokenResponse class for a custom authentication provider plug-in using the specified arguments.
This constructor includes a parameter for the ID token.

Signature
public AuthProviderTokenResponse(String provider, String oauthToken, String
oauthSecretOrRefreshToken, String state)

Parameters
provider
Type: String
The custom authentication provider.
oauthToken
Type: String
The OAuth access token.
oauthSecretOrRefreshToken
Type: String
The OAuth secret or refresh token for the currently logged-in user.
state
Type: String
The state passed in to initiate the authentication request for the user.
idToken
Type: String
The ID token in encoded JWT format.

92
Apex Reference Guide AuthProviderTokenResponse Class

AuthProviderTokenResponse Properties
The following are properties for AuthProviderTokenResponse.

IN THIS SECTION:
oauthSecretOrRefreshToken
The OAuth secret or refresh token for the currently logged-in user.
oauthToken
The OAuth access token.
provider
The authentication provider.
state
The state passed in to initiate the authentication request for the user.
idToken
The ID token from the third party in encoded JWT format.

oauthSecretOrRefreshToken
The OAuth secret or refresh token for the currently logged-in user.

Signature
public String oauthSecretOrRefreshToken {get; set;}

Property Value
Type: String

oauthToken
The OAuth access token.

Signature
public String oauthToken {get; set;}

Property Value
Type: String

provider
The authentication provider.

Signature
public String provider {get; set;}

93
Apex Reference Guide AuthToken Class

Property Value
Type: String

state
The state passed in to initiate the authentication request for the user.

Signature
public String state {get; set;}

Property Value
Type: String

idToken
The ID token from the third party in encoded JWT format.

Signature
public String idToken {get; set;}

Property Value
Type: String

AuthToken Class
Contains methods for getting and revoking access and refresh tokens that are issued when a user logs in via a single sign-on (SSO) flow
that uses an authentication provider, such as Facebook.

Namespace
Auth

Usage
To authenticate users via an authentication provider, you must create a class that implements the Auth.RegistrationHandler
interface. When a user logs in to Salesforce via a provider such as Facebook, they’re issued an access token and in some cases, a refresh
token. To retrieve and revoke these tokens, use the methods in the Auth.AuthToken class.

AuthToken Methods
The following are methods for AuthToken. All methods are static.

94
Apex Reference Guide AuthToken Class

IN THIS SECTION:
getAccessToken(authProviderId, providerName)
Returns an access token for the current user using the specified 18-character identifier of an AuthProvider definition in your org and
the proper name of the provider, such as Salesforce or Facebook.
getAccessTokenMap(authProviderId, providerName)
Returns a map from the provider’s identifier to the access token for the currently logged-in Salesforce user. The identifier value
depends on the provider. For example, for Salesforce, it’s the user ID, while for Facebook, it’s the user number.
refreshAccessToken(authProviderId, providerName, oldAccessToken)
Returns a map from the third-party provider’s identifier containing a refreshed access token for the currently logged-in Salesforce
user.
revokeAccess(authProviderId, providerName, userId, remoteIdentifier)
Revokes the access token for a specified SSO user from a provider such as Facebook. You can use this method only if the
IsNotSsoUsable field on the associated ThirdPartyAccountLink object is set to false.

getAccessToken(authProviderId, providerName)
Returns an access token for the current user using the specified 18-character identifier of an AuthProvider definition in your org and the
proper name of the provider, such as Salesforce or Facebook.

Signature
public static String getAccessToken(String authProviderId, String providerName)

Parameters
authProviderId
Type: String
providerName
Type: String
The proper name of the provider. Here are valid values for each provider type.
• Apple—Apple
• Custom—For a custom authentication provider, use the value in the FriendlyName field on the AuthProvider object, such
as MyProvider.
• Facebook—Facebook
• GitHub—GitHub
• Google—Google
• Janrain—Use the proper name of the third party, such as Yahoo!.
• LinkedIn—LinkedIn
• Microsoft—Microsoft
• Microsoft Access Control Service—Microsoft Access Control Service
• MuleSoft—MuleSoft
• Open ID Connect—Open ID Connect
• Salesforce—Salesforce
• Slack—Slack

95
Apex Reference Guide AuthToken Class

• Twitter—This method doesn’t support the Twitter authentication provider.

Note: The providerName value that you pass into this method can be different from the value that’s returned if you
query the ProviderType field on the AuthProvider object. For example, for Open ID Connect providers, OpenIdConnect
is the ProviderType value for the AuthProvider object, but the expected providerName is Open ID Connect.

Return Value
Type: String

getAccessTokenMap(authProviderId, providerName)
Returns a map from the provider’s identifier to the access token for the currently logged-in Salesforce user. The identifier value depends
on the provider. For example, for Salesforce, it’s the user ID, while for Facebook, it’s the user number.

Signature
public static Map<String, String> getAccessTokenMap(String authProviderId, String
providerName)

Parameters
authProviderId
Type: String
providerName
Type: String
The proper name of the provider. Here are valid values for each provider type.
• Apple—Apple
• Custom—For a custom authentication provider, use the value in the FriendlyName field on the AuthProvider object, such
as MyProvider.
• Facebook—Facebook
• GitHub—GitHub
• Google—Google
• Janrain—Use the proper name of the third party, such as Yahoo!.
• LinkedIn—LinkedIn
• Microsoft—Microsoft
• Microsoft Access Control Service—Microsoft Access Control Service
• MuleSoft—MuleSoft
• Open ID Connect—Open ID Connect
• Salesforce—Salesforce
• Slack—Slack
• Twitter—This method doesn’t support the Twitter authentication provider.

Note: The providerName value that you pass into this method can be different from the value that’s returned if you
query the ProviderType field on the AuthProvider object. For example, for Open ID Connect providers, OpenIdConnect
is the ProviderType value for the AuthProvider object, but the expected providerName is Open ID Connect.

96
Apex Reference Guide AuthToken Class

Return Value
Type: Map<String, String>

refreshAccessToken(authProviderId, providerName, oldAccessToken)


Returns a map from the third-party provider’s identifier containing a refreshed access token for the currently logged-in Salesforce user.

Signature
public static Map<String, String> refreshAccessToken(String authProviderId, String
providerName, String oldAccessToken)

Parameters
authProviderId
Type: String
providerName
Type: String
The proper name of the third party. Here are valid values for each provider type.
• Apple—Apple
• Custom—For a custom authentication provider, use the value in the FriendlyName field on the AuthProvider object, such
as MyProvider.
• Facebook—Facebook
• GitHub—GitHub
• Google—Google
• Janrain—Use the proper name of the third party, such as Yahoo!.
• LinkedIn—LinkedIn
• Microsoft—Microsoft
• Microsoft Access Control Service—Microsoft Access Control Service
• MuleSoft—MuleSoft
• Open ID Connect—Open ID Connect
• Salesforce—Salesforce
• Slack—Slack
• Twitter—This method doesn’t support the Twitter authentication provider.

Note: The providerName value that you pass into this method can be different from the value that’s returned if you
query the ProviderType field on the AuthProvider object. For example, for Open ID Connect providers, OpenIdConnect
is the ProviderType value for the AuthProvider object, but the expected providerName is Open ID Connect.
oldAccessToken
Type: String

Return Value
Type: Map<String, String>

97
Apex Reference Guide AuthToken Class

Usage
The returned map contains AccessToken and RefreshError keys. Evaluate the keys in the response to check if the request
was successful. For a successful request, the RefreshError value is null, and AccessToken is a token value. For an unsuccessful
request, the RefreshError value is an error message, and the AccessToken value is null.
When successful, this method updates the token stored in the database, which you can get using
Auth.AuthToken.getAccessToken().
If you’re using an OpenID Connect authentication provider, an id_token isn’t required in the response from the provider. If a Token
Issuer is specified in the Auth. Provider settings and an id_token is provided anyway, Salesforce verifies it.

Example
String accessToken = Auth.AuthToken.getAccessToken('0SOD000000000DeOAI', 'Open ID Connect');
Map<String, String> responseMap = Auth.AuthToken.refreshAccessToken('0SOD000000000DeOAI',
'Open ID Connect', accessToken);

A successful request includes the access token in the response.


(RefreshError,null)(AccessToken,00DD00000007BhE!AQkAQFzj...)

revokeAccess(authProviderId, providerName, userId, remoteIdentifier)


Revokes the access token for a specified SSO user from a provider such as Facebook. You can use this method only if the
IsNotSsoUsable field on the associated ThirdPartyAccountLink object is set to false.

Signature
public static Boolean revokeAccess(String authProviderId, String providerName, String
userId, String remoteIdentifier)

Parameters
authProviderId
Type: String
The ID of the authentication provider in Salesforce.
providerName
Type: String
The name of the third party. Here are valid providerName values for each provider type.

Important: The providerName value that you pass into this method must be lowercase.

• Apple—apple
• Custom—For a custom authentication provider, use a lowercase version of the value in the FriendlyName field on the
AuthProvider object. For example, if the FriendlyName is MyProvider, use myprovider.
• Facebook—facebook
• GitHub—github
• Google—google
• Janrain—Use a lowercase version of the name of the third party, such as yahoo!.

98
Apex Reference Guide CommunitiesUtil Class

• LinkedIn—linkedin
• Microsoft—microsoft
• Microsoft Access Control Service—microsoft access control service
• MuleSoft—mulesoft
• Open ID Connect—open id connect
• Salesforce—salesforce
• Slack—slack
• Twitter—twitter

Note: The providerName that you pass into this method is different from the value that you get if you query the
ProviderType field on the AuthProvider object. For example, for Open ID Connect providers, the providerType
value for the AuthProvider object is OpenIdConnect, but the providerName for the revokeAccess method is
open id connect.
userId
Type: String
The 15-character ID for the user whose access is being revoked.
remoteIdentifier
Type: String
The unique ID for the user in the third-party system (this value is in the associated ThirdPartyAccountLink standard object).

Return Value
Type: Boolean
The return value is true if the revokeAccess() operation is successful; otherwise false.

Example
The following example revokes a Facebook user's access token.
Auth.AuthToken.revokeAccess('0SOxx00000#####', 'facebook', '005xx00000#####',
'ThirdPartyIdentifier_exist214176560#####');

CommunitiesUtil Class
Contains methods for getting information about an Experience Cloud user.

Namespace
Auth

Example
The following example directs a guest (unauthenticated) user to one page, and authenticated users of the Experience Cloud site’s parent
organization to another page.
if (Auth.CommunitiesUtil.isGuestUser())
// Redirect to the login page if user is an unauthenticated user

99
Apex Reference Guide CommunitiesUtil Class

return new PageReference(LOGIN_URL);

if (Auth.CommunitiesUtil.isInternalUser())
// Redirect to the home page if user is an internal user
return new PageReference(HOME_URL);

CommunitiesUtil Methods
The following are methods for CommunitiesUtil. All methods are static.

IN THIS SECTION:
getLogoutUrl()
Returns the page to display after the current Experience Cloud user logs out.
getUserDisplayName()
Returns the current user’s Experience Cloud display name.
isGuestUser()
Indicates whether the current user isn’t logged in to the Experience Cloud site. Redirect the user to log in, if necessary.
isInternalUser()
Indicates whether the current user is logged in as a member of the parent Salesforce organization, such as an employee.

getLogoutUrl()
Returns the page to display after the current Experience Cloud user logs out.

Signature
public static String getLogoutUrl()

Return Value
Type: String

getUserDisplayName()
Returns the current user’s Experience Cloud display name.

Signature
public static String getUserDisplayName()

Return Value
Type: String

isGuestUser()
Indicates whether the current user isn’t logged in to the Experience Cloud site. Redirect the user to log in, if necessary.

100
Apex Reference Guide ConfigurableSelfRegHandler Interface

Signature
public static Boolean isGuestUser()

Return Value
Type: Boolean

isInternalUser()
Indicates whether the current user is logged in as a member of the parent Salesforce organization, such as an employee.

Signature
public static Boolean isInternalUser()

Return Value
Type: Boolean

ConfigurableSelfRegHandler Interface
Gives you more control over how customers or partners self-register for your Experience Cloud site by creating a class that implements
Auth.ConfigurableSelfRegHandler. You choose the user information to collect, and how users identify themselves—with
their email address, phone number, or another identifier. When verified, you create a customer or partner user and log in the user to
your Experience Cloud site.

Namespace
Auth

Usage
You set up site self-registration declaratively on the Login & Registration (L&R) page of the Administration workspace. When combined
with a configurable self-registration setup, the handler class can programmatically fill in user fields, including custom fields, and determine
how to create a user and log them in.
When you select the Configurable Self-Reg Page registration page, you choose the user fields to collect from the self-registration form,
such as last name, first name, username, nickname, mobile, or email. You also determine the verification method that the user identifies
themselves with, which can be email, mobile, or neither. Salesforce generates the Auth.ConfigurableSelfRegHandler
handler, which contains logic on how to create an Experience Cloud site member. Modify the handler to change how users are created,
and how collected user information is used.
You can add custom logic to ensure that the email or phone number is unique to the customer or partner who's registering. For example,
you can add a custom unique field, and write a copy of the email or phone number to it. You can also change how the user is created.
By default, the user is created as a contact associated with the account that you select on the L&R page.
The generated ConfigurableSelfRegHandler is located on the Setup Apex Classes page, and begins with
AutocreatedConfigSelfReg, for example, AutocreatedConfigSelfReg1532475901849.
For an example, see ConfigurableSelfRegHandler Example Implementation. For more details, see Salesforce Customer Identity in Salesforce
Help.

101
Apex Reference Guide ConfigurableSelfRegHandler Interface

IN THIS SECTION:
ConfigurableSelfRegHandler Method
ConfigurableSelfRegHandler Example Implementation
This Apex code implements the Auth.ConfigurableSelfRegHandler interface. After the customer or partner fills out
the sign-up page and submits it, the handler is invoked to create an Experience Cloud member with the supplied information. If the
registration process requires email or phone verification, the verification process finishes before the
Auth.ConfigurableSelfRegHandler.createUser is invoked. If verification isn’t required, createUser is invoked
when the customer or partner submits the page.

ConfigurableSelfRegHandler Method
The following is the method for ConfigurableSelfRegHandler.

IN THIS SECTION:
createUser(accountId, profileId, registrationAttributes, password)
Create a community member from the information that the visitor provided on your community’s self-registration page.

createUser(accountId, profileId, registrationAttributes, password)


Create a community member from the information that the visitor provided on your community’s self-registration page.

Signature
public Id createUser(Id accountId, Id profileId, Map<Schema.SObjectField,String>
registrationAttributes, String password)

Parameters
accountId
Type: Id
Default account with which the new user is associated. This value comes from the Account field setting on Login and Registration
(L&R) page under Registration Page Configuration.
profileID
Type: Id
Profile to assign the new user. This value comes from the Profile field setting on the L&R page under Registration Page Configuration.
registrationAttributes
Type: Map<Schema.sObjectField,String>
A map of attributes that the registering user entered on the self-registration page. The fields that appear on the self-registration
page come from the User Fields selected on the L&R page when the registration type is Configurable Self-Reg Page.
password
Type: String
The password entered by the user if “Include Password” is selected on the L&R page. (If a password isn’t entered, the handler must
generate one because a password is required to create a user.)

102
Apex Reference Guide ConfigurableSelfRegHandler Interface

Return Value
Type: Id
Returns an identifier for the created User object. Auth.ConfigurableSelfRegHandler inserts a user and then returns the ID
of that user.

ConfigurableSelfRegHandler Example Implementation


This Apex code implements the Auth.ConfigurableSelfRegHandler interface. After the customer or partner fills out the
sign-up page and submits it, the handler is invoked to create an Experience Cloud member with the supplied information. If the registration
process requires email or phone verification, the verification process finishes before the
Auth.ConfigurableSelfRegHandler.createUser is invoked. If verification isn’t required, createUser is invoked
when the customer or partner submits the page.
Verification occurs by email if the admin chose Email as the verification method when setting up the Configurable Self-Reg handler on
the Login & Registration (L&R) page. When a visitor clicks the sign-up link from the login page, Salesforce prompts for an email address
and then sends a one-time password to the specified email address. If the visitor enters the verification code successfully on the verify
page, the user is created and logged in. Likewise, if the admin chose Text Message as the verification method on the L&R page, the visitor
is prompted to enter a phone number. Salesforce sends a challenge (verification code) via SMS to the user. If successful, the user is
created and logged in. Requiring verification before creating a user reduces the number of dummy users cluttering your org.
The Auth.ConfigurableSelfRegHandler class contains logic for generating the user fields required to create a user in case
the user doesn’t supply them. The handler generates default values, ensuring that the values are unique by appending a timestamp.
You can modify the handler to make sure that the email address and phone number of the customer or partner are also unique.
global class AutocreatedConfigSelfReg implements Auth.ConfigurableSelfRegHandler {

private final Long CURRENT_TIME = Datetime.now().getTime();


private final String[] UPPERCASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
private final String[] LOWERCASE_CHARS = 'abcdefghijklmnopqrstuvwxyz'.split('');
private final String[] NUMBER_CHARS = '1234567890'.split('');
private final String[] SPECIAL_CHARS = '!#$%-_=+<>'.split('');

// This method is called once after verification (if any was configured).
// This method should create a user and insert it.
// Password can be null.
// Return null or throw an exception to fail creation.
global Id createUser(Id accountId, Id profileId, Map<SObjectField, String>
registrationAttributes, String password) {
User u = new User();
u.ProfileId = profileId;
for (SObjectField field : registrationAttributes.keySet()) {
String value = registrationAttributes.get(field);
u.put(field, value);
}

u = handleUnsetRequiredFields(u);
generateContact(u, accountId);
if (String.isBlank(password)) {
password = generateRandomPassword();
}
Site.validatePassword(u, password, password);
if (u.contactId == null) {
return Site.createExternalUser(u, accountId, password);

103
Apex Reference Guide ConfigurableSelfRegHandler Interface

}
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = 'UTF-8';
u.timeZoneSidKey = UserInfo.getTimezone().getID();
insert u;
System.setPassword(u.Id, password);
return u.id;
}
// Method to autogenerate a password if one isn't passed in.
// By setting a password for a user, we won't send a
// welcome email to set the password.
private String generateRandomPassword() {
String[] characters = new List<String>(UPPERCASE_CHARS);
characters.addAll(LOWERCASE_CHARS);
characters.addAll(NUMBER_CHARS);
characters.addAll(SPECIAL_CHARS);
String newPassword = '';
Boolean needsUpper = true, needsLower = true, needsNumber = true, needsSpecial =
true;
while (newPassword.length() < 50) {
Integer randomInt = generateRandomInt(characters.size());
String c = characters[randomInt];
if (needsUpper && c.isAllUpperCase()) {
needsUpper = false;
} else if (needsLower && c.isAllLowerCase()) {
needsLower = false;
} else if (needsNumber && c.isNumeric()) {
needsNumber = false;
} else if (needsSpecial && !c.isAlphanumeric()) {
needsSpecial = false;
}
newPassword += c;
}
newPassword = addMissingPasswordRequirements(newPassword, needsLower, needsUpper,
needsNumber, needsSpecial);
return newPassword;
}

private String addMissingPasswordRequirements(String password, Boolean addLowerCase,


Boolean addUpperCase, Boolean addNumber, Boolean addSpecial) {
if (addLowerCase) {
password += LOWERCASE_CHARS[generateRandomInt(LOWERCASE_CHARS.size())];
}
if (addUpperCase) {
password += UPPERCASE_CHARS[generateRandomInt(UPPERCASE_CHARS.size())];
}
if (addNumber) {
password += NUMBER_CHARS[generateRandomInt(NUMBER_CHARS.size())];
}
if (addSpecial) {
password += SPECIAL_CHARS[generateRandomInt(SPECIAL_CHARS.size())];
}
return password;

104
Apex Reference Guide ConfigurableSelfRegHandler Interface

}
// Generates a random number from 0 up to, but not including, max.
private Integer generateRandomInt(Integer max) {
return Math.mod(Math.abs(Crypto.getRandomInteger()), max);
}

// Loops over required fields that were not passed in to


// set to some default value.
private User handleUnsetRequiredFields(User u) {
if (String.isBlank(u.LastName)){
u.LastName = generateLastName();
}
if (String.isBlank(u.Username)) {
u.Username = generateUsername();
}
if (String.isBlank(u.Email)) {
u.Email = generateEmail();
}
if (String.isBlank(u.Alias)) {
u.Alias = generateAlias();
}
if (String.isBlank(u.CommunityNickname)) {
u.CommunityNickname = generateCommunityNickname();
}
return u;
}
// Method to construct a contact for a user.
private void generateContact(User u, Id accountId) {
// Add logic here if you want to build your own
// contact for the use.
}
// Default implementation to try to provide uniqueness.
private String generateAlias() {
String timeString = String.valueOf(CURRENT_TIME);
return timeString.substring(timeString.length() - 8);
}
// Default implementation to try to provide uniqueness.
private String generateLastName() {
return 'ExternalUser' + CURRENT_TIME;
}
// Default implementation to try to provide uniqueness.
private String generateUsername() {
return 'externaluser' + CURRENT_TIME + '@company.com';
}
// Default implementation to try to provide uniqueness.
private String generateEmail() {
return 'externaluser' + CURRENT_TIME + '@company.com';
}
// Default implementation to try to provide uniqueness.
private String generateCommunityNickname() {
return 'ExternalUser' + CURRENT_TIME;
}
}

105
Apex Reference Guide ConfirmUserRegistrationHandler Interface

ConfirmUserRegistrationHandler Interface
Manages single sign-on (SSO) user mappings between Salesforce and a third-party identity provider. Use this interface to confirm user
mappings before updating them.

Namespace
Auth

Usage
When you set up SSO with a third-party identity provider, you create a class that implements a registration handler using the
Auth.RegistrationHandler interface. This class manages the process of creating and updating users. For advanced use cases
that require you to confirm user information during the update process, implement the
Auth.ConfirmUserRegistrationHandler interface in your class. This interface must be implemented in addition to
Auth.RegistrationHandler.
You can use the Auth.ConfirmUserRegistrationHandler interface to ensure that users are mapped correctly between
Salesforce and the third party. When a user who has previously logged in with an authentication provider logs in again, you can confirm
that the incoming user data is consistent with the user's third-party identifier. If not, you can identify which user is supposed to be logged
in.
You can also use the Auth.ConfirmUserRegistrationHandler interface to switch context for users with multiple records.
For example, a user has two records—an admin user and a standard user. When the user logs in, the third-party identity provider confirms
the account used to log in and sends the response to Salesforce via the UserInfo endpoint. You can then use this information to determine
whether to log in the user as an admin or standard user.

IN THIS SECTION:
ConfirmUserRegistrationHandler Methods
ConfirmUserRegistrationHandler Example Implementation

ConfirmUserRegistrationHandler Methods
The following are methods for ConfirmUserRegistrationHandler.

IN THIS SECTION:
confirmUser(userId, tpalId, portalId, userdata)
Returns the ID of the user to be logged in based on their mapping to a third-party identifier. This method is called before calling the
updateUser() method. It's called only if the incoming user has previously logged in and has a third-party account link to a
Salesforce user.

confirmUser(userId, tpalId, portalId, userdata)


Returns the ID of the user to be logged in based on their mapping to a third-party identifier. This method is called before calling the
updateUser() method. It's called only if the incoming user has previously logged in and has a third-party account link to a Salesforce
user.

106
Apex Reference Guide ConfirmUserRegistrationHandler Interface

Signature
public Id confirmUser(Id userId, Id tpalId, Id portalId, Auth.UserData userdata)

Parameters
userId
Type: Id
The ID of the user who is mapped to the third-party identifier via a third-party account link.
tpalId
Type: Id
The third-party account link corresponding to the third-party identifier.
portalId
Type: Id
The portal ID the user is logging in to. If there's no portal configured, this value can be null.
userData
Type: Auth.UserData
Contains user information from the third-party identity provider.

Return Value
Type: Id
The Id of the user to be logged in. If null, login fails.

ConfirmUserRegistrationHandler Example Implementation


This example implements the Auth.ConfirmUserRegistrationHandler interface during the user update process to
confirm that the correct user is logging in based on their email address and last name.
global class StandardUserRegistrationHandler implements Auth.RegistrationHandler,
Auth.ConfirmUserRegistrationHandler {
global User createUser(Id portalId, Auth.UserData data){
User u = new User();
Profile p = [SELECT Id FROM profile WHERE name='Standard User'];
u.username = data.username + '@salesforce.com';
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
String alias = data.username;
if(alias.length() > 8) {
alias = alias.substring(0, 8);
}
u.alias = alias;
u.languagelocalekey = data.attributeMap.get('language');
u.localesidkey = data.locale;
u.emailEncodingKey = 'UTF-8';
u.timeZoneSidKey = 'America/Los_Angeles';
u.profileId = p.Id;
return u;

107
Apex Reference Guide ConnectedAppPlugin Class

global void updateUser(Id userId, Id portalId, Auth.UserData data) {


User u = new User(id=userId);
u.username = data.username + '@salesforce.com';
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
String alias = data.username;
if(alias.length() > 8) {
alias = alias.substring(0, 8);
}
u.alias = alias;
u.languagelocalekey = data.attributeMap.get('language');
u.localesidkey = data.locale;
update(u);
}

global Id confirmUser(Id userId, Id tpalId, Id portalId, Auth.UserData data) {


if (data.email.contains(data.lastName)) { // looks genuine
return userId;
} else { // find the right user
User confirmedUser = [SELECT id FROM user WHERE email=:data.email];
return confirmedUser.Id;
}
}
}

The following example tests the implementation:


@isTest
public class StandardUserRegistrationHandlerTest {
static testMethod void testConfirmUser() {
StandardUserRegistrationHandler handler = new StandardUserRegistrationHandler();
Auth.UserData sampleData = new Auth.UserData('idA', 'firstName', 'A',
'firstName A', '[email protected]', null, 'usernameA', 'en_US', 'facebook',
null, new Map<String, String>{'language' => 'en_US'});
User u = handler.createUser(null, sampleData);
insert(u);
String uid = u.id;

sampleData = new Auth.UserData('idB', 'firstName', 'B',


'firstName B', '[email protected]', null, 'usernameB', 'en_US', 'facebook',
null, new Map<String, String>{}); // note that user B is using userA's email
Id confirmedUserId = handler.confirmUser(uid, '060xx0000004Eh6', null, sampleData);

System.assertEquals(uid, confirmedUserId); // we should see userA's id


}
}

ConnectedAppPlugin Class
Contains methods for extending the behavior of a connected app, for example, customizing how a connected app is invoked depending
on the protocol used. This class gives you more control over the interaction between Salesforce and your connected app.

108
Apex Reference Guide ConnectedAppPlugin Class

Namespace
Auth

Usage
When you create a connected app, you specify general information about the app and settings for OAuth, web apps, mobile apps, and
canvas apps. To customize how the app is invoked, create a connected app handler with this ConnectedAppPlugin Apex class.
For example, use this class to support new authentication protocols or respond to user attributes in a way that benefits a business process.
When you create a connected app handler, you also configure the ConnectedAppPlugin class to run as an execution user. The
execution user authorizes access for the connected app. For example, when you use the authorize method, the execution user
authorizes the connected app to access data.
If you don't specify an execution user, the plug-in runs as an Automated Process User, which is a system user that executes tasks behind
the scenes. Most ConnectedAppPlugin methods require that you specify an execution user, with the exception of the
customAttributes method. For more information, see Create a Custom Connected App Handler.

Example
This example authorizes the connected app user to use the connected app if the context is SAML and the user has reached the quota
tracked in a custom field. It returns the user’s permission set assignments. The example uses Auth.InvocationContext to
modify a SAML assertion before it’s sent to the service provider.
global class ConnectedAppPluginExample extends Auth.ConnectedAppPlugin
{
// Authorize the app if the user has achieved quota tracked in a custom field
global override Boolean authorize(Id userId, Id connectedAppId, Boolean isAdminApproved,
Auth.InvocationContext context)
{
// Create a custom boolean field HasAchievedQuota__c on the user record
// and then uncomment the block below
// User u = [select id, HasAchievedQuota__c from User where id =: userId].get(0);

// return u.HasAchievedQuota__c;

return isAdminApproved;
}

// Call a flow during refresh


global override void refresh(Id userId, Id connectedAppId, Auth.InvocationContext
context)
{
try
{
Map<String, Object> inputVariables = new Map<String, Object>();
inputVariables.put('userId', userId);
inputVariables.put('connectedAppId', connectedAppId);

// Create a custom trigger ready flow and uncomment the block below
// Flow.Interview.MyCustomFlow interview = new
Flow.Interview.MyCustomFlow(inputVariables);
// interview.start();
} catch ( Exception e ) {

109
Apex Reference Guide ConnectedAppPlugin Class

System.debug('FLOW Exception:' + e);


}
}

// Return a user’s permission set assignments


global override Map<String,String> customAttributes(Id userId, Id connectedAppId,
Map<String,String>
formulaDefinedAttributes, Auth.InvocationContext context)
{
List<PermissionSetAssignment> psas = [SELECT id, PermissionSet.Name FROM
PermissionSetAssignment
WHERE PermissionSet.IsOwnedByProfile = false AND (AssigneeId = :userId)];
String permsets = '[';
for (PermissionSetAssignment psa :psas)
{
permsets += psa.PermissionSet.Name + ';';
}
permsets += ']';
formulaDefinedAttributes.put('PermissionSets', permsets);
return formulaDefinedAttributes;
}
}

IN THIS SECTION:
ConnectedAppPlugin Methods

ConnectedAppPlugin Methods
The following are methods for ConnectedAppPlugin.

IN THIS SECTION:
authorize(userId, connectedAppId, isAdminApproved)
Deprecated and available only in API versions 35.0 and 36.0. As of version 37.0, use authorize(userId, connectedAppId,
isAdminApproved, context) instead.
authorize(userId, connectedAppId, isAdminApproved, context)
Authorizes the specified user to access the connected app. If the connected app is set for users to self-authorize, this method isn’t
invoked.
customAttributes(userId, connectedAppId, formulaDefinedAttributes)
Deprecated and available only in API versions 35.0 and 36.0. As of version 37.0, use customAttributes(userId,
connectedAppId, formulaDefinedAttributes, context) instead.
customAttributes(userId, connectedAppId, formulaDefinedAttributes, context)
Sets new attributes for the specified user. When the connected app gets the user’s attributes from the UserInfo endpoint or through
a SAML assertion, use this method to update the attribute values.
modifySAMLResponse(authSession, connectedAppId, samlResponse)
Modifies the XML generated by the Salesforce SAML Identity Provider (IDP) before it’s sent to the service provider.

110
Apex Reference Guide ConnectedAppPlugin Class

refresh(userId, connectedAppId)
Deprecated and available only in API versions 35.0 and 36.0. As of version 37.0, use refresh(userId, connectedAppId,
context) instead.
refresh(userId, connectedAppId, context)
Salesforce calls this method during a refresh token exchange.

authorize(userId, connectedAppId, isAdminApproved)


Deprecated and available only in API versions 35.0 and 36.0. As of version 37.0, use authorize(userId, connectedAppId,
isAdminApproved, context) instead.

Signature
public Boolean authorize(Id userId, Id connectedAppId, Boolean isAdminApproved)

Parameters
userId
Type: Id
The 15-character ID of the user attempting to use the connected app.
connectedAppId
Type: String
The 15-character ID of the connected app.
isAdminApproved
Type: Boolean
The approval state of the specified user when the connected app requires approval.

Return Value
Type: Boolean
If the connected app requires admin approval, a returned value of true indicates that the current user is approved.

authorize(userId, connectedAppId, isAdminApproved, context)


Authorizes the specified user to access the connected app. If the connected app is set for users to self-authorize, this method isn’t invoked.

Signature
public Boolean authorize(Id userId, Id connectedAppId, Boolean isAdminApproved,
Auth.InvocationContext context)

Parameters
userId
Type: Id
The 15-character ID of the user attempting to use the connected app.

111
Apex Reference Guide ConnectedAppPlugin Class

connectedAppId
Type: Id
The 15-character ID of the connected app.
isAdminApproved
Type: Boolean
The approval state of the specified user when the connected app requires approval.
context
Type: InvocationContext
The context in which the connected app is invoked.

Return Value
Type: Boolean
If the connected app requires admin approval, a returned value of true indicates that the user is approved.

Usage
ConnectedAppPlugin runs on behalf of the current user. But the user must have permission to use the connected app for the
plug-in to work. Use this method to authorize the user.

customAttributes(userId, connectedAppId, formulaDefinedAttributes)


Deprecated and available only in API versions 35.0 and 36.0. As of version 37.0, use customAttributes(userId,
connectedAppId, formulaDefinedAttributes, context) instead.

Signature
public Map<String,String> customAttributes(Id userId, Id connectedAppId,
Map<String,String> formulaDefinedAttributes,)

Parameters
userId
Type: Id
The 15-character ID of the user attempting to use the connected app.
connectedAppId
Type: Id
The 15-character ID of the connected app.
formulaDefinedAttributes
Type: Map<String,String>
A map of the new set of attributes from the UserInfo endpoint (OAuth) or from a SAML assertion. For more information, see The
UserInfo Endpoint in the online help.

Return Value
Type: Map<String,String>

112
Apex Reference Guide ConnectedAppPlugin Class

A map of the updated set of attributes.

customAttributes(userId, connectedAppId, formulaDefinedAttributes, context)


Sets new attributes for the specified user. When the connected app gets the user’s attributes from the UserInfo endpoint or through a
SAML assertion, use this method to update the attribute values.

Signature
public Map<String,String> customAttributes(Id userId, Id connectedAppId,
Map<String,String> formulaDefinedAttributes, Auth.InvocationContext context)

Parameters
userId
Type: Id
The 15-character ID of the user attempting to use the connected app.
connectedAppId
Type: Id
The 15-character ID for the connected app.
formulaDefinedAttributes
Type: Map<String,String>
A map of the current set of attributes from the UserInfo endpoint (OAuth) or from a SAML assertion. For more information, see The
UserInfo Endpoint in the online help.
context
Type: InvocationContext
The context in which the connected app is invoked.

Return Value
Type: Map<String,String>
A map of the updated set of attributes.

modifySAMLResponse(authSession, connectedAppId, samlResponse)


Modifies the XML generated by the Salesforce SAML Identity Provider (IDP) before it’s sent to the service provider.

Signature
public dom.XmlNode modifySAMLResponse(Map<String,String> authSession, Id connectedAppId,
dom.XmlNode samlResponse)

Parameters
authSession
Type: Map<String,String>

113
Apex Reference Guide ConnectedAppPlugin Class

The attributes for the authorized user’s session. The map includes the 15-character ID of the authorized user who’s accessing the
connected app.
connectedAppId
Type: Id
The 15-character ID of the connected app.
samlResponse
Type: Dom.XmlNode
Contains the SAML XML response generated by the IDP.

Return Value
Type: Dom.XmlNode
Returns an instance of Dom.XmlNode containing the modified SAML XML response.

Usage
Use this method to modify the XML SAML response to perform an action based on the context of the SAML request before it’s verified,
signed, and sent to the target service provider. This method enables developers to extend the connected app plug-in to meet their
specific needs.
The developer assumes full responsibility for changes made within the connected app plug-in. The plug-in must include validation and
error handling. If the plug-in throws an exception, catch it, log it, and stop the process. Don’t send anything to the target service provider.

refresh(userId, connectedAppId)
Deprecated and available only in API versions 35.0 and 36.0. As of version 37.0, use refresh(userId, connectedAppId,
context) instead.

Signature
public void refresh(Id userId, Id connectedAppId)

Parameters
userId
Type: Id
The 15-character ID of the user requesting the refresh token.
connectedAppId
Type: Id
The 15-character ID of the connected app.

Return Value
Type: void

refresh(userId, connectedAppId, context)


Salesforce calls this method during a refresh token exchange.

114
Apex Reference Guide CustomOneTimePasswordDeliveryHandler Interface

Signature
public void refresh(Id userId, Id connectedAppId, Auth.InvocationContext context)

Parameters
userId
Type: Id
The 15-character ID of the user requesting the refresh token.
connectedAppId
Type: Id
The 15-character ID of the connected app.
context
Type: InvocationContext
The context in which the connected app is invoked.

Return Value
Type: void

CustomOneTimePasswordDeliveryHandler Interface
To use a custom SMS provider to send one-time passwords (OTPs) for Experience Cloud identity verification, create a class that implements
the Auth.CustomOneTimePasswordDeliveryHandler interface.

Namespace
Auth

IN THIS SECTION:
CustomOneTimePasswordDeliveryHandler Methods
CustomOneTimePasswordDeliveryHandler Example Implementation

CustomOneTimePasswordDeliveryHandler Methods
The following are methods for CustomOneTimePasswordDeliveryHandler.

IN THIS SECTION:
sendOneTimePassword(userId, phoneNumber, oneTimePassword, networkId, defaultText, expId)
Calls out to an external SMS messaging provider to send a Salesforce one-time password to an external user for identity verification.
Returns an Auth.CustomOneTimePasswordDeliveryResult indicating whether the provider sent the message.

115
Apex Reference Guide CustomOneTimePasswordDeliveryHandler Interface

sendOneTimePassword(userId, phoneNumber, oneTimePassword, networkId,


defaultText, expId)
Calls out to an external SMS messaging provider to send a Salesforce one-time password to an external user for identity verification.
Returns an Auth.CustomOneTimePasswordDeliveryResult indicating whether the provider sent the message.

Signature
public Auth.CustomOneTimePasswordDeliveryResult sendOneTimePassword(Id userId, String
phoneNumber, String oneTimePassword, String defaultText, Id networkId, String
experienceId)

Parameters
userId
Type: Id
ID of the external user.
phoneNumber
Type: String
The user’s phone number. The phone number isn't necessarily verified by Salesforce.
oneTimePassword
Type: String
The OTP that the user receives.
networkId
Type: String
ID of the Experience Cloud site.
defaultText
Type: Id
The content of the default SMS message that the user receives. You can create custom messages instead of sending the default. For
example, write code to send custom messages based on the Experience Cloud site ID.
expId
Type: String
A custom value that determines what the user experiences.

Return Value
Type: Auth.CustomOneTimePasswordDeliveryResult

CustomOneTimePasswordDeliveryHandler Example Implementation


This example implements the Auth.CustomOneTimePasswordDeliveryHandler interface. For a detailed explanation of
this example, see Example: Custom One-Time Password Delivery Handler in Salesforce Help.
global class TelesignMessaging implements Auth.CustomOneTimePasswordDeliveryHandler{

global Auth.CustomOneTimePasswordDeliveryResult sendOneTimePassword(Id userId, String


phoneNumber, String oneTimePassword,

116
Apex Reference Guide CustomOneTimePasswordDeliveryResult Enum

String defaultText, Id networkId, String experienceId){

//Send the message from Telesign


HttpRequest request = new HttpRequest();
//The commented-out code on the next line isn't necessary if you use named credentials

//request.setEndpoint('https://rest-ww.telesign.com/v1/messaging');
request.setEndpoint('callout:Telesign_SMS_Named');
request.setMethod('POST');
String requestBody = 'is_primary=true&phone_number=' + phoneNumber + '&message='+'Custom
OTP%20'+ oneTimePassword+';
'+defaultText+'&message_type=OTP';

request.setHeader('accept', 'application/json');
request.setHeader('content-type', 'application/x-www-form-urlencoded');
//The commented-out code on the next line isn't necessary if you use named credentials

//request.setHeader('authorization', 'Basic <Base64-encoded Telesign customer ID:API


key>');
request.setBody(requestBody);

HttpResponse response = new Http().send(request);


// Handle the response as needed
return Auth.CustomOneTimePasswordDeliveryResult.SUCCESS;
}
}

CustomOneTimePasswordDeliveryResult Enum
Indicates the status of an attempt to send a one-time password (OTP) to an external user via a custom messaging provider.

Usage
To use this feature, contact Salesforce Customer Support.
This enum specifies the result of the sendOneTimePassword method in an implementation of the
Auth.CustomOneTimePasswordDeliveryHandler interface.

Enum Values
The following are the values of the Auth.CustomOneTimePasswordDeliveryResult enum.

Value Description
COUNTRY_BLOCK Indicates that the user’s phone number has a country code that Salesforce doesn’t
support.

EXCEPTION Indicates that the handler threw an exception.

INVALID_PHONE_NUMBER Indicates that the user’s phone number isn’t valid. For example, it’s in the wrong
format or contains characters that aren’t numbers.

117
Apex Reference Guide ExternalClientAppOauthHandler Class

Value Description
MESSAGE_LIMIT_EXCEEDED Indicates that your Experience Cloud site reached the message limit allowed by
your license.

PROVIDER_ERROR Indicates an error with the custom OTP service.

SUCCESS Indicates that the OTP message was successfully sent to the user.

ExternalClientAppOauthHandler Class
Contains methods for extending the behavior of an external client app. For example, customize how an external client app is invoked
depending on the protocol used. This class gives you more control over the interaction between Salesforce and your external client app.

Namespace
Auth

Usage
When you create an external client app, you specify general information about the app and settings for OAuth. To customize how the
app is invoked, create a external client app handler with the ExternalClientAppOauthHandler Apex class. For example, use
this class to support new authentication protocols or respond to user attributes in a way that benefits the business process.
When you create an external client app handler, you also configure the ExternalClientAppOauthHandler class to run as an
execution user. The execution user authorizes access for the external client app. For example, when you use the authorize method, the
execution user authorizes the external client app to access data.
If you don't specify an execution user, the plug-in runs as an Automated Process User, which is a system user that executes tasks behind
the scenes. Most ExternalClientAppOauthHandler methods require that you specify an execution user, with the exception
of the customAttributes method.

IN THIS SECTION:
ExternalClientAppOauthHandler Methods

ExternalClientAppOauthHandler Methods
The following are methods for ExternalClientAppOauthHandler.

IN THIS SECTION:
authorize(userId, ecAppId, isAdminApproved, context)
Authorizes the specified user to access the external client app. If the external client app is set for users to self-authorize, this method
isn’t invoked.
customAttributes(userId, ecAppId, formulaDefinedAttributes, context)
Sets new attributes for the specified user. When the external client app gets the user’s attributes from the UserInfo endpoint, use
this method to update the attribute values.
refresh(userId, ecAppId, context)
Salesforce calls this method during a refresh token exchange.

118
Apex Reference Guide ExternalClientAppOauthHandler Class

authorize(userId, ecAppId, isAdminApproved, context)


Authorizes the specified user to access the external client app. If the external client app is set for users to self-authorize, this method isn’t
invoked.

Signature
public Boolean authorize(Id userId, Id ecAppId, Boolean isAdminApproved,
Auth.InvocationContext context)

Parameters
userId
Type: Id
The 15-character ID of the user attempting to use the external client app.
ecAppId
Type: Id
The 15-character ID of the external client app.
isAdminApproved
Type: Boolean
The approval state of the specified user when the external client app requires approval.
context
Type: Auth.InvocationContext on page 136
The context in which the external client app is invoked.

Return Value
Type: Boolean
A returned value of true indicates that the user is approved.

customAttributes(userId, ecAppId, formulaDefinedAttributes, context)


Sets new attributes for the specified user. When the external client app gets the user’s attributes from the UserInfo endpoint, use this
method to update the attribute values.

Signature
public Map<String,String> customAttributes(Id userId, Id ecAppId, Map<String,String>
formulaDefinedAttributes, Auth.InvocationContext context)

Parameters
userId
Type: Id
The 15-character ID of the user attempting to use the external client app.
ecAppId
Type: Id

119
Apex Reference Guide GeneratedUserData Class

The 15-character ID for the external client app.


formulaDefinedAttributes
Type: Map<String,String>
A map of the current set of attributes from the UserInfo endpoint (OAuth) or from a SAML assertion. For more information, see The
UserInfo Endpoint in the online help.
context
Type: Auth.InvocationContext
The context in which the external client app is invoked.

Return Value
Type: Map<String,String>
A map of the updated set of attributes.

refresh(userId, ecAppId, context)


Salesforce calls this method during a refresh token exchange.

Signature
public void refresh(Id userId, Id ecAppId, Auth.InvocationContext context)

Parameters
userId
Type: Id
The 15-character ID of the user requesting the refresh token.
ecAppId
Type: Id
The 15-character ID of the external client app.
context
Type: Auth.InvocationContext
The context in which the external client app is invoked.

Return Value
Type: void

GeneratedUserData Class
Stores the output of the Generate User Data invocable action, which you can access in Flow Builder.

Namespace
Auth

120
Apex Reference Guide GeneratedUserData Class

Usage
For single sign-on (SSO) implementations that use the authentication provider framework, you must set up a registration handler that
creates and updates users who log in via the identity provider. In some cases, the identity provider doesn't return enough information
to create a user record in Salesforce. If you use Flow Builder for your registration handler, you can use the Generate User Data invocable
action to help you create complete user records. This action generates placeholder data for all required fields for the User object.
The Auth.GeneratedUserData class stores the output of this action. Use the output as an Apex-defined variable in the flow.
When you create a user, reference specific properties from this class to set values for required fields.
For more information, see these resources in Salesforce Help.
• Flow Core Action: Generate User Data
• Example: Authentication Provider Registration Handler Flow

IN THIS SECTION:
GeneratedUserData Constructors
GeneratedUserData Properties

GeneratedUserData Constructors
The following are constructors for GeneratedUserData.

IN THIS SECTION:
GeneratedUserData(firstName, lastName, email, username, alias, languageLocaleKey, localesIdKey, emailEncodingKey, timeZoneSidKey)
The Generate User Data action in Flow Builder uses this constructor to create an instance of the Auth.GeneratedUserData
class.

GeneratedUserData(firstName, lastName, email, username, alias,


languageLocaleKey, localesIdKey, emailEncodingKey, timeZoneSidKey)
The Generate User Data action in Flow Builder uses this constructor to create an instance of the Auth.GeneratedUserData class.

Signature
public GeneratedUserData(String firstName, String lastName, String email, String
username, String alias, String languageLocaleKey, String localesIdKey, String
emailEncodingKey, String timeZoneSidKey)

Parameters
firstName
Type: String
Stores a generated placeholder value for the user's first name. The generated value is placeholder-first-name.
lastName
Type: String
Stores a generated placeholder value for the user's last name, also known as family name. The generated value is
placeholder-last-name.

121
Apex Reference Guide GeneratedUserData Class

email
Type: String
Stores a generated placeholder value for the user's email address. The generated value is [email protected].
username
Type: String
Stores a generated placeholder value for the user's username. The generated value is placeholder-username<unique
14-character number>@example com, such as placeholder-username17370000000000@example
com.
alias
Type: String
Stores a generated placeholder value for the user's alias. The generated value is alias.
languageLocaleKey
Type: String
Stores the default value for the user's language, such as en_US for English. The default value is the language for the registration
handler execution user. The execution user is specified in the Run As field in the authentication provider definition.
localesIdKey
Type: String
Stores the default value for the user's locale, defined using two-letter International Organization for Standardization (ISO) codes. For
example, en_US indicates English (United States). The default value is the language for the registration handler execution user.
The execution user is specified in the Run As field in the authentication provider definition.
emailEncodingKey
Type: String
Stores the default value for the email encoding type for the user, such as UTF-8. The email encoding type determines how Salesforce
encodes characters in outgoing emails. The default value is the email encoding key for the registration handler execution user. The
execution user is specified in the Run As field in the authentication provider definition.
timeZoneSidKey
Type: String
Stores the default value for the user's time zone, such as GMT-07:00) Pacific Daylight Time
(America/Los_Angeles). The time zone is defined using region and key city according to ISO standards. The default value
is the time zone for the registration handler execution user. The execution user is specified in the Run As field in the authentication
provider definition.

GeneratedUserData Properties
The following are properties for GeneratedUserData.

IN THIS SECTION:
alias
Stores a generated placeholder value for the user's alias. The placeholder value is alias.
email
Stores a generated placeholder value for the user's email address. The placeholder value is
[email protected].

122
Apex Reference Guide GeneratedUserData Class

emailEncodingKey
Stores the default value for the email encoding type for the user, such as UTF-8. The email encoding type determines how Salesforce
encodes characters in outgoing emails. The default value is the email encoding key for the execution user specified in the Run As
field in the authentication provider definition.
firstName
Stores a generated placeholder value for the user's first name. The placeholder value is placeholder-first-name.
languageLocaleKey
Stores the default value for the user's language, such as en_US for English. The default value is the language for the registration
handler execution user. The execution user is specified in the Run As field in the authentication provider definition.
lastName
Stores a generated placeholder value for the user's last name, also known as family name. The placeholder value is
placeholder-last-name.
localesIdKey
Stores the default value for the user's locale, defined using two-letter International Organization for Standardization (ISO) codes. For
example, en_US indicates English (United States). The default value is the language for the registration handler execution user.
The execution user is specified in the Run As field in the authentication provider definition.
timeZoneSidKey
Stores the default value for the user's time zone, such as (GMT-07:00) Pacific Daylight Time
(America/Los_Angeles). The time zone is defined using region and key city according to ISO standards. The default value
is the time zone for the registration handler execution user. The execution user is specified in the Run As field in the authentication
provider definition.
username
Stores a generated placeholder value for the user's username. The placeholder value is placeholder-username<unique
14-character number>@example com, such as placeholder-username17370000000000@example
com.

alias
Stores a generated placeholder value for the user's alias. The placeholder value is alias.

Signature
public String alias {get; set;}

Property Value
Type: String

email
Stores a generated placeholder value for the user's email address. The placeholder value is [email protected].

Signature
public String email {get; set;}

123
Apex Reference Guide GeneratedUserData Class

Property Value
Type: String

emailEncodingKey
Stores the default value for the email encoding type for the user, such as UTF-8. The email encoding type determines how Salesforce
encodes characters in outgoing emails. The default value is the email encoding key for the execution user specified in the Run As field
in the authentication provider definition.

Signature
public String emailEncodingKey {get; set;}

Property Value
Type: String

firstName
Stores a generated placeholder value for the user's first name. The placeholder value is placeholder-first-name.

Signature
public String firstName {get; set;}

Property Value
Type: String

languageLocaleKey
Stores the default value for the user's language, such as en_US for English. The default value is the language for the registration handler
execution user. The execution user is specified in the Run As field in the authentication provider definition.

Signature
public String languageLocaleKey {get; set;}

Property Value
Type: String

lastName
Stores a generated placeholder value for the user's last name, also known as family name. The placeholder value is
placeholder-last-name.

Signature
public String lastName {get; set;}

124
Apex Reference Guide HeadlessSelfRegistrationHandler Interface

Property Value
Type: String

localesIdKey
Stores the default value for the user's locale, defined using two-letter International Organization for Standardization (ISO) codes. For
example, en_US indicates English (United States). The default value is the language for the registration handler execution user. The
execution user is specified in the Run As field in the authentication provider definition.

Signature
public String localesIdKey {get; set;}

Property Value
Type: String

timeZoneSidKey
Stores the default value for the user's time zone, such as (GMT-07:00) Pacific Daylight Time
(America/Los_Angeles). The time zone is defined using region and key city according to ISO standards. The default value is
the time zone for the registration handler execution user. The execution user is specified in the Run As field in the authentication provider
definition.

Signature
public String timeZoneSidKey {get; set;}

Property Value
Type: String

username
Stores a generated placeholder value for the user's username. The placeholder value is placeholder-username<unique
14-character number>@example com, such as placeholder-username17370000000000@example com.

Signature
public String username {get; set;}

Property Value
Type: String

HeadlessSelfRegistrationHandler Interface
Creates customer and partner users during the Headless Registration Flow.

125
Apex Reference Guide HeadlessSelfRegistrationHandler Interface

Namespace
Auth

Usage
The Headless Registration Flow allows you to control user registration experience in a third-party app while using Salesforce to authenticate
users and manage their data access. When you set up this flow, add users in the class that is implementing the
Auth.HeadlessSelfRegistrationHandler interface. This class runs after the user verifies their identity. For a detailed
explanation of headless registration, see Headless Registration Flow for Private Clients or Headless Registration Flow for Public Clients,
depending on your app type.

IN THIS SECTION:
HeadlessSelfRegistrationHandler Methods
The following are methods for HeadlessSelfRegistrationHandler.
HeadlessSelfRegistrationHandler Example Implementation
This example class implements the Auth.HeadlessSelfRegistrationHandler interface to create a user. It finds or
creates an account to store the new user and creates a contact to associate with the account. It then creates the user based on
information that your client sends to Headless Registration API.

HeadlessSelfRegistrationHandler Methods
The following are methods for HeadlessSelfRegistrationHandler.

IN THIS SECTION:
createUser(profileId, data, customUserDataMap, experienceId, password)
Returns a User object using information submitted by your off-platform app to Headless Registration API. The User object can be a
new user that hasn’t been inserted in your org’s database, or it can represent an existing user record. If it’s a new User object, Salesforce
inserts the user record for you.

createUser(profileId, data, customUserDataMap, experienceId, password)


Returns a User object using information submitted by your off-platform app to Headless Registration API. The User object can be a new
user that hasn’t been inserted in your org’s database, or it can represent an existing user record. If it’s a new User object, Salesforce inserts
the user record for you.

Signature
public User createUser(Id profileId, Auth.UserData data, String customUserDataMap,
String experienceId, String password)

Parameters
profileId
Type: Id
The ID of the profile that is assigned to new users.

126
Apex Reference Guide HeadlessSelfRegistrationHandler Interface

data
Type: Auth.UserData
A class that stores information about the user, such as their name and locale.
customUserDataMap
Type: String
A string representation of a JSON object containing custom user information passed in during registration. We recommend that you
deserialize this string into the equivalent Apex class structure. Determine what custom information to collect when you build your
app’s registration experience.
experienceId
Type: String
A custom value that determines what the end user experiences.
password
Type: String
The user password.

Return Value
Type: User

HeadlessSelfRegistrationHandler Example Implementation


This example class implements the Auth.HeadlessSelfRegistrationHandler interface to create a user. It finds or creates
an account to store the new user and creates a contact to associate with the account. It then creates the user based on information that
your client sends to Headless Registration API.
global class ExampleHeadlessReg implements Auth.HeadlessSelfRegistrationHandler {
// TO DO: Update this constant with the actual value for your use case
private static final String CUSTOMER_ACCOUNT = 'My Account';

/*
* Retrieve an existing account or create a new one if it doesn't exist
*
* @param accountName - The name of the Account to find or create
* @return Account - The found or newly created Account record
*/
private Account findOrCreateAccount(String accountName) {
List<Account> existingAccounts = [SELECT Id FROM Account WHERE Name=:accountName
LIMIT 1];

if (existingAccounts.isEmpty()) {
Account newAccount = new Account(Name = accountName);
insert(newAccount);
return newAccount;
}

return existingAccounts[0];
}

/*

127
Apex Reference Guide HeadlessSelfRegistrationHandler Interface

* Create a contact and associate it with an account


*
* @param account - The Account object to associate the contact with
* @param user - The User object containing the first and last name for the contact
* @return Contact - The newly created contact record
*/
private Contact createContact(Account account, User user) {
Contact c = new Contact();
c.accountId = account.Id;
c.firstName = user.firstName;
c.lastName = user.lastName;

insert(c);

return c;
}

//TO DO: Implement any additional password validation that you want in this method.
// In this example, the password was already checked to ensure that it complies with
the org’s password policy,
// and the password, if present, is set automatically for the new user when they are
returned from the createUserMethod.
private Boolean isPasswordValid(String password) {
return true;
}

global User createUser(Id profileId, Auth.UserData data, String customUserDataMap,


String experienceId, String password){
if (!isPasswordValid(password)) {
return null;
}

User u = new User();


u.Username = data.username;
u.ProfileId = profileId;
u.Email = data.email;
u.LastName = data.lastName;
u.FirstName = data.firstName;
String alias = data.username;
// Alias must be 8 characters or less
if (alias.length() > 8) {
alias = alias.substring(0, 8);
}
u.Alias = alias;
Account a = findOrCreateAccount(CUSTOMER_ACCOUNT);
Contact c = createContact(a, u);
u.ContactId = c.Id;
u.LanguageLocaleKey = UserInfo.getLocale();
u.LocaleSidKey = UserInfo.getLocale();
u.EmailEncodingKey = 'UTF-8';
u.TimeZoneSidKey = UserInfo.getTimezone().getID();

return u;

128
Apex Reference Guide HeadlessUserDiscoveryHandler Interface

}
}

HeadlessUserDiscoveryHandler Interface
Use this interface to create a headless user discovery handler that you implement during headless login, passwordless login, and forgot
password flows.

Namespace
Auth

Usage
Develop headless authorization flows where users log in to an off-platform app with an identifier other than their username, such as an
email address, phone number, or order number. When a user enters the identifier in your headless app, your app sends the identifying
information to a Salesforce endpoint. Salesforce then passes the identifying information to your implementation of the
Auth.HeadlessUserDiscoveryHandler interface. The handler finds the user's account and its associated email address or
phone number.
Headless user discovery supports these use cases.
• Headless login with any identifier and a password. For example, a user goes to your headless app and enters their order number and
password to log in.
• Headless login with any identifier and a one-time password (OTP). For example, a user goes to your app and enters just their order
number. Your Apex handler finds the user's account based on the order number. Salesforce sends an OTP to the verified email
address that's associated with the account. To log in, the user enters the OTP.
• Headless password reset with any identifier. For example a user goes to your app and enters their phone number. Your Apex handler
finds the user account and Salesforce sends an OTP to the user's verified phone number. To verify their identity for password reset,
the user enters the OTP and can then set a new password.
Headless user discovery is supported for Headless Identity API flows and OAuth 2.0 for First-Party Applications flows. For more information
about supported flows and implementation details, see Headless Login Without a Username.

IN THIS SECTION:
HeadlessUserDiscoveryHandler Methods
HeadlessUserDiscoveryHandler Example Implementation

HeadlessUserDiscoveryHandler Methods
The following are methods for HeadlessUserDiscoveryHandler.

IN THIS SECTION:
discoverUserFromLoginHint(networkId, loginHint, verificationAction, customDataJson, requestAttributes)
Finds a user's Salesforce account based on user information, such as their email address, phone number, or other data, that's passed
to a Salesforce endpoint during headless login, passwordless login, and forgot password flows.

129
Apex Reference Guide HeadlessUserDiscoveryHandler Interface

discoverUserFromLoginHint(networkId, loginHint, verificationAction,


customDataJson, requestAttributes)
Finds a user's Salesforce account based on user information, such as their email address, phone number, or other data, that's passed to
a Salesforce endpoint during headless login, passwordless login, and forgot password flows.

Signature
public Auth.HeadlessUserDiscoveryResponse discoverUserFromLoginHint(Id networkId, String
loginHint, Auth.VerificationAction verificationAction, String customDataJson,
Map<String,String> requestAttributes)

Parameters
networkId
Type: Id
The ID of the Experience Cloud site where your headless app sends requests.
loginHint
Type: String
Information about the user that Salesforce can use to find their associated account, such as their email address or phone number.
verificationAction
Type: Auth.VerificationAction on page 213
The verification method that's used to log the user in, either email or SMS.
customDataJson
Type: String
Custom user data, such as first name, that you collect when the user logs in to your headless app.
requestAtttibutes
Type: Map<String,String>
Information about the login request that's based on the user’s browser state when accessing the login page. requestAttributes
passes in the CommunityUrl, IpAddress, UserAgent, Platform, Application, City, Country, and Subdivision values. The City, Country,
and Subdivision values come from IP geolocation.

Return Value
Type: Auth.HeadlessUserDiscoveryResponse on page 133
If the handler finds a user, it returns a user ID. If not, it returns an error message.

HeadlessUserDiscoveryHandler Example Implementation


Here's an example implementation of the Auth.HeadlessUserDiscoveryHandler interface. This example supports login
with email and login with SMS.
The discoverUserFromLoginHint method uses custom logic to search for a user account with a verified email address or
phone number that matches the data passed in the login hint. As a security best practice, Salesforce always recommends writing code
to determine if the user's email address or phone number is verified.
For users logging in with email, the custom logic first checks whether the email address passed in the login hint is in a valid format. Then,
to look for a verified Salesforce email address that matches the email address passed in the login hint, it queries the TwoFactorMethodsInfo

130
Apex Reference Guide HeadlessUserDiscoveryHandler Interface

object. If successful, it returns an instance of Auth.HeadlessUserDiscoveryResponse with the user ID. If something goes
wrong, it returns an instance of Auth.HeadlessUserDiscoveryResponse with a custom error message. In this example, it
returns error messages when the email address format isn't valid, the email address isn't verified, there's no user with that email address,
or there are multiple users with that email address.
For users logging in with SMS, the custom logic is similar. It checks whether the phone number passed in the login hint is in a valid
format. Then, it looks for a verified Salesforce phone number that matches the phone number passed in the login hint. If successful, it
returns an instance of Auth.HeadlessUserDiscoveryResponse with the user ID, and if not, it returns custom error messages.
/*
* Headless User Discovery Handler
*/
global class MyHeadlessUserDiscoveryHandler implements Auth.HeadlessUserDiscoveryHandler
{

/*
* This method handles the logic to determine the user account based on the loginHint and
verificationMethod
*/
global Auth.HeadlessUserDiscoveryResponse discoverUserFromLoginHint(Id networkId, String
loginHint,
Auth.VerificationAction verificationAction, String customDataJson,
Map<String,String>requestAttributes) {
if (verificationAction == Auth.VerificationAction.EMAIL) {
return doLookupByVerifiedEmail(loginHint, verificationAction);
} else if (verificationAction == Auth.VerificationAction.SMS) {
return doLookupByVerifiedMobile(loginHint, verificationAction);
} else {
return new Auth.HeadlessUserDiscoveryResponse(null, 'Unsupported
Auth.VerificationAction');
}
}

private Auth.HeadlessUserDiscoveryResponse doLookupByVerifiedEmail(String loginHint,


Auth.VerificationAction verificationAction) {
if (String.isBlank(loginHint) || !isValidEmail(loginHint)) {
return new Auth.HeadlessUserDiscoveryResponse(null, 'Invalid email sent as loginHint:
' + loginHint);
}
// Search for an user account by email
List<User> users = [SELECT Id FROM User WHERE Email = :loginHint AND IsActive = TRUE];

if (!users.isEmpty() && users.size() == 1) {


Id userId = users[0].Id;
// Check if the user has a verified email
List<TwoFactorMethodsInfo> verifiedInfo = [SELECT HasUserVerifiedEmailAddress FROM
TwoFactorMethodsInfo WHERE UserId = :userId];
if (!verifiedInfo.isEmpty() && verifiedInfo[0].HasUserVerifiedEmailAddress == true)
{
// Prepare and return HeadlessUserDiscoveryResponse with userId
return new Auth.HeadlessUserDiscoveryResponse(new Set<Id>{userId}, null);
} else {
// Return HeadlessUserDiscoveryResponse with error message
return new Auth.HeadlessUserDiscoveryResponse(null, 'Email ' + loginHint + ' not

131
Apex Reference Guide HeadlessUserDiscoveryHandler Interface

verified for the given user account');


}
} else {
if (users.isEmpty()) {
return new Auth.HeadlessUserDiscoveryResponse(null, 'No user identified for the
email: ' + loginHint);
} else {
return new Auth.HeadlessUserDiscoveryResponse(null, 'Multiple users identified for
the email: ' + loginHint);
}
}
}

private Auth.HeadlessUserDiscoveryResponse doLookupByVerifiedMobile(String loginHint,


Auth.VerificationAction verificationAction) {
String formattedSms = !String.isBlank(loginHint) ? getFormattedSms(loginHint) : null;

if (String.isBlank(formattedSms)) {
return new Auth.HeadlessUserDiscoveryResponse(null, 'Invalid phone number sent as
loginHint: ' + loginHint);
}
// Search for an user account by phone
List<User> users = [SELECT Id FROM User WHERE MobilePhone = :loginHint AND IsActive =
TRUE];
if (!users.isEmpty() && users.size() == 1) {
Id userId = users[0].Id;
// Check if the user has a verified phone
List<TwoFactorMethodsInfo> verifiedInfo = [SELECT HasUserVerifiedMobileNumber FROM
TwoFactorMethodsInfo WHERE UserId = :userId];
if (!verifiedInfo.isEmpty() && verifiedInfo[0].HasUserVerifiedMobileNumber == true)
{
// Prepare and return HeadlessUserDiscoveryResponse with userId
return new Auth.HeadlessUserDiscoveryResponse(new Set<Id>{userId}, null);
} else {
// Return HeadlessUserDiscoveryResponse with error message
return new Auth.HeadlessUserDiscoveryResponse(null, ' ' + loginHint + ' not verified
for the given user account');
}
} else {
if (users.isEmpty()) {
return new Auth.HeadlessUserDiscoveryResponse(null, 'No user identified for the
phone number: ' + loginHint);
} else {
return new Auth.HeadlessUserDiscoveryResponse(null, 'Multiple users identified for
the phone number: ' + loginHint);
}
}
}

private boolean isValidEmail(String identifier) {


String emailRegex =
'^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
// source: http://www.regular-expressions.info/email.html
Pattern EmailPattern = Pattern.compile(emailRegex);

132
Apex Reference Guide HeadlessUserDiscoveryResponse Class

Matcher EmailMatcher = EmailPattern.matcher(identifier);


if (EmailMatcher.matches()) { return true; }
else { return false; }
}

private String getFormattedSms(String identifier) {


// Accept SMS input formats with 1 or 2 digits country code, 3 digits area code and 7
digits number
// You can customize the SMS regex to allow different formats
String smsRegex = '^(\\+?\\d{1,2}?[\\s-])?(\\(?\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{4})$';

Pattern smsPattern = Pattern.compile(smsRegex);


Matcher smsMatcher = SmsPattern.matcher(identifier);
if (smsMatcher.matches()) {
try {
// Format user input into the verified SMS format '+xx xxxxxxxxxx' before DB lookup

// Append US country code +1 by default if no country code is provided


String countryCode = smsMatcher.group(1) == null ? '+1' : smsMatcher.group(1);
return System.UserManagement.formatPhoneNumber(countryCode, smsMatcher.group(2));

} catch(System.InvalidParameterValueException e) {
return null;
}
} else { return null; }
}

HeadlessUserDiscoveryResponse Class
Contains methods to describe the result of headless user discovery using a handler that implements the
Auth.HeadlessUserDiscoveryHandler interface during headless login, passwordless login, and forgot password flows.

Namespace
Auth

Usage
Use this class to return a user ID if headless user discovery was successful, or return custom error messages if not.

IN THIS SECTION:
HeadlessUserDiscoveryResponse Constructors
HeadlessUserDiscoveryResponse Properties

HeadlessUserDiscoveryResponse Constructors
The following are constructors for HeadlessUserDiscoveryResponse.

133
Apex Reference Guide HeadlessUserDiscoveryResponse Class

IN THIS SECTION:
HeadlessUserDiscoveryResponse(userIds, customErrorMessage)
Creates an instance of the Auth.HeadlessUserDiscoveryResponse class to describe the result of headless user discovery
based on data passed into the login_hint during headless login, passwordless login, and forgot password flows.

HeadlessUserDiscoveryResponse(userIds, customErrorMessage)
Creates an instance of the Auth.HeadlessUserDiscoveryResponse class to describe the result of headless user discovery
based on data passed into the login_hint during headless login, passwordless login, and forgot password flows.

Signature
public HeadlessUserDiscoveryResponse(Set<Id> userIds, String customErrorMessage)

Parameters
userIds
Type: Set<Id>
The user ID that's associated with the data passed in the login_hint parameter. If there are multiple users associated with the
data, it can return multiple IDs, but headless user discovery fails.
customErrorMessage
Type: String
A custom error message that's returned if headless user discovery fails.

HeadlessUserDiscoveryResponse Properties
The following are properties for HeadlessUserDiscoveryResponse.

IN THIS SECTION:
customErrorMessage
A custom error message that's returned if headless user discovery fails. For example, write custom logic in your headless user discovery
handler to see if the user's email address is verified. Then return a custom error message for when it isn't verified.
userIds
The user ID for the external user that's associated with the data passed into the login_hint parameter. If there are multiple
users associated with the data, it can return multiple IDs, but headless user discovery fails.

customErrorMessage
A custom error message that's returned if headless user discovery fails. For example, write custom logic in your headless user discovery
handler to see if the user's email address is verified. Then return a custom error message for when it isn't verified.

Signature
public String customErrorMessage {get; set;}

134
Apex Reference Guide HttpCalloutMockUtil Class

Property Value
Type: String

userIds
The user ID for the external user that's associated with the data passed into the login_hint parameter. If there are multiple users
associated with the data, it can return multiple IDs, but headless user discovery fails.

Signature
public Set<Id> userIds {get; set;}

Property Value
Type: Set<Id>

HttpCalloutMockUtil Class
Contains a method to send fake HTTP callouts for classes in the Auth namespace.

Namespace
Auth

Usage
Use the setHttpMock method in this class to test HTTP callouts when implementing the Auth.JWTBearerTokenExchange
and Auth.JWTUtil classes.
For the Auth.JWTBearerTokenExchange class, mock callouts to the OAuth token endpoint when using the
JWTBearerTokenExchange method.
For the Auth.JWTUtil class, mock callouts to the identity provider’s JSON Web Key Set (JWKS) endpoint when using the
validateJWTWithKeysEndpoint method.
For more information on mocking HTTP callouts, see Testing HTTP Callouts by Implementing the HttpCalloutMock Interface.

IN THIS SECTION:
HttpCalloutMockUtil Methods

HttpCalloutMockUtil Methods
The following are methods for HttpCalloutMockUtil.

IN THIS SECTION:
setHttpMock(mock)
Mocks an HTTP callout using an implementation of the System.HttpCalloutMock interface.

135
Apex Reference Guide IntegratingAppType Enum

setHttpMock(mock)
Mocks an HTTP callout using an implementation of the System.HttpCalloutMock interface.

Signature
public static void setHttpMock(System.HttpCalloutMock mock)

Parameters
mock
Type: System.HttpCalloutMock
A class that implements the System.HttpCalloutMock interface to return a fake HTTP response for a given request to the OAuth token
endpoint or a JWKS endpoint on an external identity provider, depending on your use case.

Return Value
Type: void

IntegratingAppType Enum
Specifies whether you’re integrating your app as a connected app or as an external client app in methods used in your customized Apex
token exchange handler, which extends the Auth.Oauth2TokenExchangeHandler class.

Usage
See Token Exchange Handler Validation and Subject Mapping.

Enum Values
The following are the values of the Auth.IntegratingAppType enum.

Value Description
CA Indicates a Salesforce connected app.

ECA Indicates a Salesforce external client app.

InvocationContext Enum
The context in which the connected app is invoked, such as the protocol flow used and the token type issued, if any. Developers can
use the context information to write code that is unique to the type of invocation.

Enum Values
The following are the values of the Auth.InvocationContext enum.

136
Apex Reference Guide JsonValueOutput Class

Value Description
ASSET_TOKEN Reserved for future use.

OAUTH1 Context used when authentication is through an OAuth 1.0A flow.

OAUTH2_JWT_BEARER_TOKEN Context used when authentication is through a JSON-based Web Token (JWT)
bearer token flow.

OAUTH2_SAML_ASSERTION Context used when authentication is through an OAuth 2.0 SAML assertion flow.

OAUTH2_SAML_BEARER_ASSERTION Context used when authentication is through an OAuth 2.0 SAML bearer assertion
flow.

OAUTH2_USERNAME_PASSWORD Context used when authentication is through an OAuth 2.0 username-password


flow.

OAUTH2_USER_AGENT_ID_TOKEN Context used when issuing an ID token through an OAuth 2.0 user-agent flow.

OAUTH2_USER_AGENT_TOKEN Context used when authentication is through an OAuth 2.0 user agent flow.

OAUTH2_WEB_SERVER Context used when authentication is through a web server authentication flow.

OPENIDCONNECT Context used when authentication is through an OpenID Connect authentication


flow.

REFRESH_TOKEN Context used when renewing tokens issued by a web server or user-agent flow.

SAML_ASSERTION Context used when authentication is through a SAML assertion flow.

UNKNOWN Context is unknown.

USERID_ENDPOINT Context used when issuing an access token through a UserInfo endpoint.

SEE ALSO:
Salesforce Help: Authenticating Apps with OAuth

JsonValueOutput Class
Stores the output of the Get User Data from JSON String invocable action, which you can access in Flow Builder..

Namespace
Auth

Usage
To implement single sign-on (SSO) with the authentication provider framework, you must set up a registration handler that creates and
updates users who log in via the identity provider. To create and update users, the registration handler uses user information from the
identity provider. Some identity providers return user information in an ID token or in a user info response. The ID token and user info
response are formatted as JSON objects that can be deeply nested, which makes them difficult to parse. If you use Flow Builder for your
registration handler, the Get User Data from JSON String invocable action makes it easier to get user information from these JSON objects.
Use this action to retrieve a specific attribute value from the ID token or user info response.

137
Apex Reference Guide JsonValueOutput Class

The action takes two input values. The first input value is the ID token or user info response from the identity provider. This input value
must be a JSON object that has been serialized into a string. The second input value is the JSON key that corresponds to the attribute
value that you want to retrieve. Using these input values, the action parses the ID token or user info response. It outputs the attribute
value and stores it in an instance of the Auth.JsonValueOutput class. Each instance of this class stores a single attribute. The
attribute is stored in a property that corresponds to its data type in the identity provider response, such as integerValue for an
integer.
For more information about this action and how you can use it, see these resources in Salesforce Help.
• Flow Core Action: Get User Data from JSON String
• Example: Authentication Provider Registration Handler Flow

IN THIS SECTION:
JsonValueOutput Constructors
JsonValueOutput Properties

JsonValueOutput Constructors
The following are constructors for JsonValueOutput.

IN THIS SECTION:
JsonValueOutput(stringValue, booleanValue, integerValue, doubleValue, jsonStringValue, jsonArrayValue)
The Get User Data from JSON String action in Flow Builder uses this constructor to create an instance of the
Auth.JsonValueOutput class.

JsonValueOutput(stringValue, booleanValue, integerValue, doubleValue,


jsonStringValue, jsonArrayValue)
The Get User Data from JSON String action in Flow Builder uses this constructor to create an instance of the Auth.JsonValueOutput
class.

Signature
public JsonValueOutput(String stringValue, Boolean booleanValue, Integer integerValue,
Double doubleValue, String jsonStringValue, String jsonArrayValue)

Parameters
stringValue
Type: String
If the attribute returned by the action is a string, it's stored in this parameter.
booleanValue
Type: Boolean
If the attribute returned by the action is a boolean value, it's stored in this parameter.
integerValue
Type: Integer

138
Apex Reference Guide JsonValueOutput Class

If the attribute returned by the action is an integer value, it's stored in this parameter.
doubleValue
Type: Double
If the attribute returned by the action is a Double value, it's stored in this parameter.
jsonStringValue
Type: String
If the attribute returned by the action is a JSON string, it's stored in this parameter.
jsonArrayValue
Type: String
If the attribute returned by the action is a JSON array, it's formatted as a string and stored in this parameter.

JsonValueOutput Properties
The following are properties for JsonValueOutput.

IN THIS SECTION:
booleanValue
If the attribute returned by the action is a boolean value, it's stored in this property.
doubleValue
If the attribute returned by the action is a Double value, it's stored in this property.
integerValue
If the attribute returned by the action is an integer, it's stored in this property.
jsonArrayValue
If the attribute returned by the action is a JSON array, it's formatted as a string and stored in this property.
jsonStringValue
If the attribute returned by the action is a JSON string, it's stored in this property.
stringValue
If the attribute returned by the action is a string, it's stored in this property.

booleanValue
If the attribute returned by the action is a boolean value, it's stored in this property.

Signature
public Boolean booleanValue {get; set;}

Property Value
Type: Boolean

doubleValue
If the attribute returned by the action is a Double value, it's stored in this property.

139
Apex Reference Guide JsonValueOutput Class

Signature
public Double doubleValue {get; set;}

Property Value
Type: Double

integerValue
If the attribute returned by the action is an integer, it's stored in this property.

Signature
public Integer integerValue {get; set;}

Property Value
Type: Integer

jsonArrayValue
If the attribute returned by the action is a JSON array, it's formatted as a string and stored in this property.

Signature
public String jsonArrayValue {get; set;}

Property Value
Type: String

jsonStringValue
If the attribute returned by the action is a JSON string, it's stored in this property.

Signature
public String jsonStringValue {get; set;}

Property Value
Type: String

stringValue
If the attribute returned by the action is a string, it's stored in this property.

Signature
public String stringValue {get; set;}

140
Apex Reference Guide JWS Class

Property Value
Type: String

JWS Class
Contains methods that apply a digital signature to a JSON Web Token (JWT), using a JSON Web Signature (JWS) data structure. This class
creates the signed JWT bearer token, which can be used to request an OAuth access token in the OAuth 2.0 JWT bearer token flow.

Namespace
Auth

Usage
Use the methods in this class to sign the JWT bearer token with the X509 certificate.

IN THIS SECTION:
JWS Constructors
JWS Methods

JWS Constructors
The following are constructors for JWS.

IN THIS SECTION:
JWS(jwt, certDevName)
Creates an instance of the JWS class using the specified Auth.JWT payload and the certificate used for signing the JWT bearer
token.
JWS(payload, certDevName)
Creates an instance of the JWS class using the specified payload and certificate used for signing the JWT bearer token.

JWS(jwt, certDevName)
Creates an instance of the JWS class using the specified Auth.JWT payload and the certificate used for signing the JWT bearer token.

Signature
public JWS(Auth.JWT jwt, String certDevName)

Parameters
jwt
Type: Auth.JWT
The Base64-encoded JSON Claims Set in the JWT bearer token generated by Auth.JWT.

141
Apex Reference Guide JWS Class

certDevName
Type: String
The Unique Name for a certificate stored in the Salesforce org’s Certificate and Key Management page to use for signing the
JWT bearer token.

Usage
Calls the toJSONString() method in Auth.JWT and sets the resulting string as the payload of the JWT bearer token. Alternatively,
you can specify the payload directly using JWS(payload, certDevName).

JWS(payload, certDevName)
Creates an instance of the JWS class using the specified payload and certificate used for signing the JWT bearer token.

Signature
public JWS(String payload, String certDevName)

Parameters
payload
Type: String
The Base64-encoded JSON Claims Set in the JWT bearer token.
certDevName
Type: String
The Unique Name for a certificate stored in the Salesforce org’s Certificate and Key Management page to use for signing the
JWT bearer token.

Usage
Sets the payload string as the payload of the JWT bearer token. Alternatively, if you generate the payload using Auth.JWT, you
can use JWS(jwt, certDevName) instead.

JWS Methods
The following are methods for JWS. All are instance methods.

IN THIS SECTION:
clone()
Makes a duplicate copy of the JWS object.
getCompactSerialization()
Returns the compact serialization representation of the JWS as a concatenated string, with the encoded JWS header, encoded JWS
payload, and encoded JWS signature strings separated by period ('.') characters.

clone()
Makes a duplicate copy of the JWS object.

142
Apex Reference Guide JWT Class

Signature
public Object clone()

Return Value
Type: JWS

getCompactSerialization()
Returns the compact serialization representation of the JWS as a concatenated string, with the encoded JWS header, encoded JWS
payload, and encoded JWS signature strings separated by period ('.') characters.

Signature
public String getCompactSerialization()

Return Value
Type: String

JWT Class
Generates the JSON Claims Set in a JSON Web Token (JWT). The resulting Base64-encoded payload can be passed as an argument to
create an instance of the Auth.JWS class.

Namespace
Auth

Usage
Use the methods in this class to generate the payload in a JWT bearer token for the OAuth 2.0 JWT bearer token flow. For more information
and a full code sample, see JWTBearerTokenExchange Class.

IN THIS SECTION:
JWT Methods

JWT Methods
The following are methods for JWT. All are instance methods.

IN THIS SECTION:
clone()
Makes a duplicate copy of the JWT object.
getAdditionalClaims()
Returns a map of additional claims in the JWT, where the key string contains the name of the claim, and the value contains the value
of the claim.

143
Apex Reference Guide JWT Class

getAud()
Returns the audience (aud) claim that identifies the intended recipients of the JWT.
getIss()
Returns the issuer (iss) claim that identifies the issuer of the JWT.
getNbfClockSkew()
Returns the not before (nbf) claim that identifies the time before which the JWT must not be accepted for processing, while allowing
some leeway for clock skew. This method returns a NoAccess exception for JWTs generated using methods in the
Auth.JWTUtil class. To return the nbf claim for these JWTs, use the getAdditionalClaims method instead.
getSub()
Returns the subject (sub) claim that identifies the current user of the JWT.
getValidityLength()
Returns the length of time (in seconds) that the JWT is valid, which affects the expiration (exp) claim. This method returns a
NoAccess exception for JWTs generated using methods in the Auth.JWTUtil class. To return the validity length for these
JWTs, use the getAdditionalClaims method instead.
setAdditionalClaims(additionalClaims)
Sets the additional claims in the JWT. Returned by the getAdditionalClaims method.
setAud(aud)
Sets the audience (aud) claim in the JWT. Returned by the getAud method.
setIss(iss)
Sets the issuer (iss) claim in the JWT. Returned by the getIss method.
setNbfClockSkew(nbfClockSkew)
Sets the not before (nbf) claim in the JWT. Returned by the getNbfClockSkew method. This method returns a NoAccess
exception for JWTs generated using methods in the Auth.JWTUtil class. For these JWTs, the incoming JWT determines the
nbf claim.
setSub(sub)
Sets the subject (sub) claim in the JWT. Returned by the getSub method.
setValidityLength(validityLength)
Sets the length of time (in seconds) that the JWT is valid, which affects the expiration (exp) claim. Returned by the
getValidityLength method. This method returns a NoAccess exception for JWTs generated using methods in the
Auth.JWTUtil class. For these JWTs, the incoming JWT determines the validity length.
toJSONString()
Generates the JSON object representation of the Claims Set as an encoded JWT payload.

clone()
Makes a duplicate copy of the JWT object.

Signature
public Object clone()

Return Value
Type: JWT

144
Apex Reference Guide JWT Class

getAdditionalClaims()
Returns a map of additional claims in the JWT, where the key string contains the name of the claim, and the value contains the value of
the claim.

Signature
public Map<String,Object> getAdditionalClaims()

Return Value
Type: Map<String,Object>
The claims returned depend on how the JWT was generated.
If the JWT was generated using other methods in the Auth.JWT class, this method returns the claims that were set using the
setAdditionalClaims method.
For JWTs generated using methods in the Auth.JWTUtil class, the getAdditionalClaims method returns all claims except
for these three.
• aud (audience)—Use the getAud method instead.
• iss (issuer)—Use the getIss method instead.
• sub (subject)—Use the getSub method instead.
For these JWTs, when the incoming JWT has a claim that stores an inner JSON list, the claim value is returned as a string.

getAud()
Returns the audience (aud) claim that identifies the intended recipients of the JWT.

Signature
public String getAud()

Return Value
Type: String

getIss()
Returns the issuer (iss) claim that identifies the issuer of the JWT.

Signature
public String getIss()

Return Value
Type: String

145
Apex Reference Guide JWT Class

getNbfClockSkew()
Returns the not before (nbf) claim that identifies the time before which the JWT must not be accepted for processing, while allowing
some leeway for clock skew. This method returns a NoAccess exception for JWTs generated using methods in the Auth.JWTUtil
class. To return the nbf claim for these JWTs, use the getAdditionalClaims method instead.

Signature
public Integer getNbfClockSkew()

Return Value
Type: Integer

getSub()
Returns the subject (sub) claim that identifies the current user of the JWT.

Signature
public String getSub()

Return Value
Type: String

getValidityLength()
Returns the length of time (in seconds) that the JWT is valid, which affects the expiration (exp) claim. This method returns a NoAccess
exception for JWTs generated using methods in the Auth.JWTUtil class. To return the validity length for these JWTs, use the
getAdditionalClaims method instead.

Signature
public Integer getValidityLength()

Return Value
Type: Integer

setAdditionalClaims(additionalClaims)
Sets the additional claims in the JWT. Returned by the getAdditionalClaims method.

Signature
public void setAdditionalClaims(Map<String,Object> additionalClaims)

146
Apex Reference Guide JWT Class

Parameters
additionalClaims
Type: Map<String,Object>

Return Value
Type: void

Usage
Additional claims must not include any standard claims.

setAud(aud)
Sets the audience (aud) claim in the JWT. Returned by the getAud method.

Signature
public void setAud(String aud)

Parameters
aud
Type: String

Return Value
Type: void

setIss(iss)
Sets the issuer (iss) claim in the JWT. Returned by the getIss method.

Signature
public void setIss(String iss)

Parameters
iss
Type: String

Return Value
Type: void

147
Apex Reference Guide JWT Class

setNbfClockSkew(nbfClockSkew)
Sets the not before (nbf) claim in the JWT. Returned by the getNbfClockSkew method. This method returns a NoAccess
exception for JWTs generated using methods in the Auth.JWTUtil class. For these JWTs, the incoming JWT determines the nbf
claim.

Signature
public void setNbfClockSkew(Integer nbfClockSkew)

Parameters
nbfClockSkew
Type: Integer

Return Value
Type: void

setSub(sub)
Sets the subject (sub) claim in the JWT. Returned by the getSub method.

Signature
public void setSub(String sub)

Parameters
sub
Type: String

Return Value
Type: void

setValidityLength(validityLength)
Sets the length of time (in seconds) that the JWT is valid, which affects the expiration (exp) claim. Returned by the
getValidityLength method. This method returns a NoAccess exception for JWTs generated using methods in the
Auth.JWTUtil class. For these JWTs, the incoming JWT determines the validity length.

Signature
public void setValidityLength(Integer validityLength)

Parameters
validityLength
Type: Integer

148
Apex Reference Guide JWTBearerTokenExchange Class

Return Value
Type: void

toJSONString()
Generates the JSON object representation of the Claims Set as an encoded JWT payload.

Signature
public String toJSONString()

Return Value
Type: String

JWTBearerTokenExchange Class
Contains methods that POST the signed JWT bearer token to a token endpoint to request an access token, in the OAuth 2.0 JWT bearer
token flow.

Namespace
Auth

Usage
Use the methods in this class to post a signed JWT bearer token to the OAuth token endpoint, in exchange for an access token.
To test HTTP callouts to the token endpoint, use the Auth.HttpCalloutMockUtil class.

Example
In the following example application, the Apex controller:
1. Creates the JSON Claims Set.
2. Specifies the scope of the request with additional claims.
3. Creates the signed JWT.
4. Specifies the token endpoint and POSTs to it.
5. Gets the access token from the HTTP response.
public class MyController{

public MyController() {
Auth.JWT jwt = new Auth.JWT();
jwt.setSub('[email protected]');
jwt.setAud('https://login.salesforce.com');
jwt.setIss('3MVG99OxTyEMCQ3gNp2PjkqeZKxnmAiG1xV4oHh9AKL_rSK.BoSVPGZHQ
ukXnVjzRgSuQqGn75NL7yfkQcyy7');

149
Apex Reference Guide JWTBearerTokenExchange Class

//Additional claims to set scope


Map<String, Object> claims = new Map<String, Object>();
claims.put('scope', 'scope name');

jwt.setAdditionalClaims(claims);

//Create the object that signs the JWT bearer token


Auth.JWS jws = new Auth.JWS(jwt, 'CertFromCertKeyManagement');

//Get the resulting JWS in case debugging is required


String token = jws.getCompactSerialization();

//Set the token endpoint that the JWT bearer token is posted to
String tokenEndpoint = 'https://login.salesforce.com/services/oauth2/token';

//POST the JWT bearer token


Auth.JWTBearerTokenExchange bearer = new Auth.JWTBearerTokenExchange(tokenEndpoint,
jws);

//Get the access token


String accessToken = bearer.getAccessToken();

}
}

IN THIS SECTION:
JWTBearerTokenExchange Constructors
JWTBearerTokenExchange Methods

JWTBearerTokenExchange Constructors
The following are constructors for JWTBearerTokenExchange.

IN THIS SECTION:
JWTBearerTokenExchange(tokenEndpoint, jws)
Creates an instance of the JWTBearerTokenExchange class using the specified token endpoint and the signed JWT bearer
token.
JWTBearerTokenExchange()
Creates an instance of the Auth.JWTBearerTokenExchange class.

JWTBearerTokenExchange(tokenEndpoint, jws)
Creates an instance of the JWTBearerTokenExchange class using the specified token endpoint and the signed JWT bearer token.

Signature
public JWTBearerTokenExchange(String tokenEndpoint, Auth.JWS jws)

150
Apex Reference Guide JWTBearerTokenExchange Class

Parameters
tokenEndpoint
Type: String
The token endpoint that the signed JWT bearer token is POSTed to.
jws
Type: Auth.JWS
The signed JWT bearer token.

JWTBearerTokenExchange()
Creates an instance of the Auth.JWTBearerTokenExchange class.

Signature
public JWTBearerTokenExchange()

JWTBearerTokenExchange Methods
The following are methods for JWTBearerTokenExchange. All are instance methods.

IN THIS SECTION:
clone()
Makes a duplicate copy of the JWTBearerTokenExchange object.
getAccessToken()
Returns the access_token in the token response to the JWT bearer token request.
getGrantType()
Returns the grant type specified in the JWT bearer token request. The grant type value defaults to
urn:ietf:params:oauth:grant-type:jwt-bearer.
getHttpResponse()
Returns the full System.HttpResponse token response to the JWT bearer token request.
getJWS()
Returns the JWS specified in the JWT bearer token request.
getTokenEndpoint()
Returns the token endpoint that the JWT bearer token request is POSTed to.
setGrantType(grantType)
Sets the grant type in the JWT bearer token request. Returned by the getGrantType() method.
setJWS(jws)
Sets the JWS in the JWT bearer token request. Returned by the getJWS() method.
setTokenEndpoint(tokenEndpoint)
Sets the token endpoint that the JWT bearer token request is POSTed to. Returned by the getTokenEndpoint() method.

151
Apex Reference Guide JWTBearerTokenExchange Class

clone()
Makes a duplicate copy of the JWTBearerTokenExchange object.

Signature
public Object clone()

Return Value
Type: JWTBearerTokenExchange

getAccessToken()
Returns the access_token in the token response to the JWT bearer token request.

Signature
public String getAccessToken()

Return Value
Type: String

Usage
This method extracts the access_token from the token response. If the token response issues the access token in a different
parameter, the request fails.
If you want the full HTTP token response returned, use getHttpResponse instead.

getGrantType()
Returns the grant type specified in the JWT bearer token request. The grant type value defaults to
urn:ietf:params:oauth:grant-type:jwt-bearer.

Signature
public String getGrantType()

Return Value
Type: String

getHttpResponse()
Returns the full System.HttpResponse token response to the JWT bearer token request.

Signature
public System.HttpResponse getHttpResponse()

152
Apex Reference Guide JWTBearerTokenExchange Class

Return Value
Type: System.HttpResponse

Usage
You can get the access token from the full System.HttpResponse. If you want only the access_token from the token
response, you can use getAccessToken instead.

getJWS()
Returns the JWS specified in the JWT bearer token request.

Signature
public Auth.JWS getJWS()

Return Value
Type: Auth.JWS

getTokenEndpoint()
Returns the token endpoint that the JWT bearer token request is POSTed to.

Signature
public String getTokenEndpoint()

Return Value
Type: String

setGrantType(grantType)
Sets the grant type in the JWT bearer token request. Returned by the getGrantType() method.

Signature
public void setGrantType(String grantType)

Parameters
grantType
Type: String

Return Value
Type: void

153
Apex Reference Guide JWTUtil Class

setJWS(jws)
Sets the JWS in the JWT bearer token request. Returned by the getJWS() method.

Signature
public void setJWS(Auth.JWS jws)

Parameters
jws
Type: Auth.JWS

Return Value
Type: void

setTokenEndpoint(tokenEndpoint)
Sets the token endpoint that the JWT bearer token request is POSTed to. Returned by the getTokenEndpoint() method.

Signature
public void setTokenEndpoint(String tokenEndpoint)

Parameters
tokenEndpoint
Type: String

Return Value
Type: void

JWTUtil Class
Contains methods for validating a JSON Web Token (JWT) from an external identity provider as part of the OAuth 2.0 token exchange
flow. Use these methods as part of the validateIncomingToken method in the Auth.Oauth2TokenExchangeHandler
class.

Namespace
Auth

Usage
See Token Exchange Handler Validation and Subject Mapping.
If the methods in this class fail, Salesforce returns an Auth.JWTValidationException exception.

154
Apex Reference Guide JWTUtil Class

IN THIS SECTION:
JWTUtil Methods

JWTUtil Methods
The following are methods for JWTUtil.

IN THIS SECTION:
parseJWTFromStringWithoutValidation(incomingJWT)
Parses a JWT from an encoded string into a header, payload, and signature. Use this method to decode the JWT without validating
it.
validateJWTWithCert(incomingJWT, certDeveloperName)
Parses and validates the JWT using a certificate saved in Salesforce. The certificate can be self-signed or signed by a certificate
authority.
validateJWTWithKey(incomingJWT, publicKey)
Parses and validates the JWT using a public key from the external identity provider.
validateJWTWithKeysEndpoint(incomingJWT, keysEndpoint, shouldUseCache)
Parses and validates the JWT using a remote JSON Web Key Set (JWKS) endpoint on your external identity provider.

parseJWTFromStringWithoutValidation(incomingJWT)
Parses a JWT from an encoded string into a header, payload, and signature. Use this method to decode the JWT without validating it.

Signature
public static Auth.JWT parseJWTFromStringWithoutValidation(String incomingJWT)

Parameters
incomingJWT
Type: String
The JWT from your identity provider.

Return Value
Type:Auth.JWT

validateJWTWithCert(incomingJWT, certDeveloperName)
Parses and validates the JWT using a certificate saved in Salesforce. The certificate can be self-signed or signed by a certificate authority.

Signature
public static Auth.JWT validateJWTWithCert(String incomingJWT, String certDeveloperName)

155
Apex Reference Guide JWTUtil Class

Parameters
incomingJWT
Type: String
The JWT from your identity provider.
certDeveloperName
Type: String
A certificate saved in the Certificate and Key Management page in Setup.

Return Value
Type: Auth.JWT

validateJWTWithKey(incomingJWT, publicKey)
Parses and validates the JWT using a public key from the external identity provider.

Signature
public static Auth.JWT validateJWTWithKey(String incomingJWT, String publicKey)

Parameters
incomingJWT
Type: String
The JWT from your identity provider.
publicKey
Type: String
The public key from your identity provider.

Return Value
Type: Auth.JWT

validateJWTWithKeysEndpoint(incomingJWT, keysEndpoint, shouldUseCache)


Parses and validates the JWT using a remote JSON Web Key Set (JWKS) endpoint on your external identity provider.

Signature
public static Auth.JWT validateJWTWithKeysEndpoint(String incomingJWT, String
keysEndpoint, Boolean shouldUseCache)

Parameters
incomingJWT
Type: String
The JWT from your identity provider.

156
Apex Reference Guide LightningLoginEligibility Enum

keysEndpoint
Type: String
A URL pointing to a valid JWKS endpoint on your identity provider. The JWKS returned by the endpoint must conform to the
specification defined in RFC 7517: JSON Web Key (JWK).
To test HTTP callouts to the JWKS endpoint, use the Auth.HttpCalloutMockUtil class.
shouldUseCache
Type: Boolean
Indicates whether the certificate from the keys endpoint is cached.

Return Value
Type: Auth.JWT

LightningLoginEligibility Enum
Contains a Lightning Login eligibility value used by the Auth.SessionManagement.getLightningLoginEligibility
method.

Usage
If you use the Discovery page type, users can verify themselves with Lightning Login. Lightning Login lets internal users log in with
Salesforce Authenticator instead of a password. Certain conditions must be met for Lightning Login to succeed.
Call Auth.SessionManagement.getLightningLoginEligibility before or after a login attempt to get the eligibility
status. You can call after a login attempt to determine why the login attempt failed.

Enum Values
The following are the values of the Auth.LightningLoginEligibility enum.

Value Description
ELIGIBLE All eligibility conditions are met. The admin has enabled Salesforce Authenticator
and Lightning Login, assigned the user Lightning Login user permission, and selected
Allow only for users with the Lightning Login User permission from the Session
Settings Setup page. The user has set up Salesforce Authenticator and enrolled in
Lightning Login.

ORG_AUTHENTICATOR_NOT_ENABLED The admin hasn’t enabled Salesforce Authenticator.

ORG_PREF_NOT_ENABLED The admin hasn’t enabled Lightning Login. The Admin must select Allow Lightning
Login from the Session Settings Setup page.

USER_AUTHENTICATOR_NOT_CONNECTED The user hasn’t set up Salesforce Authenticator.

USER_NOT_ALLOWED The admin hasn’t granted the user AllowLightningLogin user permission. Allowing
Lightning Login to certain users requires the OnlyLLPermUserAllowed org preference.
Admins must select Allow only for users with the Lightning Login User
permission from the Session Settings Setup page.

157
Apex Reference Guide LoginDiscoveryHandler Interface

Value Description
USER_NOT_ENROLLED The user hasn’t enrolled in Lightning Login.

USER_PERM_NOT_ENABLED The admin hasn’t granted the user the Lightning Login Eligible user permission.

LoginDiscoveryHandler Interface
Salesforce gives you the ability to log in users based on other verification methods than username and password. For example, it can
prompt users to log in with their email, phone number, or another identifier like a Federation ID or device identifier. Login Discovery is
available to these licenses: Customer Community, Customer Community Plus, External Identity, Partner Community, and Partner
Community Plus.

Namespace
Auth

Usage
Implement a Auth.LoginDiscoveryHandler for an interview-based log in. The handler looks up a user from the identifier
entered, and can call Site.passwordlessLogin to determine which credential to use, such as email or SMS. Or the handler can
redirect a user to a third-party identity provider for login. With this handler, the login page doesn't show a password field. However, you
can use Site.passwordlessLogin to then prompt for a password.
From the user perspective, the user enters an identifier at the log in prompt. Then the user completes the login by entering a PIN or
password. Or, if SSO-enabled, the user bypasses login.
For an example, see LoginDiscoveryHandler Example Implementation. For more details, see Salesforce Customer Identity in Salesforce
Help.

IN THIS SECTION:
LoginDiscoveryHandler Method
LoginDiscoveryHandler Example Implementation

LoginDiscoveryHandler Method
Here’s the method for LoginDiscoveryHandler.

IN THIS SECTION:
login(identifier, startUrl, requestAttributes)
Log in the customer or partner given the specified identifier, such as email or phone number. If successful, redirect the user to the
Experience Cloud site page specified by the start URL.

login(identifier, startUrl, requestAttributes)


Log in the customer or partner given the specified identifier, such as email or phone number. If successful, redirect the user to the
Experience Cloud site page specified by the start URL.

158
Apex Reference Guide LoginDiscoveryHandler Interface

Signature
public System.PageReference login(String identifier, String startUrl,
Map<String,String>requestAttributes)

Parameters
identifier
Type: String
Identifier the customer or partner entered at the login prompt, for example, an email address or phone number.
startUrl
Type: String
Path to the Experience Cloud site page requested by the customer or partner. The user is redirected to this location after successful
login.
requestAttributes
Type: Map<String,String>
Information about the login request based on the user’s browser state when accessing the login page. requestAttributes
passes in the CommunityUrl, IpAddress, UserAgent, Platform, Application, City, Country, and Subdivision values. The City, Country,
and Subdivision values come from IP geolocation.

Return Value
Type: System.PageReference
The URL of the page where the user is redirected.

Example
Here’s a sample requestAttributes response.
CommunityUrl=http://my-developer-edition.mycompany.com:5555/discover
IpAddress=55.555.0.0
UserAgent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/605.1.15 (KHTML,
like Gecko) Version/11.1 Safari/605.1.15
Platform=Mac OSX
Application=Browser
City=San Mateo
Country=United States
Subdivision=California

LoginDiscoveryHandler Example Implementation


This Apex code example implements the Auth.LoginDiscoveryHandler interface. It checks whether the user who is logging
in has a verified email or phone number, depending on which identifier was supplied on the login page. If verified, with
Auth.VerificationMethod.EMAIL or Auth.VerificationMethod.SMS, we send a challenge to the identifier, either
the user’s email address or mobile device. If the user enters the code correctly on the verify page, the user is redirected to the Experience
Cloud site’s page specified by the start URL. If the user isn’t verified, the user must enter a password to log in. The handler also checks
that the email and phone number are unique with this code: users.size()==1.

159
Apex Reference Guide LoginDiscoveryHandler Interface

Note: Passwordless login works only with verified methods. You can check the verification status on the User object, for example,
with User list view, a report, or the API. Make sure that your solution handles the case where the user doesn’t have a verification
method. This code example falls back to a password.
The default discoverable login handler checks whether the user entered a valid email address or phone number before redirecting
the user to the verification page. If an invalid entry is made, the handler returns an error. Because this behavior is vulnerable to
user enumeration attack, make sure that your solution prevents this attack. For example, you can create a dummy page similar to
the verification page and redirect the user to the dummy page when invalid user identifier is entered. Also, use generic error
messages to avoid providing additional information.

The discoveryResult function calls the Site.passwordlessLogin method to log the user in with the specified verification
method. The getSsoRedirect function looks up whether the user logs in with SAML or an Auth Provider. Add the
implementation-specific logic to handle the lookup.
global class AutocreatedDiscLoginHandler1535377170343 implements Auth.LoginDiscoveryHandler
{

global PageReference login(String identifier, String startUrl, Map<String, String>


requestAttributes) {
if (identifier != null && isValidEmail(identifier)) {
// Search for user by email.
List<User> users = [SELECT Id FROM User WHERE Email = :identifier AND IsActive =
TRUE];
if (!users.isEmpty() && users.size() == 1) {
// User must have a verified email before using this verification method.
// We cannot send messages to unverified emails.
// You can check if the user's email verified bit set and add the
// password verification method as fallback.
List<TwoFactorMethodsInfo> verifiedInfo = [SELECT HasUserVerifiedEmailAddress
FROM TwoFactorMethodsInfo WHERE UserId = :users[0].Id];
if (!verifiedInfo.isEmpty() && verifiedInfo[0].HasUserVerifiedEmailAddress ==
true) {
// Use email verification method if the user's email is verified.
return discoveryResult(users[0], Auth.VerificationMethod.EMAIL, startUrl,
requestAttributes);
} else {
// Use password verification method as fallback
// if the user's email is unverified.
return discoveryResult(users[0], Auth.VerificationMethod.PASSWORD, startUrl,
requestAttributes);
}
} else {
throw new Auth.LoginDiscoveryException('No unique user found. User count=' +
users.size());
}
}
if (identifier != null) {
String formattedSms = getFormattedSms(identifier);
if (formattedSms != null) {
// Search for user by SMS.
List<User> users = [SELECT Id FROM User WHERE MobilePhone = :formattedSms AND
IsActive = TRUE];
if (!users.isEmpty() && users.size() == 1) {
// User must have a verified SMS before using this verification method.

160
Apex Reference Guide LoginDiscoveryHandler Interface

// We cannot send messages to unverified mobile numbers.


// You can check if the user's mobile verified bit is set or add
// the password verification method as fallback.
List<TwoFactorMethodsInfo> verifiedInfo = [SELECT HasUserVerifiedMobileNumber
FROM TwoFactorMethodsInfo WHERE UserId = :users[0].Id];
if (!verifiedInfo.isEmpty() && verifiedInfo[0].HasUserVerifiedMobileNumber
== true) {
// Use SMS verification method if the user's mobile number is verified.

return discoveryResult(users[0], Auth.VerificationMethod.SMS, startUrl,


requestAttributes);
} else {
// Use password verification method as fallback if the user's
// mobile number is unverified.
return discoveryResult(users[0], Auth.VerificationMethod.PASSWORD,
startUrl, requestAttributes);
}
} else {
throw new Auth.LoginDiscoveryException('No unique user found. User count='
+ users.size());
}
}
}
if (identifier != null) {
// You can customize the code to find user via other attributes,
// such as SSN or Federation ID.
}
throw new Auth.LoginDiscoveryException('Invalid Identifier');
}
private boolean isValidEmail(String identifier) {
String emailRegex =
'^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
// source: https://www.regular-expressions.info/email.html
Pattern EmailPattern = Pattern.compile(emailRegex);
Matcher EmailMatcher = EmailPattern.matcher(identifier);
if (EmailMatcher.matches()) { return true; }
else { return false; }
}
private String getFormattedSms(String identifier) {
// Accept SMS input formats with 1- or 2-digit country code,
// 3-digit area code, and 7-digit number.
// You can customize the SMS regex to allow different formats.
String smsRegex = '^(\\+?\\d{1,2}?[\\s-])?(\\(?\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{4})$';

Pattern smsPattern = Pattern.compile(smsRegex);


Matcher smsMatcher = SmsPattern.matcher(identifier);
if (smsMatcher.matches()) {
try {
// Format user input into the verified SMS format '+xx xxxxxxxxxx'
// before DB lookup. If no country code is provided, append
// US country code +1 for the default.
String countryCode = smsMatcher.group(1) == null ? '+1' : smsMatcher.group(1);

return System.UserManagement.formatPhoneNumber(countryCode, smsMatcher.group(2));

161
Apex Reference Guide LoginDiscoveryHandler Interface

} catch(System.InvalidParameterValueException e) {
return null;
}
} else { return null; }
}
private PageReference getSsoRedirect(User user, String startUrl, Map<String, String>
requestAttributes) {
// You can look up to check whether the user should log in with
// SAML or an Auth Provider and return the URL to initialize SSO.
return null;
}
private PageReference discoveryResult(User user, Auth.VerificationMethod method, String
startUrl, Map<String, String> requestAttributes) {
// Only users with an External Identity or community license can log in
// using Site.passwordlessLogin. Use getSsoRedirect to let your org employees
// log in to an Experience Cloud site.
PageReference ssoRedirect = getSsoRedirect(user, startUrl, requestAttributes);
if (ssoRedirect != null) {
return ssoRedirect;
} else {
if (method != null) {
List<Auth.VerificationMethod> methods = new List<Auth.VerificationMethod>();
methods.add(method);
PageReference pwdlessRedirect = Site.passwordlessLogin(user.Id, methods,
startUrl);
if (pwdlessRedirect != null) {
return pwdlessRedirect;
} else {
throw new Auth.LoginDiscoveryException('No Passwordless Login redirect URL
returned for verification method: ' + method);
}
} else {
throw new Auth.LoginDiscoveryException('No method found');
}
}
}
}

Code Example: Filter Login Discovery Users by Profile


Your production org can have multiple users with the same verified email address and mobile number. But your customers must have
unique ones. To address this problem, you can add a few lines of code that filters users by profile to ensure uniqueness. This code example
handles users with the External Identity User profile, but can be adapted to support other use cases. For example, you can modify the
first line of code to address users with other user licenses or criteria.
Login Discovery is available with the following user licenses: Customer Community, Customer Community Plus, External Identity, Partner
Community, and Partner Community Plus. It depends on which profiles have access to your Experience Cloud site.
global class AutocreatedDiscLoginHandler1551301979709 implements Auth.LoginDiscoveryHandler
{

global PageReference login(String identifier, String startUrl, Map<String, String>


requestAttributes) {

162
Apex Reference Guide LoginDiscoveryHandler Interface

if (identifier != null && isValidEmail(identifier)) {


// Ensure uniqueness by profile
Profile p = [SELECT id FROM profile WHERE name = 'External Identity User'];
List<User> users = [SELECT Id FROM User WHERE Email = :identifier AND IsActive =
TRUE AND profileId=:p.id];
if (!users.isEmpty() && users.size() == 1) {
// User must have verified email before using this verification method. We
cannot send messages to unverified emails.
// You can check if the user has email verified bit on and add the password
verification method as fallback.
List<TwoFactorMethodsInfo> verifiedInfo = [SELECT HasUserVerifiedEmailAddress
FROM TwoFactorMethodsInfo WHERE UserId = :users[0].Id];
if (!verifiedInfo.isEmpty() && verifiedInfo[0].HasUserVerifiedEmailAddress ==
true) {
// Use email verification method if the user's email is verified.
return discoveryResult(users[0], Auth.VerificationMethod.EMAIL, startUrl,
requestAttributes);
} else {
// Use password verification method as fallback if the user's email is
unverified.
return discoveryResult(users[0], Auth.VerificationMethod.PASSWORD, startUrl,
requestAttributes);
}
} else {
throw new Auth.LoginDiscoveryException('No unique user found. User count=' +
users.size());
}
}
if (identifier != null) {
String formattedSms = getFormattedSms(identifier);
if (formattedSms != null) {
// Ensure uniqueness by profile
Profile p = [SELECT id FROM profile WHERE name = 'External Identity User'];
List<User> users = [SELECT Id FROM User WHERE MobilePhone = :formattedSms AND
IsActive = TRUE AND profileId=:p.id];
if (!users.isEmpty() && users.size() == 1) {
// User must have verified SMS before using this verification method. We
cannot send messages to unverified mobile numbers.
// You can check if the user has mobile verified bit on or add the password
verification method as fallback.
List<TwoFactorMethodsInfo> verifiedInfo = [SELECT HasUserVerifiedMobileNumber
FROM TwoFactorMethodsInfo WHERE UserId = :users[0].Id];
if (!verifiedInfo.isEmpty() && verifiedInfo[0].HasUserVerifiedMobileNumber
== true) {
// Use SMS verification method if the user's mobile number is verified.

return discoveryResult(users[0], Auth.VerificationMethod.SMS, startUrl,


requestAttributes);
} else {
// Use password verification method as fallback if the user's mobile
number is unverified.
return discoveryResult(users[0], Auth.VerificationMethod.PASSWORD,
startUrl, requestAttributes);
}

163
Apex Reference Guide LoginDiscoveryHandler Interface

} else {
throw new Auth.LoginDiscoveryException('No unique user found. User count='
+ users.size());
}
}
}
if (identifier != null) {
// You can customize the code to find user via other attributes, such as SSN or
Federation ID
}
throw new Auth.LoginDiscoveryException('Invalid Identifier');
}

private boolean isValidEmail(String identifier) {


String emailRegex =
'^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
// source: https://www.regular-expressions.info/email.html
Pattern EmailPattern = Pattern.compile(emailRegex);
Matcher EmailMatcher = EmailPattern.matcher(identifier);
if (EmailMatcher.matches()) { return true; }
else { return false; }
}

private String getFormattedSms(String identifier) {


// Accept SMS input formats with 1 or 2 digits country code, 3 digits area code and 7
digits number
// You can customize the SMS regex to allow different formats
String smsRegex = '^(\\+?\\d{1,2}?[\\s-])?(\\(?\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{4})$';

Pattern smsPattern = Pattern.compile(smsRegex);


Matcher smsMatcher = SmsPattern.matcher(identifier);
if (smsMatcher.matches()) {
try {
// Format user input into the verified SMS format '+xx xxxxxxxxxx' before DB
lookup
// Append US country code +1 by default if no country code is provided
String countryCode = smsMatcher.group(1) == null ? '+1' : smsMatcher.group(1);

return System.UserManagement.formatPhoneNumber(countryCode, smsMatcher.group(2));

} catch(System.InvalidParameterValueException e) {
return null;
}
} else { return null; }
}

private PageReference getSsoRedirect(User user, String startUrl, Map<String, String>


requestAttributes) {
// You can look up if the user should log in with SAML or an Auth Provider and return
the URL to initialize SSO.
return null;
}

private PageReference discoveryResult(User user, Auth.VerificationMethod method, String

164
Apex Reference Guide LoginDiscoveryMethod Enum

startUrl, Map<String, String> requestAttributes) {


//Only users with an External Identity or community license can login using
Site.passwordlessLogin
//Use getSsoRedirect to enable your org employees to log in to an Experience Cloud
site
PageReference ssoRedirect = getSsoRedirect(user, startUrl, requestAttributes);
if (ssoRedirect != null) {
return ssoRedirect;
} else {
if (method != null) {
List<Auth.VerificationMethod> methods = new List<Auth.VerificationMethod>();
methods.add(method);
PageReference pwdlessRedirect = Site.passwordlessLogin(user.Id, methods,
startUrl);
if (pwdlessRedirect != null) {
return pwdlessRedirect;
} else {
throw new Auth.LoginDiscoveryException('No Passwordless Login redirect URL
returned for verification method: ' + method);
}
} else {
throw new Auth.LoginDiscoveryException('No method found');
}
}
}
}

LoginDiscoveryMethod Enum
Contains methods used to verify the user’s identity when the My Domain login process uses Login Discovery.

Usage
Specifies the verification method used to authenticate internal users when My Domain is set up for Login Discovery.

Enum Values
Auth.LoginDiscoveryMethod enum has the following values.

Value Description
LIGHTNING_LOGIN Verify identity by Lightning Login, which lets internal users log in with Salesforce
Authenticator.

PASSWORD Verify identity by entering a password.

165
Apex Reference Guide MyDomainLoginDiscoveryHandler Interface

MyDomainLoginDiscoveryHandler Interface
The handler used to implement the My Domain Login Discovery page, which is an interview-based (two-step) login process. First the
user is prompted for a unique identifier such as an email address or phone number. Then the handler determines (discovers) how to
authenticate the user. Either the user enters a password or is directed to an identity provider’s login page.

Namespace
Auth

Usage
Implement MyDomainLoginDiscoveryHandler to let My Domain users log in with something other than their username and
password. This handler contains the logic to look up the user based on the identifier value entered on the login page. The
Auth.MyDomainLoginDiscoveryHandler.login method is invoked when the identifier page is submitted and finds the
user that corresponds to the submitted identifier. The Auth.SessionManagement.finishLoginDiscovery method
sends the user to the authentication mechanism and then logs in the user.
Register the handler from the My Domain Setup page. Under Authentication Configuration, select the Discovery Login Page Type. For
Login Discovery Handler, select this handler from the list of Apex classes.
For an example, see MyDomainLoginDiscoveryHandler Example Implementation. For more details, search for My Domain Login Discovery
in Salesforce Help.

IN THIS SECTION:
MyDomainLoginDiscoveryHandler Method
MyDomainLoginDiscoveryHandler Example Implementation

MyDomainLoginDiscoveryHandler Method
MyDomainLoginDiscoveryHandler has the following method.

IN THIS SECTION:
login(identifier, startUrl, requestAttributes)
Log in a Salesforce user given the specified identifier, such as email or phone number. If successful, redirect the user to the page
specified by the start URL.

login(identifier, startUrl, requestAttributes)


Log in a Salesforce user given the specified identifier, such as email or phone number. If successful, redirect the user to the page specified
by the start URL.

Signature
public System.PageReference login(String identifier, String startUrl, Map<String,String>
requestAttributes)

166
Apex Reference Guide MyDomainLoginDiscoveryHandler Interface

Parameters
identifier
Type: String
Identifier the Salesforce user entered at the login prompt, for example, an email address or phone number.
startUrl
Type: String
The page users see after successfully logging in to the My Domain subdomain.
requestAttributes
Type: Map <String, String>
Information about the login request based on the user’s browser state when accessing the login page. requestAttributes
passes in the MyDomainUrl, IpAddress, UserAgent, Platform, Application, City, Country, and Subdivision values. The City, Country,
and Subdivision values come from IP address geolocation.

Return Value
Type: System.PageReference
The URL of the page where the user is redirected to complete authentication.

Example
Here’s a sample requestAttributes response.
CommunityUrl=http://my-dev-ed.my.salesforce.com:5555/discover
IpAddress=55.255.0.0
UserAgent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/605.1.15 (KHTML,
like Gecko) Version/11.1 Safari/605.1.15
Platform=Mac OSX
Application=Browser
City=San Mateo
Country=United States
Subdivision=California

MyDomainLoginDiscoveryHandler Example Implementation


Here's an example of the Auth.MyDomainLoginDiscoveryHandler interface. This sample class contains the default logic
for My Domain login discovery using password authentication. You can customize the code to ensure it meets your needs. The
requestAttributes parameter provides additional information that you can use in the discovery logic. Attributes include MyDomainUrl,
IpAddress, UserAgent, and location information (such as Country and City). Use Auth.DiscoveryCustomErrorException
to throw custom errors to display on the login page.
To implement this interface, the My Domain login page type must be set to Discovery.
// This sample class contains the default logic for My Domain login discovery by password.
// You can customize the code to ensure it meets your needs. The requestAttributes parameter
// provides additional information you can use in the discovery logic. Attributes include MyDomainUrl,
// IpAddress, UserAgent, and location information (such as Country and City).
// Use Auth.DiscoveryCustomErrorException to throw custom errors which will be shown on login page.
global class MyDomainDiscLoginDefaultHandler implements Auth.MyDomainLoginDiscoveryHandler {
global PageReference login(String identifier, String startUrl, Map<String, String> requestAttributes)
{

167
Apex Reference Guide MyDomainLoginDiscoveryHandler Interface

if (identifier != null) {
// Search for user by email
List<User> users = [SELECT Id FROM User WHERE Email = :identifier AND IsActive = TRUE];
if (!users.isEmpty() && users.size() == 1) {
return discoveryResult(users[0], startUrl, requestAttributes);
} else {
throw new Auth.LoginDiscoveryException('No unique user found. User count=' + users.size());
}
}
throw new Auth.LoginDiscoveryException('Invalid Identifier');
}

private PageReference getSsoRedirect(User user, String startUrl, Map<String, String> requestAttributes) {


// You can look up if the user should log in with SAML or an Auth Provider and return the URL to initialize SSO. For example:
// SamlSsoConfig SSO = [select Id from SamlSsoConfig where DeveloperName='SamlTest' limit 1];

// To get the URL for a My Domain subdomain, you can pass null in the communityURL
parameter.
// String ssoUrl = Auth.AuthConfiguration.getSamlSsoUrl(null, startUrl, SSO.Id);
// return new PageReference(ssoUrl);
return null;
}

private PageReference discoveryResult(User user, String startUrl, Map<String, String> requestAttributes)

{
PageReference ssoRedirect = getSsoRedirect(user, startUrl, requestAttributes);
if (ssoRedirect != null) {
return ssoRedirect;
}
else {
return Auth.SessionManagement.finishLoginDiscovery(Auth.LoginDiscoveryMethod.password, user.Id);
}
}
}

Test Class for MyDomainDiscLoginDefaultHandler Class


The following is the test class for MyDomainDiscoveryLoginHandler. For the test to work, your org must have the My Domain login page
type set to Discovery.
// Test class for MyDomainDiscLoginDefaultHandler
@isTest
class MyDomainDiscLoginDefaultHandlerTest {
/* Test Discoverable handler login.
Create a user with specific email identifier and invoke login.
Expected : User should be discovered and pagereference should be returned.
*/
@isTest static void testLogin() {
// Create user
String identifierEmail = getUniqueName() + '@test.org';
createTestUser(identifierEmail);
Map<String, String> requestAttributes = new Map<String, String>();
String startUrl = '';

168
Apex Reference Guide MyDomainLoginDiscoveryHandler Interface

MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();


// Invoke login method from handler with the email of user created
PageReference pageReference = myDomainDiscLoginDefaultHandler.login(identifierEmail, startUrl, requestAttributes);
// Asser page reference is returned
System.assertNotEquals(null, pageReference, 'Page reference was not returned');
}
/* Test Discoverable handler login with invalid (non-existing) user.
Expected : Auth.LoginDiscoveryException
*/
@isTest static void testLoginWithInvalidUser() {
try {
Map<String, String> requestAttributes = new Map<String, String>();
String startUrl = '';
String uniqueName = getUniqueName();
String email = uniqueName + '@test.org';
MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();
// Invoke login method from handler with non-existing user
myDomainDiscLoginDefaultHandler.login(email, startUrl, requestAttributes);
}catch (Auth.LoginDiscoveryException loginDiscoveryException) {
// Assert exception message
System.assert(loginDiscoveryException.getMessage().contains('Nouniqueuserfound'),'message='+loginDiscoveryException.getMessage());
}
}
/*
Generate a random name
*/
private static String getUniqueName() {
String orgId = UserInfo.getOrganizationId();
String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
String uniqueName = orgId + dateString + randomInt;
return uniqueName;
}
/*
Create user with given email.
*/
private static void createTestUser(String identifierEmail)
{
String uniqueName = getUniqueName();
Profile pf = [SELECT Id FROM Profile WHERE Name='Standard User'];
String profileID = pf.Id;
String fName = 'fname';
String lName = uniqueName + '-lname';
User tuser = new User( firstname = fName,
lastName = lName,
email = identifierEmail,
Username = uniqueName + '@test.org',
EmailEncodingKey = 'ISO-8859-1',
Alias = uniqueName.substring(18, 23),
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US',
ProfileId = profileID);
insert tuser;

169
Apex Reference Guide Oauth2TokenExchangeHandler Class

}
}

Oauth2TokenExchangeHandler Class
Use this class to create a token exchange handler that validates tokens from an external identity provider and maps the token’s subject
to a Salesforce user during the OAuth 2.0 token exchange flow. The handler can also be used to create users by setting up a new User
object and returning it to Salesforce for automatic insertion.

Namespace
Auth

Usage
See Token Exchange Handler Validation and Subject Mapping.

IN THIS SECTION:
Oauth2TokenExchangeHandler Methods

Oauth2TokenExchangeHandler Methods
The following are methods for Oauth2TokenExchangeHandler.

IN THIS SECTION:
getUserForTokenSubject(networkId, result, canCreateUser, appDeveloperName, appType)
Finds the subject defined in the external identity provider’s token so that it can be mapped to a Salesforce subject.
validateIncomingToken(appDeveloperName, appType, incomingToken, tokenType)
Validates an access token, refresh token, ID token, SAML 2.0 assertion, or JWT passed from an external identity provider during the
OAuth 2.0 token exchange flow.

getUserForTokenSubject(networkId, result, canCreateUser, appDeveloperName,


appType)
Finds the subject defined in the external identity provider’s token so that it can be mapped to a Salesforce subject.

Signature
public User getUserForTokenSubject(Id networkId, Auth.TokenValidationResult result,
Boolean canCreateUser, String appDeveloperName, Auth.IntegratingAppType appType)

Parameters
networkId
Type: Id
The identifier for the Salesforce user, if one exists.

170
Apex Reference Guide Oauth2TokenExchangeHandler Class

result
Type: Auth.TokenValidationResult
The result of the token validation performed by the validateIncomingToken method in the
Auth.Oauth2TokenExchangeHandler class.
canCreateUser
Type: Boolean
Specifies whether the handler can set up a User object if no user exists. Salesforce automatically inserts the user into this object.
appDeveloperName
Type: String
The developer name of the Salesforce connected app or external client app that’s being used to integrate your app with Salesforce.
appType
Type: Auth.IntegratingAppType
Specifies whether your app is integrated with Salesforce as a connected app or as an external client app.

Return Value
Type: User
Returns a User object with the user information obtained from the token, from Salesforce, and from callouts to the identity provider, if
applicable. The User object can be an existing user record or a new user that hasn’t been inserted in the database. If it’s a new user,
Salesforce automatically inserts the user on behalf of the token exchange handler.

validateIncomingToken(appDeveloperName, appType, incomingToken, tokenType)


Validates an access token, refresh token, ID token, SAML 2.0 assertion, or JWT passed from an external identity provider during the OAuth
2.0 token exchange flow.

Signature
public Auth.TokenValidationResult validateIncomingToken(String appDeveloperName,
Auth.IntegratingAppType appType, String incomingToken, Auth.OAuth2TokenExchangeType
tokenType)

Parameters
appDeveloperName
Type: String
The developer name of the Salesforce connected app or external client app that’s being used to integrate your app with Salesforce.
appType
Type: Auth.IntegratingAppType
Specifies whether your app is integrated with Salesforce as a connected app or as an external client app.
incomingToken
Type: String
The token from the external identity provider.
tokenType
Type: Auth.OAuth2TokenExchangeType

171
Apex Reference Guide OAuth2TokenExchangeType Enum

The type of token from the external identity provider. It can be an access token, a refresh token, an ID token, a SAML 2.0 assertion,
or any token that’s formatted as a JSON Web Token (JWT).

Return Value
Type: Auth.TokenValidationResult
Returns information about whether the token is valid, data extracted from the token, the token itself, and the token type. It can also
return a custom error message if the validation failed.

OAuth2TokenExchangeType Enum
Used during the OAuth 2.0 token exchange flow to specify the type of token that’s being exchanged for a Salesforce token.

Usage
During the token exchange flow, your app requests a token from Salesforce by sending a POST request with a token from an external
identity provider. The request includes a subject_token_type parameter to specify the type of token. The values specified in
this enum must correspond to the subject_token_type in the token request.

Enum Values
The following are the values of the Auth.OAuth2TokenExchangeType enum.

Value Description
ACCESS_TOKEN An access token from the identity provider. The corresponding
subject_token_type is
urn:ietf:params:oauth:token-type:access_token.

ID_TOKEN An ID token from the identity provider. The corresponding


subject_token_type is
urn:ietf:params:oauth:token-type:id_token.

JWT A token from the identity provider that’s formatted as a JSON Web Token (JWT).
The corresponding subject_token_type is
urn:ietf:params:oauth:token-type:JWT.

REFRESH_TOKEN A refresh token from the identity provider. The corresponding


subject_token_type is
urn:ietf:params:oauth:token-type:refresh_token.

SAML_2 A SAML 2.0 assertion from the identity provider. The corresponding
subject_token_type is
urn:ietf:params:oauth:token-type:saml2.

OAuthRefreshResult Class
Stores the result of an AuthProviderPluginClass refresh method. OAuth authentication flow provides a refresh token that
can be used to get a new access token. Access tokens have a limited lifetime as specified by the session timeout value. When an access
token expires, use a refresh token to get a new access token.

172
Apex Reference Guide OAuthRefreshResult Class

Namespace
Auth

Usage
The OAuthRefreshResult class contains the parameters, accessToken, refreshToken, and error, all of which are of
type string. For a code example, see .

IN THIS SECTION:
OAuthRefreshResult Constructors
OAuthRefreshResult Properties

OAuthRefreshResult Constructors
The following are constructors for OAuthRefreshResult.

IN THIS SECTION:
OAuthRefreshResult(accessToken, refreshToken, error)
Creates an instance of the OAuthRefreshResult class using the specified access token, refresh token, and error for a custom
authentication provider plug-in.
OAuthRefreshResult(accessToken, refreshToken)
Creates an instance of the OAuthRefreshResult class using the specified access token and refresh token for a custom
authentication provider plug-in. Use this method when you know that the refresh was successful.

OAuthRefreshResult(accessToken, refreshToken, error)


Creates an instance of the OAuthRefreshResult class using the specified access token, refresh token, and error for a custom
authentication provider plug-in.

Signature
public OAuthRefreshResult(String accessToken, String refreshToken, String error)

Parameters
accessToken
Type: String
OAuth access token for the user who is currently logged in.
refreshToken
Type: String
OAuth refresh token for the user who is currently logged in.
error
Type: String
Error that occurred when a user attempted to authenticate with the custom authentication provider.

173
Apex Reference Guide OAuthRefreshResult Class

OAuthRefreshResult(accessToken, refreshToken)
Creates an instance of the OAuthRefreshResult class using the specified access token and refresh token for a custom authentication
provider plug-in. Use this method when you know that the refresh was successful.

Signature
public OAuthRefreshResult(String accessToken, String refreshToken)

Parameters
accessToken
Type: String
The OAuth access token for the user who is logged in.
refreshToken
Type: String
The OAuth refresh token for the user who is logged in.

OAuthRefreshResult Properties
The following are properties for OAuthRefreshResult.

IN THIS SECTION:
accessToken
The OAuth access token for the user who is currently logged in.
error
Error that occurs when a user unsuccessfully attempts to authenticate with the custom authentication provider.
refreshToken
The OAuth refresh token for the user who is currently logged in.

accessToken
The OAuth access token for the user who is currently logged in.

Signature
public String accessToken {get; set;}

Property Value
Type: String

error
Error that occurs when a user unsuccessfully attempts to authenticate with the custom authentication provider.

174
Apex Reference Guide OauthToken Class

Signature
public String error {get; set;}

Property Value
Type: String

refreshToken
The OAuth refresh token for the user who is currently logged in.

Signature
public String refreshToken {get; set;}

Property Value
Type: String

OauthToken Class
Contains a method to revoke OAuth access tokens and refresh tokens. This method supports opaque tokens and JSON Web Token
(JWT)-based access tokens, including guest and named user JWT-based access tokens.

Namespace
Auth

Usage
When a client completes an authorization flow and is authorized to access Salesforce data, they’re issued an access token, which the
client can use to make authenticated requests for protected Salesforce resources. The client can also use refresh tokens to get more
access tokens. If you don’t want the client to access Salesforce data anymore, revoke its Salesforce tokens.
This class is distinct from the Auth.AuthToken class, which contains a method to revoke tokens issued by a third-party provider
instead of Salesforce tokens.

IN THIS SECTION:
OauthToken Methods

OauthToken Methods
The following are methods for OauthToken.

IN THIS SECTION:
revokeToken(type, authToken)
Revokes Salesforce-issued OAuth tokens.

175
Apex Reference Guide OauthTokenType Enum

revokeToken(type, authToken)
Revokes Salesforce-issued OAuth tokens.

Signature
public static Boolean revokeToken(Auth.OauthTokenType type, String authToken)

Parameters
type
Type: Auth.OauthTokenType
Specifies the type of token to be revoked. To revoke an opaque access token, use the ACCESS_TOKEN value. To revoke a refresh
token and any associated access tokens, use the REFRESH_TOKEN value. To revoke a refresh token and associated access tokens,
use the DELETE_TOKEN value. To revoke a JSON Web Token (JWT)-based access token, use the ORG_JWT value.
authToken
Type: String
The access token (opaque or JWT-based), refresh token, or delete token issued by Salesforce.

Return Value
Type: Boolean
The method returns true if successful, and false if not. For invalid or expired tokens, the method returns a
NoDataFoundException exception.

OauthTokenType Enum
Specifies the type of Salesforce-issued OAuth 2.0 token being revoked in the OauthToken.revokeToken method.

Enum Values
The following are the values of the Auth.OauthTokenType enum.

Value Description
ACCESS_TOKEN An opaque access token, which Salesforce grants to a client when it successfully
completes an authorization flow. Salesforce grants opaque access tokens by default.

DELETE_TOKEN A delete token, which can be queried and used to revoke refresh tokens and
associated access tokens.

REFRESH_TOKEN A refresh token, which Salesforce grants to a client as a result of the refresh token
flow. Refresh tokens are used to get more access tokens.

ORG_JWT A JSON Web Token (JWT)-based access token, which Salesforce grants to a client
when it successfully completes an authorization flow. Salesforce grants JWT-based
access tokens if you enable them for a connected app or external client app.

176
Apex Reference Guide RegistrationHandler Interface

RegistrationHandler Interface
Salesforce provides the ability to use an authentication provider, such as Facebook© or Janrain©, for single sign-on into Salesforce.

Namespace
Auth

Usage
To set up single sign-on, you must create a class that implements Auth.RegistrationHandler. Classes implementing the
Auth.RegistrationHandler interface are specified as the Registration Handler in authentication provider definitions,
and enable single sign-on into Salesforce portals and organizations from third-party services such as Facebook. Using information from
the authentication providers, your class must perform the logic of creating and updating user data as appropriate, including any associated
account and contact records.

Note: During the user update process, you can use the confirmUser() method to ensure that users are correctly mapped
between Salesforce and the third party. For more information, see the ConfirmUserRegistrationHandler Interface.

IN THIS SECTION:
RegistrationHandler Methods
Storing User Information and Getting Access Tokens
Auth.RegistrationHandler Example Implementation
Auth.RegistrationHandler Error Example
This example implements the Auth.RegistrationHandler interface and shows how to use a custom exception to display
an error message in the URL of the page. If you don’t use a custom exception, the error code and description appear in the URL and
the error description appears on the page.

RegistrationHandler Methods
The following are methods for RegistrationHandler.

IN THIS SECTION:
createUser(portalId, userData)
Returns a User object using the specified portal ID and user information from the third party, such as the username and email address.
The User object corresponds to the third party’s user information. It can be a new user that hasn’t been inserted in your org’s database,
or it can represent an existing user record in the database. If it’s a new User object, Salesforce inserts a user record for you.
updateUser(userId, portalId, userData)
Updates the specified user’s information. This method is called if the user has logged in before with the authentication provider and
then logs in again.

createUser(portalId, userData)
Returns a User object using the specified portal ID and user information from the third party, such as the username and email address.
The User object corresponds to the third party’s user information. It can be a new user that hasn’t been inserted in your org’s database,
or it can represent an existing user record in the database. If it’s a new User object, Salesforce inserts a user record for you.

177
Apex Reference Guide RegistrationHandler Interface

Signature
public User createUser(ID portalId, Auth.UserData userData)

Parameters
portalId
Type: ID
userData
Type: Auth.UserData

Return Value
Type: User

Usage
The portalID value can be null or an empty key if there’s no portal configured with this provider.

updateUser(userId, portalId, userData)


Updates the specified user’s information. This method is called if the user has logged in before with the authentication provider and
then logs in again.

Signature
public Void updateUser(ID userId, ID portalId, Auth.UserData userData)

Parameters
userId
Type: ID
portalId
Type: ID
userData
Type: Auth.UserData

Return Value
Type: Void

Usage
The portalID value can be null or an empty key if there's no portal configured with this provider.

Storing User Information and Getting Access Tokens


The Auth.UserData class is used to store user information for Auth.RegistrationHandler. The third-party identity
provider can send back a large collection of data about the user, including their username, email address, locale, and more. The Salesforce

178
Apex Reference Guide RegistrationHandler Interface

authentication provider framework converts this data into a common format with the Auth.UserData class and then sendsit to
the registration handler.

Note: If you use a predefined Salesforce authentication provider, Salesforce constructs the Auth.UserData object for you.
If you use a custom authentication provider plug-in, it's up to you to determine how you store information in the Auth.UserData
object.
If the registration handler wants to use the rest of the data, the Auth.UserData class has an attributeMap variable. The
attribute map is a map of strings (Map<String, String>) for the raw values of all the data from the third party. Because the map
is <String, String>, values that the third party returns that aren't strings (like an array of URLs or a map) are converted into an
appropriate string representation. The map includes everything returned by the third-party authentication provider, including the items
automatically converted into the common format.
To learn about Auth.UserData properties, see Auth.UserData Class.

Note: You can only perform DML operations on additional sObjects in the same transaction with User objects under certain
circumstances. For more information, see sObjects That Cannot Be Used Together in DML Operations.
For all authentication providers except Janrain, after a user is authenticated using a provider, the access token associated with that
provider for this user can be obtained in Apex using the Auth.AuthToken Apex class. Auth.AuthToken provides two methods
to retrieve access tokens. One is getAccessToken, which obtains a single access token. Use this method if the user ID is mapped
to a single third-party user. If the user ID is mapped to multiple third-party users, use getAccessTokenMap, which returns a map
of access tokens for each third-party user. For more information about authentication providers, see Authentication Providers in Salesforce
Help.
When using Janrain as an authentication provider, you must use the Janrain accessCredentials dictionary values to retrieve the
access token or its equivalent. Only some providers supported by Janrain provide an access token, while other providers use other fields.
The Janrain accessCredentials fields are returned in the attributeMap variable of the Auth.UserData class. See the
Janrain auth_info documentation for more information on accessCredentials.

Note: Not all Janrain account types return accessCredentials. Sometimes you must change your account type to receive
the information.
To learn about the Auth.AuthToken methods, see Auth.AuthToken Class.

User Information in the ID Token and User Info Response


Some identity providers send additional user information in an ID token or in a user info response. To extract user information from these
responses, there are some extra steps.
An ID token is formatted as a JWT and includes information about the authenticated user. If the identity provider sends an ID token,
Salesforce stores the full encoded JWT in the idToken property. Salesforce also stores the decoded JWT payload of the ID token in
the idTokenJSONString property.
Salesforce doesn't validate the ID token. To validate it, use methods in the Auth.JWTUtil class and pass in the encoded JWT stored
in the idToken property. The methods in the Auth.JWTUtil class all return an instance of the Auth.JWT object.
Once you validate the JWT, you can use methods in the Auth.JWT class to access specific claims. For example, the Apex code in this
snippet validates the ID token using a public keys endpoint from the identity provider and then retrieves the value of an email claim
stored in the token.
Auth.JWT jwt = Auth.JWTUtil.validateJWTWithKeysEndpoint(userdata.idToken, keysEndpoint,
true);

// Retrieve email claim from id token

179
Apex Reference Guide RegistrationHandler Interface

String email = (String) jwt.getAdditionalClaims().get('email');


System.debug(email);

Alternatively, to access specific claims in the idTokenJSONString property, you can deserialize the JSON string and then write
code to retrieve the claim you want. To deserialize the idTokenJSONString, use the JSON.deserialize (jsonString,
apexType) method in the System.JSON class.
The user info response, if returned by the identity provider, is also a JSON object that has been serialized into a string. The user info
response is stored in the userInfoJSONString property. You can use the JSON.deserialize (jsonString,
apexType) method to deserialize the user info response so that you can retrieve specific information.
This example snippet creates a custom class to store the user info response. It then deserializes the user info response in the
userInfoJSONString into this custom class structure.

public class UserInfoResponse {


public String preferred_username;
public String email;
public Boolean email_verified;
public String given_name;
public String family_name;
public String locale;
}

UserInfoResponse userInfo =
(UserInfoResponse)System.JSON.deserialize(userData.userInfoJSONString,
UserInfoResponse.class);
System.debug(userInfo.email);

Auth.RegistrationHandler Example Implementation


This example implements the Auth.RegistrationHandler interface that creates as well as updates a standard user based on
data provided by the authentication provider. Error checking has been omitted to keep the example simple.
global class StandardUserRegistrationHandler implements Auth.RegistrationHandler{
global User createUser(Id portalId, Auth.UserData data) {
User u = new User();
Profile p = [SELECT Id FROM profile WHERE name='Standard User'];
u.Username = data.username + '@salesforce.com';
u.Email = data.email;
u.LastName = data.lastName;
u.FirstName = data.firstName;
String alias = data.username;
if(alias.length() > 8) {
alias = alias.substring(0, 8);
}
u.Alias = alias;
u.LanguageLocaleKey = data.attributeMap.get('language');
u.LocaleSidKey = data.locale;
u.EmailEncodingKey = 'UTF-8';
u.TimeZoneSidKey = 'America/Los_Angeles';
u.ProfileId = p.Id;
return u;
}

global void updateUser(Id userId, Id portalId, Auth.UserData data) {

180
Apex Reference Guide RegistrationHandler Interface

User u = new User(id=userId);


u.Username = data.username + '@salesforce.com';
u.Email = data.email;
u.LastName = data.lastName;
u.FirstName = data.firstName;
String alias = data.username;
if(alias.length() > 8) {
alias = alias.substring(0, 8);
}
u.Alias = alias;
u.LanguageLocaleKey = data.attributeMap.get('language');
u.TimeZoneSidKey = data.locale;
update(u);
}
}

The following example tests the above code.


@isTest
private class StandardUserRegistrationHandlerTest {
static testMethod void testCreateAndUpdateUser() {
StandardUserRegistrationHandler handler = new StandardUserRegistrationHandler();
Auth.UserData sampleData = new Auth.UserData('testId', 'testFirst', 'testLast',
'testFirst testLast', '[email protected]', null, 'testuserlong', 'en_US',
'facebook',
null, new Map<String, String>{'language' => 'en_US'});
User u = handler.createUser(null, sampleData);
System.assertEquals('[email protected]', u.username);
System.assertEquals('[email protected]', u.email);
System.assertEquals('testLast', u.lastName);
System.assertEquals('testFirst', u.firstName);
System.assertEquals('testuser', u.alias);
insert(u);
String uid = u.id;

sampleData = new Auth.UserData('testNewId', 'testNewFirst', 'testNewLast',


'testNewFirst testNewLast', '[email protected]', null, 'testnewuserlong',
'en_US', 'facebook',
null, new Map<String, String>{});
handler.updateUser(uid, null, sampleData);

User updatedUser = [SELECT username, email, firstName, lastName, alias FROM user WHERE
id=:uid];
System.assertEquals('[email protected]', updatedUser.username);
System.assertEquals('[email protected]', updatedUser.email);
System.assertEquals('testNewLast', updatedUser.lastName);
System.assertEquals('testNewFirst', updatedUser.firstName);
System.assertEquals('testnewu', updatedUser.alias);
}
}

181
Apex Reference Guide SamlJitHandler Interface

Auth.RegistrationHandler Error Example


This example implements the Auth.RegistrationHandler interface and shows how to use a custom exception to display an
error message in the URL of the page. If you don’t use a custom exception, the error code and description appear in the URL and the
error description appears on the page.
To limit this example to the custom exception, some code was omitted.
global class RegHandler implements Auth.RegistrationHandler {

class RegHandlerException extends Exception {}

global User createUser(Id portalId, Auth.UserData data){


List<Profile> profiles = [SELECT Id, Name, UserType FROM Profile WHERE Name =
'Power User'];
Profile profile = profiles.isEmpty() ? null : profiles[0];
if(profile==null)
throw new RegHandlerException('Cannot find the profile. For help, contact
your administrator.');
...
}

global void updateUser(Id userId, Id portalId, Auth.UserData data){


User u = new User(id=userId);
u.lastName = data.lastName;
u.firstName = data.firstName;
update(u);
}
}

SamlJitHandler Interface
Use this interface to control and customize Just-in-Time user provisioning logic during SAML single sign-on.

Namespace
Auth

Usage
To use custom logic for user provisioning during SAML single sign-on, you must create a class that implements
Auth.SamlJitHandler. This allows you to incorporate organization-specific logic (such as populating custom fields) when users
log in to Salesforce with single sign-on. Keep in mind that your class must perform the logic of creating and updating user data as
appropriate, including any associated account and contact records.
In Salesforce, you specify your class that implements this interface in the SAML JIT Handler field in SAML Single Sign-On Settings.
Make sure that the user you specify to run the class has “Manage Users” permission.

IN THIS SECTION:
SamlJitHandler Methods
SamlJitHandler Example Implementation

182
Apex Reference Guide SamlJitHandler Interface

SamlJitHandler Methods
The following are methods for SamlJitHandler.

IN THIS SECTION:
createUser(samlSsoProviderId, communityId, portalId, federationId, attributes, assertion)
Returns a User object using the specified Federation ID. The User object corresponds to the user information. This object can be a
new user that hasn’t been inserted in the database or an existing user record in the database.
updateUser(userId, samlSsoProviderId, communityId, portalId, federationId, attributes, assertion)
Updates the specified user’s information. This method is called if the user has logged in before with SAML single sign-on and then
logs in again, or if your application is using the Existing User Linking URL.

createUser(samlSsoProviderId, communityId, portalId, federationId, attributes,


assertion)
Returns a User object using the specified Federation ID. The User object corresponds to the user information. This object can be a new
user that hasn’t been inserted in the database or an existing user record in the database.

Signature
public User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String
federationId, Map<String,String> attributes, String assertion)

Parameters
samlSsoProviderId
Type: Id
The ID of the SamlSsoConfig standard object.
communityId
Type: Id
The ID of the Experience Cloud site. This parameter can be null if you’re not creating an Experience Cloud user.
portalId
Type: Id
The ID of the portal. This parameter can be null if you’re not creating a portal user.
federationId
Type: String
The ID Salesforce expects to be used for this user.
attributes
Type: Map<String,String>
All attributes in the SAML assertion that were added to the default assertion; for example, custom attributes. Attributes are
case-sensitive.
If the assertion is encrypted, the attribute map contains a decrypted assertion stored as a value with the key
Sfdc.SamlAssertion.

183
Apex Reference Guide SamlJitHandler Interface

assertion
Type: String
The default SAML assertion, base-64 encoded.
If the assertion is encrypted, this parameter is also encrypted. To access the decrypted assertion, see the Sfdc.SamlAssertion
key in the attribute map.

Return Value
Type: User
A User sObject.

Usage
The communityId and portalId parameter values can be null or the associated keys can be empty if there’s no Experience
Cloud site or portal configured with this organization.

updateUser(userId, samlSsoProviderId, communityId, portalId, federationId,


attributes, assertion)
Updates the specified user’s information. This method is called if the user has logged in before with SAML single sign-on and then logs
in again, or if your application is using the Existing User Linking URL.

Signature
public void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId,
String federationId, Map<String,String> attributes, String assertion)

Parameters
userId
Type: Id
The ID of the Salesforce user.
samlSsoProviderId
Type: Id
The ID of the SamlSsoConfig object.
communityId
Type: Id
The ID of the Experience Cloud site. This type can be null if you’re not updating an Experience Cloud user.
portalId
Type: Id
The ID of the portal. This type can be null if you’re not updating a portal user.
federationId
Type: String
The ID Salesforce expects to be used for this user.

184
Apex Reference Guide SamlJitHandler Interface

attributes
Type: Map<String,String>
All attributes in the SAML assertion that were added to the default assertion; for example, custom attributes. Attributes are
case-sensitive.
If the assertion is encrypted, the attribute map also contains a decrypted assertion stored as a value with the key
Sfdc.SamlAssertion.
assertion
Type: String
The default SAML assertion, base-64 encoded.
If the assertion is encrypted, this parameter is also encrypted. To access the decrypted assertion, see the Sfdc.SamlAssertion
key in the attribute map.

Return Value
Type: void

SamlJitHandler Example Implementation


This is an example implementation of the Auth.SamlJitHandler interface. This code uses private methods to handle accounts
and contacts (handleContact() and handleAccount()), which aren’t included in this example.
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes,
String federationIdentifier, boolean isStandard) {
if(create && attributes.containsKey('User.Username')) {
u.Username = attributes.get('User.Username');
}
if(create) {
if(attributes.containsKey('User.FederationIdentifier')) {
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else {
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId')) {
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId];
u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId')) {
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id;
}
if(attributes.containsKey('User.Phone')) {
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email')) {
u.Email = attributes.get('User.Email');

185
Apex Reference Guide SessionManagement Class

//More attributes here - removed for length

//Handle custom fields here

if(!create) {
update(u);
}
}

private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId,


Id portalId,
String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null) {
String account = handleAccount(create, u, attributes);
handleContact(create, account, u, attributes);
handleUser(create, u, attributes, federationIdentifier, false);
} else {
handleUser(create, u, attributes, federationIdentifier, true);
}
}

global User createUser(Id samlSsoProviderId, Id communityId, Id portalId,


String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User();
handleJit(true, u, samlSsoProviderId, communityId, portalId,
federationIdentifier, attributes, assertion);
return u;
}

global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId,


String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = [SELECT Id FROM User WHERE Id=:userId];
handleJit(false, u, samlSsoProviderId, communityId, portalId,
federationIdentifier, attributes, assertion);
}
}

SessionManagement Class
Contains methods for verifying users’ identity, creating custom login flows, customizing security levels, and defining trusted IP ranges
for a current session.

Namespace
Auth

IN THIS SECTION:
SessionManagement Methods

186
Apex Reference Guide SessionManagement Class

SessionManagement Methods
The following are methods for SessionManagement. All methods are static. Use these methods to customize your user identity
verification flows, manage the use of time-based one-time password (TOTP) apps like Google Authenticator, or create custom login
flows. Other methods validate a user’s incoming IP address against trusted IP range settings for an organization or profile.

IN THIS SECTION:
finishLoginDiscovery(method, userId)
Finishes the My Domain Login Discovery login process.
finishLoginFlow()
Finish the Visualforce Page login flow process, and redirect the user to the default home page.
finishLoginFlow(startUrl)
Finish the Visualforce Page login flow process, and redirect the user to the specified start URL.
generateVerificationUrl(policy, description, destinationUrl)
Initiates a user identity verification flow with the verification method that the user registered with, and returns a URL to the identity
verification screen. For example, if you have a custom Visualforce page that displays sensitive account details, you can prompt the
user to verify identity before viewing it.
getCurrentSession()
Returns a map of attributes for the current session.
getLightningLoginEligibility(userId)
Returns the eligibility status for a user who’s logging in with Lightning Login when you set up your org with My Domain and use
the Login Discovery page type. Use this method to redirect the user to a custom login flow. For example, use after a login attempt
to redirect the user to password flow if the user is ineligible for Lightning Login.
getQrCode()
Returns a map containing a URL to a quick response (QR) code and a time-based one-time password (TOTP) shared secret to configure
authenticator apps or devices for multi-factor authentication (MFA).
getRequiredSessionLevelForProfile(profileId)
Indicates the required login security session level for the given profile.
ignoreForConcurrentSessionLimit(sessions)
This method is reserved for internal Salesforce use.
inOrgNetworkRange(ipAddress)
Indicates whether the given IP address is within the organization's trusted IP range according to the organization's Network Access
settings.
isIpAllowedForProfile(profileId, ipAddress)
Indicates whether the given IP address is within the trusted IP range for the given profile.
setSessionLevel(level)
Sets the user's current session security level.
validateTotpTokenForKey(sharedKey, totpCode)
Deprecated. Use validateTotpTokenForKey(totpSharedKey, totpCode, description) instead.
validateTotpTokenForKey(totpSharedKey, totpCode, description)
Indicates whether a time-based one-time password (TOTP) code (token) is valid for the given shared key.

187
Apex Reference Guide SessionManagement Class

validateTotpTokenForUser(totpCode)
Deprecated. Use validateTotpTokenForUser(totpCode, description) instead.
validateTotpTokenForUser(totpCode, description)
Indicates whether a time-based one-time password (TOTP) code (token) is valid for the current user.
verifyDeviceFlow(userCode, startUrl)
Verifies the user code entered during the device authentication flow and redirects users to the OAuth approval page. If users aren’t
logged in, they must log in. After successful login, users are prompted to allow the device to access Salesforce data.

finishLoginDiscovery(method, userId)
Finishes the My Domain Login Discovery login process.

Signature
public static System.PageReference finishLoginDiscovery(Auth.LoginDiscoveryMethod
method, Id userId)

Parameters
method
Type: Auth.LoginDiscoveryMethod LoginDiscoveryMethod Enum
Verification method used with My Domain Login Discovery.
userId
Type: Id
ID used to log in the user. The user must be active.

Return Value
Type: System.PageReference

Usage
Include this method when implementing the MyDomainLoginDiscoveryHandler interface to direct users to an authentication
mechanism, and then log them in. If users enter a username in the login page, they are sent to the password page for authentication.
If users are enrolled in Lightning Login, they are directed to the Salesforce Authenticator to authenticate. If users are SSO-enabled, they
are sent to the suitable identity provider (IdP) to authenticate.
The calling user requires Manage Users permission. If the user passed in is frozen or inactive, the method throws an exception.
After implementing the MyDomainLoginDiscoveryHandler interface, register the Login Discovery handler from the My
Domain Setup page. Under Authentication Configuration, select this handler from the list of Apex classes.

finishLoginFlow()
Finish the Visualforce Page login flow process, and redirect the user to the default home page.

Signature
public static System.PageReference finishLoginFlow()

188
Apex Reference Guide SessionManagement Class

Return Value
Type: System.PageReference

Usage
Include this method in the Apex controller of the Visualforce Page login flow when creating login flows programmatically. This method
indicates that the login flow is finished and redirects the user to the Experience Cloud site’s default home page. The login process runs
in a restricted session until users complete the process. Calling this method indicates that the login flow is complete, lifts the restriction,
and gives users full access to the Experience Cloud site.

finishLoginFlow(startUrl)
Finish the Visualforce Page login flow process, and redirect the user to the specified start URL.

Signature
public static System.PageReference finishLoginFlow(String startUrl)

Parameters
startUrl
Type: String
Path to the page that users see when they access the Experience Cloud site.

Return Value
Type: System.PageReference

Usage
Include this method in the Apex controller of the Visualforce Page login flow when creating login flows programmatically. This method
indicates that the login flow is finished and redirects the user to the specified location in the Experience Cloud site. The login process
runs in a restricted session until users complete the process. Calling this method indicates that the login flow is complete, lifts the
restriction, and gives users full access to the Experience Cloud site.

generateVerificationUrl(policy, description, destinationUrl)


Initiates a user identity verification flow with the verification method that the user registered with, and returns a URL to the identity
verification screen. For example, if you have a custom Visualforce page that displays sensitive account details, you can prompt the user
to verify identity before viewing it.

Signature
public static String generateVerificationUrl(Auth.VerificationPolicy policy, String
description, String destinationUrl)

Parameters
policy
Type: Auth.VerificationPolicy

189
Apex Reference Guide SessionManagement Class

The session security policy required to initiate identity verification for the user’s session. For example, if the policy is set to High
Assurance level of session security, and the user’s current session has the standard level of session security, the user’s session is raised
to high assurance after successful verification of identity. In the Setup user interface, this value is shown in the Triggered By column
of Identity Verification History.
description
Type: String
The custom description that describes the activity requiring identity verification; for example, “Complete purchase and check out”.
This text appears to users when they verify their identity in Salesforce and, if they use Salesforce Authenticator version 2 or later, in
the Salesforce Authenticator mobile app. In addition, in the Setup user interface, this text is shown in the Activity Message column
of Identity Verification History.
destinationUrl
Type: String
The relative or absolute Salesforce URL that you want to redirect the user to after identity verification—for example, /apex/mypage.
The user is redirected to destinationUrl when the identity verification flow is complete, regardless of success. For example,
if a user chooses to not respond to the identity challenge and cancels it, the user is still redirected to destinationUrl. As a
best practice, ensure that your code for this page manually checks that the security policy was satisfied (and the user didn’t just
manually type the URL in the browser). For example, if the policy is High Assurance, the target page checks that the user's session
is high assurance before allowing access.

Return Value
Type: String
The URL where the user is redirected to verify identity.

Usage
• If the user is already registered to confirm identity using a time-based one-time password (TOTP), then the user is redirected to the
one-time password identity verification flow and asked to provide a code.
• If the user isn’t registered with any verification method (such as one-time password or Salesforce Authenticator version 2 or later),
the user is prompted to download and verify identity using Salesforce Authenticator. The user can also choose a different verification
method.

getCurrentSession()
Returns a map of attributes for the current session.

Signature
public static Map<String, String> getCurrentSession()

Return Value
Type: Map<String, String>

190
Apex Reference Guide SessionManagement Class

Usage
The map includes a ParentId value, which is the 18-character ID for the parent session, if one exists (for example, if the current
session is for a canvas app). If the current session doesn’t have a parent, this value is null. The map also includes the LogoutUrl
assigned to the current session.
If you create an Apex test method that calls this method, the test fails with an error such as, “Unexpected Exception: Current session
unavailable." An error occurs because there isn’t a session in the context through which the test is being run.
When a session is reused, Salesforce updates the LoginHistoryId with the value from the most recent login.

Example
The following example shows the name-value pairs in a map returned by getCurrentSession(). Note that UsersId includes
an “s” in the name to match the name of the corresponding field in the AuthSession object.
{
SessionId=0Ak###############,
UserType=Standard,
ParentId=0Ak###############,
NumSecondsValid=7200,
LoginType=SAML Idp Initiated SSO,
LoginDomain=null,
LoginHistoryId=0Ya###############,
[email protected],
CreatedDate=Wed Jul 30 19:09:29 GMT 2014,
SessionType=Visualforce,
LastModifiedDate=Wed Jul 30 19:09:16 GMT 2014,
LogoutUrl=https://google.com,
SessionSecurityLevel=STANDARD,
UsersId=005###############,
SourceIp=1.1.1.1
}

getLightningLoginEligibility(userId)
Returns the eligibility status for a user who’s logging in with Lightning Login when you set up your org with My Domain and use the
Login Discovery page type. Use this method to redirect the user to a custom login flow. For example, use after a login attempt to redirect
the user to password flow if the user is ineligible for Lightning Login.

Signature
public static Auth.LightningLoginEligibility getLightningLoginEligibility(Id userId)

Parameters
userId
Type: Id
ID of the user who is logging in.

Return Value
Type: Auth.LightningLoginEligibility

191
Apex Reference Guide SessionManagement Class

Returns the current eligibility status.

Example
Auth.LightningLoginEligibility eligibility =
Auth.SessionManagement.getLightningLoginEligibility(id);
if (eligibility == Auth.LightningLoginEligibility.ELIGIBLE) {
// success
}

getQrCode()
Returns a map containing a URL to a quick response (QR) code and a time-based one-time password (TOTP) shared secret to configure
authenticator apps or devices for multi-factor authentication (MFA).

Signature
public static Map<String, String> getQrCode()

Return Value
Type: Map<String, String>

Usage
The QR code encodes the returned secret as well as the current user's username. The keys are qrCodeUrl and secret. Calling this
method does not change any state for the user, nor does it read any state from the user. This method returns a brand new secret every
time it is called, does not save that secret anywhere, and does not validate the TOTP token. The admin must explicitly save the values
for the user after verifying a TOTP token with the secret.
The secret is a base32-encoded string of a 20-byte shared key.

Example
The following is an example of how to request the QR code.
public String getGetQRCode() {
return getQRCode();
}
public String getQRCode() {
Map<String, String> codeResult = Auth.SessionManagement.getQrCode();
String result = 'URL: '+codeResult.get('qrCodeUrl') + ' SECRET: ' +
codeResult.get('secret');
return result;
}

The following is an example of a returned map.


{qrCodeUrl=https://www.salesforce.com/secur/qrCode?w=200&h=200&t=tf&u=user%0000000000.com&s=AAAAA7B5BBBB5AAAAAAA66BBBB,

secret=AAAAA7B5AAAAAA5BBBBBBBBB66AAA}

192
Apex Reference Guide SessionManagement Class

getRequiredSessionLevelForProfile(profileId)
Indicates the required login security session level for the given profile.

Signature
public static Auth.SessionLevel getRequiredSessionLevelForProfile(String profileId)

Parameters
profileId
Type: String
The 15-character profile ID.

Return Value
Type: Auth.SessionLevel
The session security level required at login for the profile with the ID profileId. You can customize the assignment of each level in
Session Settings. For example, you can set the High Assurance level to apply only to users who authenticated with multi-factor
authentication (MFA) or through a specific identity provider.

ignoreForConcurrentSessionLimit(sessions)
This method is reserved for internal Salesforce use.

Signature
public static Map<String,String> ignoreForConcurrentSessionLimit(Object sessions)

Parameters
sessions
Type: Object

Return Value
Type: Map<String, String>

inOrgNetworkRange(ipAddress)
Indicates whether the given IP address is within the organization's trusted IP range according to the organization's Network Access
settings.

Signature
public static Boolean inOrgNetworkRange(String ipAddress)

193
Apex Reference Guide SessionManagement Class

Parameters
ipAddress
Type: String
The IP address to validate.

Return Value
Type: Boolean

Usage
If a trusted IP range is not defined, this returns false, and throws an exception if the IP address is not valid.

Trusted IP Range Exists? User is in the Trusted IP Range? Return Value


Yes Yes true

Yes No false

No N/A false

isIpAllowedForProfile(profileId, ipAddress)
Indicates whether the given IP address is within the trusted IP range for the given profile.

Signature
public static Boolean isIpAllowedForProfile(String profileId, String ipAddress)

Parameters
profileId
Type: String
The 15-character alphanumeric string for the current user’s profile ID.
ipAddress
Type: String
The IP address to validate.

Return Value
Type: Boolean

Usage
If a trusted IP range is not defined, this returns true, and throws an exception if the IP address is not valid or if the profile ID is not valid.

Trusted IP Range Exists? User is in the Trusted IP Range? Return Value


Yes Yes true

194
Apex Reference Guide SessionManagement Class

Trusted IP Range Exists? User is in the Trusted IP Range? Return Value


Yes No false

No N/A true

setSessionLevel(level)
Sets the user's current session security level.

Signature
public static Void setSessionLevel(Auth.SessionLevel level)

Parameters
level
Type: Auth.SessionLevel
The session security level to assign to the user. The meaning of each level can be customized in the Session Settings for each
organization, such as setting the High Assurance level to apply only to users who authenticated with multi-factor authentication
(MFA) or through a specific identity provider.

Return Value
Type: Void

Usage
This setting affects the session level of all sessions associated with the current session, such as Visualforce or UI access.
If you create an Apex test method that calls this method, the test fails with an error such as, “Unexpected Exception: Current session
unavailable." An error occurs because there isn’t a session in the context through which the test is being run.

Example
The following is an example class for setting the session level.
public class RaiseSessionLevel{
public void setLevelHigh() {
Auth.SessionManagement.setSessionLevel(Auth.SessionLevel.HIGH_ASSURANCE);
}
public void setLevelStandard() {
Auth.SessionManagement.setSessionLevel(Auth.SessionLevel.STANDARD);
}
}

validateTotpTokenForKey(sharedKey, totpCode)
Deprecated. Use validateTotpTokenForKey(totpSharedKey, totpCode, description) instead.

195
Apex Reference Guide SessionManagement Class

Signature
public static Boolean validateTotpTokenForKey(String sharedKey, String totpCode)

Parameters
sharedKey
Type: String
The shared (secret) key. The sharedKey must be a base32-encoded string of a 20-byte shared key.
totpCode
Type: String
The time-based one-time password (TOTP) code to validate.

Return Value
Type: Boolean

Usage
If the key is invalid or doesn’t exist, this method throws an invalid parameter value exception or a no data found exception, respectively.
If the current user exceeds the maximum of 10 token validation attempts, this method throws a security exception.

validateTotpTokenForKey(totpSharedKey, totpCode, description)


Indicates whether a time-based one-time password (TOTP) code (token) is valid for the given shared key.

Signature
public static Boolean validateTotpTokenForKey(String totpSharedKey, String totpCode,
String description)

Parameters
totpSharedKey
Type: String
The shared (secret) key. The totpSharedKey must be a base32-encoded string of a 20-byte shared key.
totpCode
Type: String
The time-based one-time password (TOTP) code to validate.
description
Type: String
The custom description that describes the activity requiring identity verification; for example, “Complete purchase and check out”.
In the Setup user interface, this text is shown in the Activity Message column of Identity Verification History. The description
must be 128 characters or fewer. If you provide a value that’s longer, it’s truncated to 128 characters.

Return Value
Type: Boolean

196
Apex Reference Guide SessionManagement Class

Usage
If the key is invalid or doesn’t exist, this method throws an invalid parameter value exception or a no data found exception, respectively.
If the current user exceeds the maximum of 10 token validation attempts, this method throws a security exception.

validateTotpTokenForUser(totpCode)
Deprecated. Use validateTotpTokenForUser(totpCode, description) instead.

Signature
public static Boolean validateTotpTokenForUser(String totpCode)

Parameters
totpCode
Type: String
The time-based one-time password (TOTP) code to validate.

Return Value
Type: Boolean

Usage
If the current user does not have a TOTP code, this method throws an exception. If the current user has attempted too many validations,
this method throws an exception.

validateTotpTokenForUser(totpCode, description)
Indicates whether a time-based one-time password (TOTP) code (token) is valid for the current user.

Signature
public static Boolean validateTotpTokenForUser(String totpCode, String description)

Parameters
totpCode
Type: String
The time-based one-time password (TOTP) code to validate.
description
Type: String
The custom description that describes the activity requiring identity verification; for example, “Complete purchase and check out”.
This text appears to users when they verify their identity in Salesforce and, if they use Salesforce Authenticator version 2 or later, in
the Salesforce Authenticator mobile app. In addition, in the Setup user interface, this text is shown in the Activity Message column
of Identity Verification History. The description must be 128 characters or fewer. If you provide a value that’s longer, it’s
truncated to 128 characters.

197
Apex Reference Guide SessionLevel Enum

Return Value
Type: Boolean

Usage
If the current user does not have a TOTP code, or if the current user has attempted too many validations, this method throws an exception.

verifyDeviceFlow(userCode, startUrl)
Verifies the user code entered during the device authentication flow and redirects users to the OAuth approval page. If users aren’t
logged in, they must log in. After successful login, users are prompted to allow the device to access Salesforce data.

Signature
public static System.PageReference verifyDeviceFlow(String userCode, String startUrl)

Parameters
userCode
Type: String
Human-readable user code provided to the user by Salesforce. The user must enter this code at the verification URL to approve
device access to Salesforce data.
startURL
Type: String
The URL for the page that the user is redirected to after successful login and approval of the device to access Salesforce data. If you
don’t specify a start URL, the user is redirected to the Home page.

Return Value
Type:System.PageReference

Usage
Include this method in the Apex controller when creating a custom Visualforce User Code Verification page for the OAuth 2.0 device
authentication flow. This method verifies the user code, prompts the user to log in as needed, and prompts the user to allow the device
access to Salesforce data. Upon successful verification and authentication, the user is redirected to the page defined by the start URL.

SessionLevel Enum
An Auth.SessionLevel enum value is used by the SessionManagement.setSessionLevel method.

Namespace
Auth

198
Apex Reference Guide TokenValidationResult Class

Enum Values
Value Description
LOW The user’s security level for the current session meets the lowest requirements.

Note: This low level is not available, nor used, in the Salesforce UI. User
sessions through the Salesforce UI are either standard or high assurance. You
can set this level using the API, but users assigned this level will experience
unpredictable and reduced functionality in their Salesforce organization.

STANDARD The user’s security level for the current session meets the Standard requirements
set in the current organization Session Security Levels.

HIGH_ASSURANCE The user’s security level for the current session meets the High Assurance
requirements set in the current organization Session Security Levels.

Usage
With session-level security, you control user access to features that support it, such as connected apps and reporting. For example, you
can customize an organization’s Session Settings to require users to log in with multi-factor authentication (MFA) to get a High Assurance
session. Then, you can restrict access to a specific connected app by requiring a High Assurance session level in the settings for the
connected app.

TokenValidationResult Class
Contains methods that describe the result of the token validation performed by a token exchange handler using the
validateIncomingToken method in the Auth.Oauth2TokenExchangeHandler class during the OAuth 2.0 token
exchange flow.

Namespace
Auth

Usage
For a full example implementation that shows how to get information from the TokenValidationResult class, see OAuth 2.0
Token Exchange Handler Examples.

Example
Here’s is an example of the Auth.TokenValidationResult class.
global class TokenValidationResult {
global TokenValidationResult(Boolean valid) { this.isValid = valid; }

global TokenValidationResult(Boolean isValid, Object data, Auth.UserData userData,


String token, Auth.OAuth2TokenExchangeType tokenType, String customErrorMsg) {

this.isValid = isValid;

199
Apex Reference Guide TokenValidationResult Class

this.data = data;
this.userData = userData;
this.token = token;
this.tokenType = tokenType;
this.customErrorMsg = customErrorMsg;

global Boolean isValid;


global Object data;
global Auth.UserData userData;
global String token;
global Auth.OAuth2TokenExchangeType tokenType; //Enum
global String customErrorMsg; //Custom error message that’s returned to the client if
token validation fails

global Boolean isValid(){


return isValid;
}
global Object getData(){
return data;
}
global Auth.UserData getUserData(){
return userData;
}
global String getToken(){
return token;
}
global OAuth2TokenExchangeType getTokenType(){
return tokenType;
}
global String getCustomErrorMessage(){
return customErrorMsg;
}
}

IN THIS SECTION:
TokenValidationResult Constructors
TokenValidationResult Properties
TokenValidationResult Methods

TokenValidationResult Constructors
The following are constructors for TokenValidationResult.

IN THIS SECTION:
TokenValidationResult(isValid, data, userData, token, tokenType, customErrorMsg)
Creates an instance of the Auth.TokenValidationResult class to describe the result of token validation performed during
the OAuth 2.0 token exchange flow.

200
Apex Reference Guide TokenValidationResult Class

TokenValidationResult(valid)
Creates an instance of the Auth.TokenValidationResult class to describe a valid token validation result during the OAuth
2.0 token exchange flow.

TokenValidationResult(isValid, data, userData, token, tokenType,


customErrorMsg)
Creates an instance of the Auth.TokenValidationResult class to describe the result of token validation performed during
the OAuth 2.0 token exchange flow.

Signature
public TokenValidationResult(Boolean isValid, Object data, Auth.UserData userData,
String token, Auth.OAuth2TokenExchangeType tokenType, String customErrorMsg)

Parameters
isValid
Type: Boolean
If true, the token is valid.
data
Type: Object
Stores custom data that isn’t stored in userData.
userData
Type: Auth.UserData
Stores information about a Salesforce user.
token
Type: String
The token from the external identity provider.
tokenType
Type: Auth.OAuth2TokenExchangeType
The type of token from the external identity provider.
customErrorMsg
Type: String
A custom error message that’s returned if the token validation fails.

TokenValidationResult(valid)
Creates an instance of the Auth.TokenValidationResult class to describe a valid token validation result during the OAuth
2.0 token exchange flow.

Signature
public TokenValidationResult(Boolean valid)

201
Apex Reference Guide TokenValidationResult Class

Parameters
valid
Type: Boolean
Indicates a valid token validation result.

TokenValidationResult Properties
The following are properties for TokenValidationResult.

IN THIS SECTION:
customErrorMsg
A custom error message that’s returned if token validation fails.
data
Contains information about the user that isn’t stored in the Auth.UserData class, such as information obtained via callouts to
the external identity provider.
isValid
Indicates whether the token is valid or not, based on the custom validation logic in your token exchange handler.
token
The token from the external identity provider.
tokenType
The type of token from the external identity provider. It can be an access token, refresh token, ID token, SAML 2.0 assertion, or a JSON
Web Token (JWT).
userData
Information about the user that’s obtained from the identity provider’s token.

customErrorMsg
A custom error message that’s returned if token validation fails.

Signature
public String customErrorMsg {get; set;}

Property Value
Type: String

data
Contains information about the user that isn’t stored in the Auth.UserData class, such as information obtained via callouts to the
external identity provider.

Signature
public Object data {get; set;}

202
Apex Reference Guide TokenValidationResult Class

Property Value
Type: Object

isValid
Indicates whether the token is valid or not, based on the custom validation logic in your token exchange handler.

Signature
public Boolean isValid {get; set;}

Property Value
Type: Boolean

token
The token from the external identity provider.

Signature
public String token {get; set;}

Property Value
Type: String

tokenType
The type of token from the external identity provider. It can be an access token, refresh token, ID token, SAML 2.0 assertion, or a JSON
Web Token (JWT).

Signature
public Auth.OAuth2TokenExchangeType tokenType {get; set;}

Property Value
Type: Auth.OAuth2TokenExchangeType

userData
Information about the user that’s obtained from the identity provider’s token.

Signature
public Auth.UserData userData {get; set;}

203
Apex Reference Guide TokenValidationResult Class

Property Value
Type: Auth.UserData

TokenValidationResult Methods
The following are methods for TokenValidationResult.

IN THIS SECTION:
getCustomErrorMessage()
Retrieves the CustomErrorMsg that’s returned when token validation fails.
getData()
Retrieves data from the identity provider token. This data can include custom data that isn’t stored in the userData property.
getToken()
Retrieves the token that was passed from the external identity provider.
getTokenType()
Retrieves the type of token that was passed from the external identity provider.
getUserData()
Retrieves information about the user. The user information can be obtained from the identity provider’s token or from callouts to
the identity provider, if applicable.
isValid
Indicates whether the token is valid or not, based on the custom validation logic in your token exchange handler.

getCustomErrorMessage()
Retrieves the CustomErrorMsg that’s returned when token validation fails.

Signature
public String getCustomErrorMessage()

Return Value
Type: String

getData()
Retrieves data from the identity provider token. This data can include custom data that isn’t stored in the userData property.

Signature
public Object getData()

Return Value
Type: Object

204
Apex Reference Guide TokenValidationResult Class

getToken()
Retrieves the token that was passed from the external identity provider.

Signature
public String getToken()

Return Value
Type: String

getTokenType()
Retrieves the type of token that was passed from the external identity provider.

Signature
public Auth.OAuth2TokenExchangeType getTokenType()

Return Value
Type: Auth.OAuth2TokenExchangeType

getUserData()
Retrieves information about the user. The user information can be obtained from the identity provider’s token or from callouts to the
identity provider, if applicable.

Signature
public Auth.UserData getUserData()

Return Value
Type: Auth.UserData

isValid
Indicates whether the token is valid or not, based on the custom validation logic in your token exchange handler.

Signature
public Boolean isValid {get; set;}

Property Value
Type: Boolean

205
Apex Reference Guide UserData Class

UserData Class
Stores user information for authentication provider registration handlers, including handlers that implement the
Auth.RegistrationHandler interface and handlers built using Flow Builder.

Namespace
Auth

Usage
For more information about using this class with the Auth.RegistrationHandler interface, see Storing User Information and
Getting Access Tokens in the RegistrationHandler Interface documentation.
For more information about using this class as an Apex-defined variable in a user registration flow, see Example: Authentication Provider
Registration Handler Flow in Salesforce Help

IN THIS SECTION:
UserData Constructors
UserData Properties

UserData Constructors
The following are constructors for UserData.

IN THIS SECTION:
UserData(identifier, firstName, lastName, fullName, email, link, userName, locale, provider, siteLoginUrl, attributeMap)
Creates a new instance of the Auth.UserData class using the specified arguments.
UserData(identifier, firstName, lastName, fullName, email, link, username, locale, provider, siteLoginUrl, attributeMap, idToken,
userInfoJSONString)
Creates an instance of the Auth.UserData class that includes the ID token and user info response from the identity provider, if returned
during single sign-on.

UserData(identifier, firstName, lastName, fullName, email, link, userName,


locale, provider, siteLoginUrl, attributeMap)
Creates a new instance of the Auth.UserData class using the specified arguments.

Signature
public UserData(String identifier, String firstName, String lastName, String fullName,
String email, String link, String userName, String locale, String provider, String
siteLoginUrl, Map<String,String> attributeMap)

206
Apex Reference Guide UserData Class

Parameters
identifier
Type: String
An identifier from the third party for the authenticated user, such as the Facebook user number or the Salesforce user ID.
firstName
Type: String
The first name of the authenticated user, according to the third party.
lastName
Type: String
The last name of the authenticated user, according to the third party.
fullName
Type: String
The full name of the authenticated user, according to the third party.
email
Type: String
The email address of the authenticated user, according to the third party.
link
Type: String
A stable link for the authenticated user such as https://www.facebook.com/MyUsername.
userName
Type: String
The username of the authenticated user in the third party.
locale
Type: String
The standard locale string for the authenticated user.
provider
Type: String
The service used to log in, such as Facebook or Janrain.
siteLoginUrl
Type: String
The site login page URL passed in if used with a site; null otherwise.
attributeMap
Type: Map<String, String>
A map of data from the third party, in case the handler has to access non-standard values. For example, when using Janrain as a
provider, the fields Janrain returns in its accessCredentials dictionary are placed into the attributeMap. These fields
vary by provider.

207
Apex Reference Guide UserData Class

UserData(identifier, firstName, lastName, fullName, email, link, username,


locale, provider, siteLoginUrl, attributeMap, idToken, userInfoJSONString)
Creates an instance of the Auth.UserData class that includes the ID token and user info response from the identity provider, if returned
during single sign-on.

Signature
public UserData(String identifier, String firstName, String lastName, String fullName,
String email, String link, String username, String locale, String provider, String
siteLoginUrl, Map<String,String> attributeMap, String idToken, String userInfoJSONString)

Parameters
identifier
Type: String
An identifier from the third party for the authenticated user, such as the Facebook user number or the Salesforce user ID.
firstName
Type: String
The first name of the authenticated user, according to the third party.
lastName
Type: String
The last name of the authenticated user, according to the third party.
fullName
Type: String
The full name of the authenticated user, according to the third party.
email
Type: String
The email address of the authenticated user, according to the third party.
link
Type: String
A stable link for the authenticated user such as https://www.facebook.com/MyUsername.
username
Type: String
The username of the authenticated user in the third party.
locale
Type: String
The standard locale string for the authenticated user.
provider
Type: String
The service used to log in, such as Facebook or Janrain.
siteLoginUrl
Type: String

208
Apex Reference Guide UserData Class

The site login page URL passed in if used with a site; null otherwise.
attributeMap
Type: Map<String, String>
A map of data from the third party, in case the handler has to access non-standard values. For example, when using Janrain as a
provider, the fields Janrain returns in its accessCredentials dictionary are placed into the attributeMap. These fields
vary by provider.
idToken
Type: String
If provided by the third party, the ID token, formatted as an encoded JWT. The ID token contains claims with information about the
authenticated user.
userInfoJSONString
Type: String
If provided by the third party, the user info response, formatted as a JSON object that has been serialized into a string.

UserData Properties
The following are properties for UserData.

IN THIS SECTION:
identifier
An identifier from the third party for the authenticated user, such as the Facebook user number or the Salesforce user ID.
firstName
The first name of the authenticated user, according to the third party.
lastName
The last name of the authenticated user, according to the third party.
fullName
The full name of the authenticated user, according to the third party.
email
The email address of the authenticated user, according to the third party.
link
A stable link for the authenticated user such as https://www.facebook.com/MyUsername.
username
The username of the authenticated user in the third party.
locale
The standard locale string for the authenticated user.
provider
The service used to log in, such as Facebook or Janrain.
siteLoginUrl
The site login page URL passed in if used with a site; null otherwise.

209
Apex Reference Guide UserData Class

attributeMap
A map of data from the third party, in case the handler has to access non-standard values. For example, when using Janrain as a
provider, the fields Janrain returns in its accessCredentials dictionary are placed into the attributeMap. These fields
vary by provider.
idToken
If provided, the ID token from the third party, formatted as an encoded JWT. The ID token contains claims with information about
the authenticated user.
userInfoJSONString
If provided, the user info response from the third party. The user info response is a JSON object containing user attributes. When
used in this property, the JSON object is serialized into a string.
idTokenJSONString
If provided, the ID token from the third party. The ID token is formatted as a JSON Web Token (JWT) containing claims with information
about the user. When used in this property, the ID token is serialized into a string.

identifier
An identifier from the third party for the authenticated user, such as the Facebook user number or the Salesforce user ID.

Signature
public String identifier {get; set;}

Property Value
Type: String

firstName
The first name of the authenticated user, according to the third party.

Signature
public String firstName {get; set;}

Property Value
Type: String

lastName
The last name of the authenticated user, according to the third party.

Signature
public String lastName {get; set;}

Property Value
Type: String

210
Apex Reference Guide UserData Class

fullName
The full name of the authenticated user, according to the third party.

Signature
public String fullName {get; set;}

Property Value
Type: String

email
The email address of the authenticated user, according to the third party.

Signature
public String email {get; set;}

Property Value
Type: String

link
A stable link for the authenticated user such as https://www.facebook.com/MyUsername.

Signature
public String link {get; set;}

Property Value
Type: String

username
The username of the authenticated user in the third party.

Signature
public String username {get; set;}

Property Value
Type: String

locale
The standard locale string for the authenticated user.

211
Apex Reference Guide UserData Class

Signature
public String locale {get; set;}

Property Value
Type: String

provider
The service used to log in, such as Facebook or Janrain.

Signature
public String provider {get; set;}

Property Value
Type: String

siteLoginUrl
The site login page URL passed in if used with a site; null otherwise.

Signature
public String siteLoginUrl {get; set;}

Property Value
Type: String

attributeMap
A map of data from the third party, in case the handler has to access non-standard values. For example, when using Janrain as a provider,
the fields Janrain returns in its accessCredentials dictionary are placed into the attributeMap. These fields vary by provider.

Signature
public Map<String, String> attributeMap {get; set;}

Property Value
Type: Map<String, String>

idToken
If provided, the ID token from the third party, formatted as an encoded JWT. The ID token contains claims with information about the
authenticated user.

212
Apex Reference Guide VerificationAction Enum

Signature
public String idToken {get; set;}

Property Value
Type: String

userInfoJSONString
If provided, the user info response from the third party. The user info response is a JSON object containing user attributes. When used
in this property, the JSON object is serialized into a string.

Signature
public String userInfoJSONString {get; set;}

Property Value
Type: String

idTokenJSONString
If provided, the ID token from the third party. The ID token is formatted as a JSON Web Token (JWT) containing claims with information
about the user. When used in this property, the ID token is serialized into a string.

Signature
public String idTokenJSONString {get; set;}

Property Value
Type: String

VerificationAction Enum
Indicates the method that you use to send a one-time password (OTP) to a user during the headless passwordless login flow.

Usage
Use this enum to specify the user's method of receiving a one-time password when you implement the
Auth.HeadlessUserDiscoveryHandler interface.

Enum Values
The following are the values of the Auth.VerificationAction enum.

Value Description
EMAIL Indicates that the user is verifying their identity with email.

213
Apex Reference Guide VerificationMethod Enum

Value Description
SMS Indicates that the user is verifying their identity with SMS.

VerificationMethod Enum
Contains the different ways users can identify themselves when logging in. You can use it to implement mobile-centric passwordless
login pages and to self-register (and deregister) verification methods.

Usage
The enum value is an argument in System.Site.passwordlessLogin,
System.UserManagement.registerVerificationMethod, and
System.UserManagement.deregisterVerificationMethod on page 4160 methods. The value indicates the method
used to verify a user’s identity.

Enum Values
The following are the values of the Auth.VerificationMethod enum.

Value Description
BUILT_IN_AUTHENTICATOR Identity verified with a built-in authenticator.

EMAIL Identity verified with a verification code sent in an email message.

PASSWORD Identity verified with a password.

SALESFORCE_AUTHENTICATOR Identity verified by Salesforce Authenticator.

SECURITY_KEY Identity verified by a WebAuthn-compatible physical security key. Includes all security
keys registered or used after Summer ’22.

SMS Identity verified with a verification code sent via SMS message.

TOTP Identity verified with a time-based one-time password (TOTP).

U2F Identity verified by a U2F physical security key, such as a YubiKey.

Note: For U2F security keys registered or used after Summer ’22, use
SECURITY_KEY instead.

VerificationPolicy Enum
The Auth.VerificationPolicy enum contains an identity verification policy value used by the
SessionManagement.generateVerificationUrl method.

214
Apex Reference Guide VerificationResult Class

Usage
The enum value is an argument in the SessionManagement.generateVerificationUrl method. The value indicates the
session security policy required to initiate identity verification for the user’s session.

Enum Values
The Auth.VerificationPolicy enum has this value.

Value Description
HIGH_ASSURANCE The security level for the user’s current session must be High Assurance.

VerificationResult Class
Contains the result of a verification challenge that you invoke when you create your own Verify page. The challenge can be initiated by
either the System.UserManagement.verifyPasswordlessLogin or
System.UserManagement.verifySelfRegistration method.

Namespace
Auth

Usage
When users sign up for or log in to your Experience Cloud site with an email address or phone number, Salesforce sends them a verification
code. At the same time, Salesforce generates the Verify page for users to enter the code to verify their identity. You can replace the
Salesforce-generated Verify page with one that you create with Visualforce. Then invoke the verification challenge and, if the verification
code is entered correctly, log in the user. For sign-up, you use the System.UserManagement.verifySelfRegistration
method. For passwordless login, you use the System.UserManagement.verifyPasswordlessLogin method. The methods return the
verification result, which contains the message displayed as a result of the challenge. This message also indicates whether the challenge
is successful and where to direct the user when the verification code is entered correctly.

Example
This code contains the result of a verification challenge that registers a new user.
String id = System.UserManagement.initSelfRegistration
(Auth.VerificationMethod.SMS, user);
Auth.VerificationResult res = System.UserManagement.verifySelfRegistration
(Auth.VerificationMethod.SMS, id, ‘123456’, null);
if(res.success == true){
//redirect
}

IN THIS SECTION:
VerificationResult Constructor
VerificationResult Properties

215
Apex Reference Guide VerificationResult Class

VerificationResult Method

VerificationResult Constructor
VerificationResult has the following constructor.

IN THIS SECTION:
VerificationResult(redirect, success, message)
Creates an instance of the VerificationResult class that contains the verification result from
System.UserManagement.verifySelfRegistration.

VerificationResult(redirect, success, message)


Creates an instance of the VerificationResult class that contains the verification result from
System.UserManagement.verifySelfRegistration.

Signature
public VerificationResult(System.PageReference redirect, Boolean success, String message)

Parameters
redirect
Type: System.PageReferenceSystem.PageReference
Where user is directed upon successful verification.
success
Type: Boolean
Indicates whether verification succeeded.
message
Type: String
Message that displays as a result of a verification challenge.

VerificationResult Properties
The following are properties for VerificationResult.

IN THIS SECTION:
message
Message that displays as a result of a verification challenge. SUCCESS if the identity verification is successful. Other values are FAILURE,
PENDING, RATE_LIMITED, or FAILURE_REPORT.
redirect
Where the user is directed after entering the verification code successfully, for example, the Experience Cloud site’s home page or
location specified by the start URL.
success
The verification challenge is successful.

216
Apex Reference Guide VerificationResult Class

message
Message that displays as a result of a verification challenge. SUCCESS if the identity verification is successful. Other values are FAILURE,
PENDING, RATE_LIMITED, or FAILURE_REPORT.

Signature
public String message {get; set;}

Property Value
Type: String

redirect
Where the user is directed after entering the verification code successfully, for example, the Experience Cloud site’s home page or location
specified by the start URL.

Signature
public System.PageReference redirect {get; set;}

Property Value
Type: System.PageReferenceSystem.PageReference

success
The verification challenge is successful.

Signature
public Boolean success {get; set;}

Property Value
Type: Boolean

VerificationResult Method
VerificationResult has the following method.

IN THIS SECTION:
clone()
Duplicates the Auth.VerificationResult object.

clone()
Duplicates the Auth.VerificationResult object.

217
Apex Reference Guide Auth Exceptions

Signature
public Object clone()

Return Value
Type: VerificationResult

Auth Exceptions
The Auth namespace contains some exception classes.
All exception classes support built-in methods for returning the error message and exception type. See Exception Class and Built-In
Exceptions.
The Auth namespace contains the following exception.

Exception Description
Auth. Throw this exception to indicate that an error occurred when using the auth provider plug-in.
AuthProviderPluginException Use to display a custom error message to the user. To get the error message and write it to
debug log, use the String getMessage().

Auth.ConnectedAppPlugin Throw this exception to indicate that an error occurred while running the custom behavior for
Exception a connected app. To get the error message and write it to debug log, use the String
getMessage().

Auth.DiscoveryCustomErrorException Throw this exception to customize error messages that appear on Discovery logins and
Configurable Self-Registration pages. An error message can have up to 200 characters. Use
custom error exceptions to localize error messages.
Include this exception in:
• Auth.MyDomainLoginDiscoveryHandler to show a custom error message on
the My Domain login page
• Auth.LoginDiscoveryHandler to show an error message on the Experience
Cloud site login page
• Auth.ConfigurableSelfRegHandler to show an error message on the
Experience Cloud site self-registration Verify page
The Verify page shows up if you configured self-registration with either an Email or Text
Message verification method. If you didn’t set up sign-up with a verification method, the error
message appears on the self-registration page.
To get the error message and write it to debug log, use the String getMessage().

Auth.JWTBearerTokenExchange. Throw this exception to indicate a problem with the response from the token endpoint in the
JWTBearerTokenExchangeException JWTBearerTokenExchange class. This exception occurs during the OAuth 2.0 JWT bearer token
flow when the HTTP response:
• Fails to return an access token
• Isn’t in JSON format
• Returns a response code other than a 200 “OK” success code
To get the error message and write it to debug log, use the String getMessage().

218
Apex Reference Guide Auth Exceptions

Exception Description
Auth.JWTValidationException Throws this exception to indicate failure to validate a JWT using methods in the JWTUtil
class. This exception occurs during the OAuth 2.0 token exchange flow in these scenarios.
• Can’t parse the JWT
• Can’t validate the JWT using a certificate, a public key, or the remote keys endpoint,
depending on which method you use

Auth.LoginDiscoveryException Throw this exception to indicate that an error occurred when executing the Login Discovery
handler. For an example, see LoginDiscoveryHandler Example Implementation. To get the error
message and write it to debug log, use the String getMessage().

Auth.VerificationException Throw this exception to trigger verification based on the passed-in policy. You can throw this
exception in an Apex trigger or Visualforce controller. The system automatically sends you to
the verification endpoint, if possible.

Note: You can’t catch this exception. The exception immediately triggers the verification.

Examples
This example uses AuthProviderPluginException to throw a custom exception in a custom authentication provider
implementation. Use this exception if you want the end user to see a specific message, passing in the error message as a parameter. If
you use another exception, users see a standard Salesforce error message.
global override Auth.OAuthRefreshResult refresh(Map<string,string>
authProviderConfiguration,String refreshToken){
HttpRequest req = new HttpRequest();
String accessToken = null;
String error = null;
try {

// DEVELOPER TODO: Make a refresh token flow using refreshToken passed


// in as an argument to get the new access token
// accessToken = ...
} catch (System.CalloutException e) {
error = e.getMessage();
}
catch(Exception e) {
error = e.getMessage();
throw new Auth.AuthProviderPluginException('My custom error');
}

return new Auth.OAuthRefreshResult(accessToken,refreshToken, error);

This example uses Auth.VerificationException to trigger verification if a user attempts to create an account without a high
assurance session.
trigger testTrigger on Account (before insert) {
Map<String, String> sessionMap = auth.SessionManagement.getCurrentSession();
if(!sessionMap.get('SessionSecurityLevel').equals('HIGH_ASSURANCE')) {

219
Apex Reference Guide Cache Namespace

throw new Auth.VerificationException(


Auth.VerificationPolicy.HIGH_ASSURANCE, 'Insert Account');
}
}

Cache Namespace
The Cache namespace contains methods for managing the platform cache.
The following are the classes in the Cache namespace.

IN THIS SECTION:
CacheBuilder Interface
An interface for safely retrieving and removing values from a session or org cache. Use the interface to generate a value that you
want to store in the cache. The interface checks for cache misses, which means you no longer need to check for null cache values
yourself.
Org Class
Use the Cache.Org class to add, retrieve, and manage values in the org cache. Unlike the session cache, the org cache is not tied
to any session and is available to the organization across requests and to all users.
OrgPartition Class
Contains methods to manage cache values in the org cache of a specific partition. Unlike the session cache, the org cache is not tied
to any session. It’s available to the organization across requests and to all users.
Partition Class
Base class of Cache.OrgPartition and Cache.SessionPartition. Use the subclasses to manage the cache partition
for org caches and session caches.
Session Class
Use the Cache.Session class to add, retrieve, and manage values in the session cache. The session cache is active as long as
the user’s Salesforce session is valid (the user is logged in, and the session is not expired).
SessionPartition Class
Contains methods to manage cache values in the session cache of a specific partition.
Cache Exceptions
The Cache namespace contains exception classes.
Visibility Enum
Use the Cache.Visibility enumeration in the Cache.Session or Cache.Org methods to indicate whether a cached
value is visible only in the value’s namespace or in all namespaces.

SEE ALSO:
Apex Developer Guide: Platform Cache

CacheBuilder Interface
An interface for safely retrieving and removing values from a session or org cache. Use the interface to generate a value that you want
to store in the cache. The interface checks for cache misses, which means you no longer need to check for null cache values yourself.

220
Apex Reference Guide CacheBuilder Interface

Namespace
Cache

IN THIS SECTION:
CacheBuilder Methods
CacheBuilder Example Implementation

SEE ALSO:
Apex Developer Guide: Safely Cache Values with the CacheBuilder Interface

CacheBuilder Methods
The following are methods for CacheBuilder.

IN THIS SECTION:
doLoad(var)
Contains the logic that builds a cached value. You don’t call this method directly. Instead, it’s called indirectly when you reference
the class that implements the CacheBuilder interface.

doLoad(var)
Contains the logic that builds a cached value. You don’t call this method directly. Instead, it’s called indirectly when you reference the
class that implements the CacheBuilder interface.

Signature
public Object doLoad(String var)

Parameters
var
Type: String
A case-sensitive string value used to build a cached value. This parameter is also used as part of the unique key that identifies the
cached value.

Return Value
Type: Object
The value that was cached. Cast the return value to the appropriate type.

221
Apex Reference Guide Org Class

CacheBuilder Example Implementation


This example creates a class called UserInfoCache that implements the CacheBuilder interface. The class caches the results
of a SOQL query run against the User object.
class UserInfoCache implements Cache.CacheBuilder {
public Object doLoad(String userid) {
User u = (User)[SELECT Id, IsActive, username FROM User WHERE id =: userid];
return u;
}
}

This example gets a cached User record based on a user ID. If the value exists in the org cache, it is returned. If the value doesn’t exist,
the doLoad(String var) method is re-executed, and the new value is cached and returned.
User batman = (User) Cache.Org.get(UserInfoCache.class, ‘00541000000ek4c');

Org Class
Use the Cache.Org class to add, retrieve, and manage values in the org cache. Unlike the session cache, the org cache is not tied to
any session and is available to the organization across requests and to all users.

Namespace
Cache

Usage
Cache Key Format
This table lists the format of the key parameter that some methods in this class take, such as put, get, and contains.

Key Format Description


namespace.partition.key Fully qualified key name.

key Refers to a partition marked as default when the


namespace.partition prefix is omitted.

local.partition.key Use the local prefix to refer to the org’s namespace when the
org doesn’t have a namespace defined. If the org has a namespace
defined, the local prefix also refers to that org’s namespace.

Note:
• If no default partition is specified in the org, calling a cache method without fully qualifying the key name causes a
Cache.Org.OrgCacheException to be thrown.
• The local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s
namespace. The cache put calls aren’t allowed in a partition that the invoking class doesn’t own.

222
Apex Reference Guide Org Class

Example
This class is the controller for a sample Visualforce page (shown in the subsequent code sample). The cached values are initially added
to the cache by the init() method, which the Visualforce page invokes when it loads through the action attribute. The cache
keys don’t contain the namespace.partition prefix. They all refer to the default partition in your org. To run this sample, create
a partition and mark it as default.
The Visualforce page contains four output components. These components call get methods on the controller that returns the following
values from the cache: a date, data based on the MyData inner class, a counter, a text value, and a list. The size of the list is also returned.
The Visualforce page also contains two buttons. The Rerender button invokes the go() method on the controller. This method increases
the values of the counter and the custom data in the cache. When you click Rerender, the two counters increase by one each time. The
go() method retrieves the values of these counters from the cache, increments their values by one, and stores them again in the
cache.
The Remove datetime Key button deletes the date-time value (with key datetime) from the cache. As a result, the value next to
Cached datetime: is cleared on the page.

Note: If another user logs in and runs this sample, this user gets the cache values that were last added or updated by the previous
user. For example, if the counter value was five, the next user sees the counter value as increased to six.
public class OrgCacheController {

// Inner class.
// Used as the data type of a cache value.
class MyData {
public String value { get; set; }
public Integer counter { get; set; }

public MyData(String value) {


this.value = value;
this.counter = 0;
}

public void inc() {


counter++;
}

override public String toString() {


return this.value + ':' + this.counter;
}
}

// Apex List.
// Used as the data type of a cached value.
private List<String> numbers =
new List<String> { 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE' };

// Constructor of the controller for the Visualforce page.


public OrgCacheController() {
}

// Adds various values to the cache.


// This method is called when the Visualforce page loads.
public void init() {
// All key values are not qualified by the namespace.partition

223
Apex Reference Guide Org Class

// prefix because they use the default partition.

// Add counter to the cache with initial value of 0


// or increment it if it's already there.
if (!Cache.Org.contains('counter')) {
Cache.Org.put('counter', 0);
} else {
Cache.Org.put('counter', getCounter() + 1);
}

// Add the datetime value to the cache only if it's not already there.
if (!Cache.Org.contains('datetime')) {
DateTime dt = DateTime.now();
Cache.Org.put('datetime', dt);
}

// Add the custom data to the cache only if it's not already there.
if (!Cache.Org.contains('data')) {
Cache.Org.put('data', new MyData('Some custom value'));
}

// Add a list of number to the cache if not already there.


if (!Cache.Org.contains('list')) {
Cache.Org.put('list', numbers);
}

// Add a string value to the cache if not already there.


if (!Cache.Org.contains('output')) {
Cache.Org.put('output', 'Cached text value');
}
}

// Return counter from the cache.


public Integer getCounter() {
return (Integer)Cache.Org.get('counter');
}

// Return datetime value from the cache.


public String getCachedDatetime() {
DateTime dt = (DateTime)Cache.Org.get('datetime');
return dt != null ? dt.format() : null;
}

// Return cached value whose type is the inner class MyData.


public String getCachedData() {
MyData mydata = (MyData)Cache.Org.get('data');
return mydata != null ? mydata.toString() : null;
}

// Return output from the cache.


public String getOutput() {
return (String)Cache.Org.get('output');
}

224
Apex Reference Guide Org Class

// Return list from the cache.


public List<String> getList() {
return (List<String>)Cache.Org.get('list');
}

// Method invoked by the Rerender button on the Visualforce page.


// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go() {
// Increase the cached counter value or set it to 0
// if it's not cached.
if (Cache.Org.contains('counter')) {
Cache.Org.put('counter', getCounter() + 1);
} else {
Cache.Org.put('counter', 0);
}

// Get the custom data value from the cache.


MyData d = (MyData)Cache.Org.get('data');
// Only if the data is already in the cache, update it.
if (Cache.Org.contains('data')) {
d.inc();
Cache.Org.put('data', d);
}

return null;
}

// Method invoked by the Remove button on the Visualforce page.


// Removes the datetime cached value from the org cache.
public PageReference remove() {
Cache.Org.remove('datetime');

return null;
}
}

This is the Visualforce page that corresponds to the OrgCacheController class.


<apex:page controller="OrgCacheController" action="{!init}">

<apex:outputPanel id="output">
<br/>Cached datetime: <apex:outputText value="{!cachedDatetime}"/>
<br/>Cached data: <apex:outputText value="{!cachedData}"/>
<br/>Cached counter: <apex:outputText value="{!counter}"/>
<br/>Output: <apex:outputText value="{!output}"/>
<br/>Repeat: <apex:repeat var="item" value="{!list}">
<apex:outputText value="{!item}"/>&nbsp;
</apex:repeat>
<br/>List size: <apex:outputText value="{!list.size}"/>
</apex:outputPanel>

<br/><br/>
<apex:form >

225
Apex Reference Guide Org Class

<apex:commandButton id="go" action="{!go}" value="Rerender" rerender="output"/>


<apex:commandButton id="remove" action="{!remove}" value="Remove datetime Key"
rerender="output"/>
</apex:form>

</apex:page>

This is the output of the page after clicking the Rerender button twice. The counter value could differ in your case if a key named
counter was already in the cache before running this sample.

Cached datetime:8/11/2015 1:58 PM


Cached data:Some custom value:2
Cached counter:2
Output:Cached text value
Repeat:ONE TWO THREE FOUR FIVE
List size:5

IN THIS SECTION:
Org Constants
The Org class provides a constant that you can use when setting the time-to-live (TTL) value.
Org Methods

SEE ALSO:
Apex Developer Guide: Platform Cache

Org Constants
The Org class provides a constant that you can use when setting the time-to-live (TTL) value.

Constant Description
MAX_TTL_SECS Represents the maximum amount of time, in seconds, to keep the cached value in the
org cache.

Org Methods
The following are methods for Org. All methods are static.

IN THIS SECTION:
contains(key)
Returns true if the org cache contains a cached value corresponding to the specified key.
contains(keys)
Returns true if the org cache contains values for the specified key entries.
contains(setOfKeys)
Returns true if the org cache contains values for a specified set of keys.

226
Apex Reference Guide Org Class

get(key)
Returns the cached value corresponding to the specified key from the org cache.
get(cacheBuilder, key)
Returns the cached value corresponding to the specified key from the org cache. Use this method if your cached value is a class that
implements the CacheBuilder interface.
get(keys)
Returns the cached values corresponding to the specified set of keys from the org cache.
getAvgGetSize()
Returns the average item size of all the keys fetched from the org cache, in bytes.
getAvgGetTime()
Returns the average time taken to get a key from the org cache, in nanoseconds.
getAvgValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the org cache, in bytes.
getCapacity()
Returns the percentage of org cache capacity that has been used.
getKeys()
Returns a set of all keys that are stored in the org cache and visible to the invoking namespace.
getMaxGetSize()
Returns the maximum item size of all the keys fetched from the org cache, in bytes.
getMaxGetTime()
Returns the maximum time taken to get a key from the org cache, in nanoseconds.
getMaxValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the org cache, in
bytes.
getMissRate()
Returns the miss rate in the org cache.
getName()
Returns the name of the default cache partition.
getNumKeys()
Returns the total number of keys in the org cache.
getPartition(partitionName)
Returns a partition from the org cache that corresponds to the specified partition name.
put(key, value)
Stores the specified key/value pair as a cached entry in the org cache. The put method can write only to the cache in your org’s
namespace.
put(key, value, visibility)
Stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s visibility.
put(key, value, ttlSecs)
Stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s lifetime.

227
Apex Reference Guide Org Class

put(key, value, ttlSecs, visibility, immutable)


Stores the specified key/value pair as a cached entry in the org cache. This method also sets the cached value’s lifetime, visibility,
and whether it can be overwritten by another namespace.
remove(key)
Deletes the cached value corresponding to the specified key from the org cache.
remove(cacheBuilder, key)
Deletes the cached value corresponding to the specified key from the org cache. Use this method if your cached value is a class that
implements the CacheBuilder interface.

contains(key)
Returns true if the org cache contains a cached value corresponding to the specified key.

Signature
public static Boolean contains(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value
Type: Boolean
true if a cache entry is found. Othewise, false.

contains(keys)
Returns true if the org cache contains values for the specified key entries.

Signature
public static List<Boolean> contains(List<String> keys)

Parameters
keys
Type: List<String>
A list of keys that identifies cached values. For information about the format of the key name, see Usage.

Return Value
Type: List<Boolean>
true if the key entries are found. Othewise, false.

228
Apex Reference Guide Org Class

contains(setOfKeys)
Returns true if the org cache contains values for a specified set of keys.

Signature
public static Map <String, Boolean> contains (Set<String> keys)

Parameters
setOfKeys
Type: Set <String>
A set of keys that uniquely identifies cached values. For information about the format of the key name, see Usage

Return Value
Type: Map <String, Boolean>
Returns the cache key and corresponding Boolean value indicating that the key entry exists. The Boolean value is false if the key
entry doesn't exist.

Usage
The number of input keys cannot exceed the maximum limit of 10.

Example
In this example, the code checks for the presence of multiple keys on the default partition. It fetches the cache key and the corresponding
Boolean value for the key entry from the org cache of the default partition.
Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};
Map<String,Boolean> result = Cache.Org.contains(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('Is Key Present in the cache : ' + result.get(key));
}

In this example, the code checks for the presence of multiple keys on different partitions. It fetches the cache key and the corresponding
Boolean value for the key entry from the org cache of different partitions.
// Assuming there are three partitions p1, p2, p3 with default 'local' namespace

Set<String> keys = new Set<String>{'local.p1.key','local.p2.key', 'local.p3.key'};


Map<String,Boolean> result = Cache.Org.contains(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('Is Key Present in the cache : + result.get(key));
}

get(key)
Returns the cached value corresponding to the specified key from the org cache.

229
Apex Reference Guide Org Class

Signature
public static Object get(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.

Usage
Because Cache.Org.get() returns an object, cast the returned value to a specific type to facilitate use of the returned value.
// Get a cached value
Object obj = Cache.Org.get('ns1.partition1.orderDate');
// Cast return value to a specific data type
DateTime dt2 = (DateTime)obj;

If a Cache.Org.get() call doesn’t find the referenced key, it returns null.

get(cacheBuilder, key)
Returns the cached value corresponding to the specified key from the org cache. Use this method if your cached value is a class that
implements the CacheBuilder interface.

Signature
public static Object get(System.Type cacheBuilder, String key)

Parameters
cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely
identifies a cached value.

Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.

230
Apex Reference Guide Org Class

Usage
Because Cache.Org.get(cacheBuilder, key) returns an object, cast the returned value to a specific type to facilitate use
of the returned value.
return ((DateTime)Cache.Org.get(DateCache.class, 'datetime')).format();

get(keys)
Returns the cached values corresponding to the specified set of keys from the org cache.

Signature
public static Map <String, Object> get (Set <String> keys)

Parameters
keys
Type: Set <String>
A set of keys that uniquely identify cached values. For information about the format of the key name, see Usage.

Return Value
Type: Map <String, Object>
Returns the cache key and corresponding value. Returns null when no corresponding value is found for an input key.

Usage
The number of input keys cannot exceed the maximum limit of 10.

Examples
Fetch multiple keys from the org cache of the default partition.
Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};
Map<String,Object> result = Cache.Org.get(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

Fetch multiple keys from the org cache of different partitions.


// Assuming there are three partitions p1, p2, p3 with default 'local' namespace

Set<String> keys = new Set<String>{'local.p1.key','local.p2.key', 'local.p3.key'};


Map<String,Object> result = Cache.Org.get(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

231
Apex Reference Guide Org Class

getAvgGetSize()
Returns the average item size of all the keys fetched from the org cache, in bytes.

Signature
public static Long getAvgGetSize()

Return Value
Type: Long

Example
In this example the following keys and their corresponding value sizes are inserted. The code then fetches the keys: key 1, key 2, key 3
and key 4 and returns the average item size of the fetched keys.

Key Key Value Size


key 1 42

key 2 42

key 3 58

key 4 36

key 5 36

// Inserting keys key1, key2, key3, key4, key5


Cache.Org.put('key1', 'value1');
Cache.Org.put('key2', 'value2');
Cache.Org.put('key3', 'this is a big value !!!');
Cache.Org.put('key4', 4);
Cache.Org.put('key5', 5);

// Fetching keys - key1, key2, key3, key4


Object v1 = Cache.Org.get('key1');
Object v2 = Cache.Org.get('key2');
Object v3 = Cache.Org.get('key3');
Object v4 = Cache.Org.get('key4');

// Fetching average get size


Long val = Cache.Org.getAvgGetSize();
// Avg item size returned is 44 ( average of 42(key1), 42(key2), 58(key3) and 36(key4)
keys that were fetched )
System.debug('Avg Get Size :' + val);

getAvgGetTime()
Returns the average time taken to get a key from the org cache, in nanoseconds.

232
Apex Reference Guide Org Class

Signature
public static Long getAvgGetTime()

Return Value
Type: Long

getAvgValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the org cache, in bytes.

Signature
public static Long getAvgValueSize()

Return Value
Type: Long

getCapacity()
Returns the percentage of org cache capacity that has been used.

Signature
public static Double getCapacity()

Return Value
Type: Double
Used cache as a percentage number.

getKeys()
Returns a set of all keys that are stored in the org cache and visible to the invoking namespace.

Signature
public static Set<String> getKeys()

Return Value
Type: Set<String>
A set containing all cache keys.

getMaxGetSize()
Returns the maximum item size of all the keys fetched from the org cache, in bytes.

233
Apex Reference Guide Org Class

Signature
public static Long getMaxGetSize()

Return Value
Type: Long

Example
In this example the following keys and their corresponding value sizes are inserted. The code fetches the keys: key 1, key 2 and key 4
and returns the maximum key value size from the fetched keys.

Key Key Value Size


key 1 42

key 2 42

key 3 58

key 4 36

key 5 36

// Inserting keys key1, key2, key3, key4, key5


Cache.Org.put('key1', 'value1');
Cache.Org.put('key2', 'value2');
Cache.Org.put('key3', 'this is a big value !!!');
Cache.Org.put('key4', 4);
Cache.Org.put('key5', 5);

// Fetching keys - key1, key2, key4


Object v1 = Cache.Org.get('key1');
Object v2 = Cache.Org.get('key2');
Object v4 = Cache.Org.get('key4');

// Fetching max get size


Long val = Cache.Org.getMaxGetSize();
// Max item size returned is 42 ( max of 42(key1), 42(key2), and 36(key4) keys that were
fetched )
System.debug('Max Get Size :' + val);

getMaxGetTime()
Returns the maximum time taken to get a key from the org cache, in nanoseconds.

Signature
public static Long getMaxGetTime()

234
Apex Reference Guide Org Class

Return Value
Type: Long

getMaxValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the org cache, in bytes.

Signature
public static Long getMaxValueSize()

Return Value
Type: Long

getMissRate()
Returns the miss rate in the org cache.

Signature
public static Double getMissRate()

Return Value
Type: Double

getName()
Returns the name of the default cache partition.

Signature
public String getName()

Return Value
Type: String
The name of the default cache partition.

getNumKeys()
Returns the total number of keys in the org cache.

Signature
public static Long getNumKeys()

235
Apex Reference Guide Org Class

Return Value
Type: Long

getPartition(partitionName)
Returns a partition from the org cache that corresponds to the specified partition name.

Signature
public static cache.OrgPartition getPartition(String partitionName)

Parameters
partitionName
Type: String
A partition name that is qualified by the namespace, for example, namespace.partition.

Return Value
Type: Cache.OrgPartition

Example
After you get the org partition, you can add and retrieve the partition’s cache values.
// Get partition
Cache.OrgPartition orgPart = Cache.Org.getPartition('myNs.myPartition');
// Retrieve cache value from the partition
if (orgPart.contains('BookTitle')) {
String cachedTitle = (String)orgPart.get('BookTitle');
}

// Add cache value to the partition


orgPart.put('OrderDate', Date.today());

// Or use dot notation to call partition methods


String cachedAuthor = (String)Cache.Org.getPartition('myNs.myPartition').get('BookAuthor');

put(key, value)
Stores the specified key/value pair as a cached entry in the org cache. The put method can write only to the cache in your org’s
namespace.

Signature
public static void put(String key, Object value)

236
Apex Reference Guide Org Class

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.

Return Value
Type: void

put(key, value, visibility)


Stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s visibility.

Signature
public static void put(String key, Object value, Cache.Visibility visibility)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing
from any namespace.

Return Value
Type: void

put(key, value, ttlSecs)


Stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s lifetime.

Signature
public static void put(String key, Object value, Integer ttlSecs)

237
Apex Reference Guide Org Class

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the org cache. The maximum is 172,800 seconds (48 hours). The
minimum value is 300 seconds or 5 minutes. The default value is 86,400 seconds (24 hours).

Return Value
Type: void

put(key, value, ttlSecs, visibility, immutable)


Stores the specified key/value pair as a cached entry in the org cache. This method also sets the cached value’s lifetime, visibility, and
whether it can be overwritten by another namespace.

Signature
public static void put(String key, Object value, Integer ttlSecs, cache.Visibility
visibility, Boolean immutable)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the org cache. The maximum is 172,800 seconds (48 hours). The
minimum value is 300 seconds or 5 minutes. The default value is 86,400 seconds (24 hours).
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing
from any namespace.
immutable
Type: Boolean

238
Apex Reference Guide Org Class

Indicates whether the cached value can be overwritten by another namespace (false) or not (true).

Return Value
Type: void

remove(key)
Deletes the cached value corresponding to the specified key from the org cache.

Signature
public static Boolean remove(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value
Type: Boolean
true if the cache value was successfully removed. Otherwise, false.

remove(cacheBuilder, key)
Deletes the cached value corresponding to the specified key from the org cache. Use this method if your cached value is a class that
implements the CacheBuilder interface.

Signature
public static Boolean remove(System.Type cacheBuilder, String key)

Parameters
cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely
identifies a cached value.

Return Value
Type: Boolean
true if the cache value was successfully removed. Otherwise, false.

239
Apex Reference Guide OrgPartition Class

OrgPartition Class
Contains methods to manage cache values in the org cache of a specific partition. Unlike the session cache, the org cache is not tied to
any session. It’s available to the organization across requests and to all users.

Namespace
Cache

Usage
This class extends Cache.Partition and inherits all its non-static methods. Utility methods for creating and validating keys aren’t supported
and can be called only from the Cache.Partition parent class. For a list of Cache.Partition methods, see Partition Methods.
To get an org partition, call Cache.Org.getPartition and pass in a fully qualified partition name, as follows.
Cache.OrgPartition orgPartition = Cache.Org.getPartition('namespace.myPartition');

See Cache Key Format for Partition Methods.

Example
This class is the controller for a sample Visualforce page (shown in the subsequent code sample). The controller shows how to use the
methods of Cache.OrgPartition to manage a cache value on a particular partition. The controller takes inputs from the Visualforce
page for the partition name, key name for a counter, and initial counter value. The controller contains default values for these inputs.
When you click Rerender on the Visualforce page, the go() method is invoked and increases the counter by one. When you click
Remove Key, the counter key is removed from the cache. The counter value gets reset to its initial value when it’s re-added to the cache.

Note: If another user logs in and runs this sample, the user gets the cache values that were last added or updated by the previous
user. For example, if the counter value was five, the next user sees the counter value as increased to six.
public class OrgPartitionController {

// Name of a partition
String partitionInput = 'local.myPartition';
// Name of the key
String counterKeyInput = 'counter';
// Key initial value
Integer counterInitValue = 0;
// Org partition object
Cache.OrgPartition orgPartition;

// Constructor of the controller for the Visualforce page.


public OrgPartitionController() {
}

// Adds counter value to the cache.


// This method is called when the Visualforce page loads.
public void init() {
// Create the partition instance based on the partition name
orgPartition = getPartition();

// Create the partition instance based on the partition name

240
Apex Reference Guide OrgPartition Class

// given in the Visualforce page or the default value.


orgPartition = Cache.Org.getPartition(partitionInput);

// Add counter to the cache with an initial value


// or increment it if it's already there.
if (!orgPartition.contains(counterKeyInput)) {
orgPartition.put(counterKeyInput, counterInitValue);
} else {
orgPartition.put(counterKeyInput, getCounter() + 1);
}
}

// Returns the org partition based on the partition name


// given in the Visualforce page or the default value.
private Cache.OrgPartition getPartition() {
if (orgPartition == null) {
orgPartition = Cache.Org.getPartition(partitionInput);
}

return orgPartition;
}

// Return counter from the cache.


public Integer getCounter() {
return (Integer)getPartition().get(counterKeyInput);
}

// Invoked by the Submit button to save input values


// supplied by the user.
public PageReference save() {
// Reset the initial key value in the cache
getPartition().put(counterKeyInput, counterInitValue);

return null;
}

// Method invoked by the Rerender button on the Visualforce page.


// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go() {
// Get the org partition object
orgPartition = getPartition();
// Increase the cached counter value or set it to 0
// if it's not cached.
if (orgPartition.contains(counterKeyInput)) {
orgPartition.put(counterKeyInput, getCounter() + 1);
} else {
orgPartition.put(counterKeyInput, counterInitValue);
}

return null;
}

241
Apex Reference Guide OrgPartition Class

// Method invoked by the Remove button on the Visualforce page.


// Removes the datetime cached value from the org cache.
public PageReference remove() {
getPartition().remove(counterKeyInput);

return null;
}

// Get and set methods for accessing variables


// that correspond to the input text fields on
// the Visualforce page.
public String getPartitionInput() {
return partitionInput;
}

public String getCounterKeyInput() {


return counterKeyInput;
}

public Integer getCounterInitValue() {


return counterInitValue;
}

public void setPartitionInput(String partition) {


this.partitionInput = partition;
}

public void setCounterKeyInput(String keyName) {


this.counterKeyInput = keyName;
}

public void setCounterInitValue(Integer counterValue) {


this.counterInitValue = counterValue;
}
}

This is the Visualforce page that corresponds to the OrgPartitionController class.


<apex:page controller="OrgPartitionController" action="{!init}">

<apex:form >
<br/>Partition with Namespace Prefix: <apex:inputText value="{!partitionInput}"/>

<br/>Counter Key Name: <apex:inputText value="{!counterKeyInput}"/>


<br/>Counter Initial Value: <apex:inputText value="{!counterInitValue}"/>
<apex:commandButton action="{!save}" value="Save Key Input Values"/>
</apex:form>

<apex:outputPanel id="output">
<br/>Cached Counter: <apex:outputText value="{!counter}"/>
</apex:outputPanel>

<br/>
<apex:form >

242
Apex Reference Guide Partition Class

<apex:commandButton id="go" action="{!go}" value="Rerender" rerender="output"/>


<apex:commandButton id="remove" action="{!remove}" value="Remove Key"
rerender="output"/>
</apex:form>

</apex:page>

SEE ALSO:
Apex Developer Guide: Platform Cache

Partition Class
Base class of Cache.OrgPartition and Cache.SessionPartition. Use the subclasses to manage the cache partition
for org caches and session caches.

Namespace
Cache

Cache Key Format for Partition Methods


After you obtain the partition object (an instance of Cache.OrgPartition or Cache.SessionPartition), the methods
to add, retrieve, and manage the cache values in a partition take the key name. The key name that you supply to these methods (get(),
put(), remove(), and contains()) doesn’t include the namespace.partition prefix.

IN THIS SECTION:
Partition Methods

SEE ALSO:
OrgPartition Class
SessionPartition Class
Apex Developer Guide: Platform Cache

Partition Methods
The following are methods for Partition.

IN THIS SECTION:
contains(key)
Returns true if the cache partition contains a cached value corresponding to the specified key.
contains(setOfKeys)
Returns true if the cache partition contains values for a specified set of keys.

243
Apex Reference Guide Partition Class

createFullyQualifiedKey(namespace, partition, key)


Generates a fully qualified key from the passed-in key components. The format of the generated key string is
namespace.partition.key.
createFullyQualifiedPartition(namespace, partition)
Generates a fully qualified partition name from the passed-in namespace and partition. The format of the generated partition string
is namespace.partition.
get(key)
Returns the cached value corresponding to the specified key from the cache partition.
get(keys)
Returns the cached values corresponding to the specified set of keys from the cache partition.
get(cacheBuilder, key)
Returns the cached value corresponding to the specified key from the partition cache. Use this method if your cached value is a class
that implements the CacheBuilder interface.
getAvgGetSize()
Returns the average item size of all the keys fetched from the partition, in bytes.
getAvgGetTime()
Returns the average time taken to get a key from the partition, in nanoseconds.
getAvgValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the partition, in bytes.
getCapacity()
Returns the percentage of cache used of the total capacity for this partition.
getKeys()
Returns a set of all keys that are stored in the cache partition and visible to the invoking namespace.
getMaxGetSize()
Returns the maximum item size of all the keys fetched from the partition, in bytes.
getMaxGetTime()
Returns the maximum time taken to get a key from the partition, in nanoseconds.
getMaxValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the partition, in
bytes.
getMissRate()
Returns the miss rate in the partition.
getName()
Returns the name of this cache partition.
getNumKeys()
Returns the total number of keys in the partition.
isAvailable()
Returns true if the Salesforce session is available. Only applies to Cache.SessionPartition. The session cache isn’t
available when an active session isn’t present, such as in asynchronous Apex or code called by asynchronous Apex. For example, if
batch Apex causes an Apex trigger to execute, the session cache isn’t available in the trigger because the trigger runs in asynchronous
context.

244
Apex Reference Guide Partition Class

put(key, value)
Stores the specified key/value pair as a cached entry in the cache partition. The put method can write only to the cache in your
org’s namespace.
put(key, value, visibility)
Stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s visibility.
put(key, value, ttlSecs)
Stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s lifetime.
put(key, value, ttlSecs, visibility, immutable)
Stores the specified key/value pair as a cached entry in the cache partition. This method also sets the cached value’s lifetime, visibility,
and whether it can be overwritten by another namespace.
remove(key)
Deletes the cached value corresponding to the specified key from this cache partition.
remove(cacheBuilder, key)
Deletes the cached value corresponding to the specified key from the partition cache. Use this method if your cached value is a class
that implements the CacheBuilder interface.
validateCacheBuilder(cacheBuilder)
Validates that the specified class implements the CacheBuilder interface.
validateKey(isDefault, key)
Validates a cache key. This method throws a Cache.InvalidParamException if the key is not valid. A valid key is not
null and contains alphanumeric characters.
validateKeyValue(isDefault, key, value)
Validates a cache key and ensures that the cache value is non-null. This method throws a Cache.InvalidParamException
if the key or value is not valid. A valid key is not null and contains alphanumeric characters.
validateKeys(isDefault, keys)
Validates the specified cache keys. This method throws a Cache.InvalidParamException if the key is not valid. A valid
key is not null and contains alphanumeric characters.
validatePartitionName(name)
Validates the partition name — for example, that it is not null.

contains(key)
Returns true if the cache partition contains a cached value corresponding to the specified key.

Signature
public Boolean contains(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.

245
Apex Reference Guide Partition Class

Return Value
Type: Boolean
true if a cache entry is found. Othewise, false.

contains(setOfKeys)
Returns true if the cache partition contains values for a specified set of keys.

Signature
public Map <String, Boolean> contains (Set<String> keys)

Parameters
setOfKeys
Type: Set <String>
A set of keys that uniquely identifies cached values. For information about the format of the key name, see Usage.

Return Value
Type: Map <String, Boolean>
Returns the cache key and corresponding Boolean value indicating that the key entry exists. The Boolean value is false if the key
entry doesn't exist.

Usage
The number of input keys cannot exceed the maximum limit of 10.

Example
In this example, the code checks for the presence of multiple keys on a partition. It fetches the cache key and the corresponding Boolean
value for the key entry from the org cache of the partition.
// Assuming there is a partition p1 in the default 'local' namespace

Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};


Cache.OrgPartition orgPart = Cache.Org.getPartition('local.p1');
Map<String,Boolean> result = orgPart.contains(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('Is Key Present in the cache:' + result.get(key));
}

In this example, the code checks for the presence of multiple keys on a partition. It fetches the cache key and the corresponding Boolean
value for the key entry from the session cache of the partition.
// Assuming there are three partitions p1, p2, p3 with default 'local' namespace

Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};


Cache.SessionPartition sessionPart = Cache.Session.getPartition('local.p1');
Map<String,Boolean> result = sessionPart.contains(keys);

246
Apex Reference Guide Partition Class

for(String key : result.keySet()) {


system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

createFullyQualifiedKey(namespace, partition, key)


Generates a fully qualified key from the passed-in key components. The format of the generated key string is
namespace.partition.key.

Signature
public static String createFullyQualifiedKey(String namespace, String partition, String
key)

Parameters
namespace
Type: String
The namespace of the cache key.
partition
Type: String
The partition of the cache key.
key
Type: String
The name of the cache key.

Return Value
Type: String

createFullyQualifiedPartition(namespace, partition)
Generates a fully qualified partition name from the passed-in namespace and partition. The format of the generated partition string is
namespace.partition.

Signature
public static String createFullyQualifiedPartition(String namespace, String partition)

Parameters
namespace
Type: String
The namespace of the cache key.
partition
Type: String

247
Apex Reference Guide Partition Class

The partition of the cache key.

Return Value
Type: String

get(key)
Returns the cached value corresponding to the specified key from the cache partition.

Signature
public Object get(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.

Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.

get(keys)
Returns the cached values corresponding to the specified set of keys from the cache partition.

Signature
public Map <String, Object> get (Set <String> keys)

Parameters
keys
Type: Set <String>
A set of keys that uniquely identify cached values. For information about the format of the key name, see Usage.

Return Value
Type: Map <String, Object>
Returns the cache key and corresponding value. Returns null when no corresponding value is found for an input key.

Usage
The number of input keys cannot exceed the maximum limit of 10.

248
Apex Reference Guide Partition Class

Examples
Fetch multiple keys from the org cache of a partition.
// Assuming there is a partition p1 in the default 'local' namespace

Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};


Cache.OrgPartition orgPart = Cache.Org.getPartition('local.p1');
Map<String,Object> result = orgPart.get(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

Fetch multiple keys from the session cache of a partition.


// Assuming there is a partition p1 in the default 'local' namespace

Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};


Cache.SessionPartition sessionPart = Cache.Session.getPartition('local.p1');
Map<String,Object> result = sessionPart.get(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

get(cacheBuilder, key)
Returns the cached value corresponding to the specified key from the partition cache. Use this method if your cached value is a class
that implements the CacheBuilder interface.

Signature
public Object get(System.Type cacheBuilder, String key)

Parameters
cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely
identifies a cached value.

Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.

249
Apex Reference Guide Partition Class

getAvgGetSize()
Returns the average item size of all the keys fetched from the partition, in bytes.

Signature
public Long getAvgGetSize()

Return Value
Type: Long

getAvgGetTime()
Returns the average time taken to get a key from the partition, in nanoseconds.

Signature
public Long getAvgGetTime()

Return Value
Type: Long

getAvgValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the partition, in bytes.

Signature
public Long getAvgValueSize()

Return Value
Type: Long

getCapacity()
Returns the percentage of cache used of the total capacity for this partition.

Signature
public Double getCapacity()

Return Value
Type: Double
Used partition cache as a percentage number.

250
Apex Reference Guide Partition Class

getKeys()
Returns a set of all keys that are stored in the cache partition and visible to the invoking namespace.

Signature
public Set<String> getKeys()

Return Value
Type: Set<String>
A set containing all cache keys.

getMaxGetSize()
Returns the maximum item size of all the keys fetched from the partition, in bytes.

Signature
public Long getMaxGetSize()

Return Value
Type: Long

getMaxGetTime()
Returns the maximum time taken to get a key from the partition, in nanoseconds.

Signature
public Long getMaxGetTime()

Return Value
Type: Long

getMaxValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the partition, in bytes.

Signature
public Long getMaxValueSize()

Return Value
Type: Long

251
Apex Reference Guide Partition Class

getMissRate()
Returns the miss rate in the partition.

Signature
public Double getMissRate()

Return Value
Type: Double

getName()
Returns the name of this cache partition.

Signature
public String getName()

Return Value
Type: String
The name of this cache partition.

getNumKeys()
Returns the total number of keys in the partition.

Signature
public Long getNumKeys()

Return Value
Type: Long

isAvailable()
Returns true if the Salesforce session is available. Only applies to Cache.SessionPartition. The session cache isn’t available
when an active session isn’t present, such as in asynchronous Apex or code called by asynchronous Apex. For example, if batch Apex
causes an Apex trigger to execute, the session cache isn’t available in the trigger because the trigger runs in asynchronous context.

Signature
public Boolean isAvailable()

Return Value
Type: Boolean

252
Apex Reference Guide Partition Class

put(key, value)
Stores the specified key/value pair as a cached entry in the cache partition. The put method can write only to the cache in your org’s
namespace.

Signature
public void put(String key, Object value)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.
value
Type: Object
The value to store in the cache. The cached value must be serializable.

Return Value
Type: void

put(key, value, visibility)


Stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s visibility.

Signature
public void put(String key, Object value, cache.Visibility visibility)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing
from any namespace.

Return Value
Type: void

253
Apex Reference Guide Partition Class

put(key, value, ttlSecs)


Stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s lifetime.

Signature
public void put(String key, Object value, Integer ttlSecs)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the cache.

Return Value
Type: void

put(key, value, ttlSecs, visibility, immutable)


Stores the specified key/value pair as a cached entry in the cache partition. This method also sets the cached value’s lifetime, visibility,
and whether it can be overwritten by another namespace.

Signature
public void put(String key, Object value, Integer ttlSecs, cache.Visibility visibility,
Boolean immutable)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the cache.
visibility
Type: Cache.Visibility

254
Apex Reference Guide Partition Class

Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing
from any namespace.
immutable
Type: Boolean
Indicates whether the cached value can be overwritten by another namespace (false) or not (true).

Return Value
Type: void

remove(key)
Deletes the cached value corresponding to the specified key from this cache partition.

Signature
public Boolean remove(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value.

Return Value
Type: Boolean
true if the cache value was successfully removed. Otherwise, false.

remove(cacheBuilder, key)
Deletes the cached value corresponding to the specified key from the partition cache. Use this method if your cached value is a class
that implements the CacheBuilder interface.

Signature
public Boolean remove(System.Type cacheBuilder, String key)

Parameters
cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely
identifies a cached value.

255
Apex Reference Guide Partition Class

Return Value
Type: Boolean
true if the cache value was successfully removed. Otherwise, false.

validateCacheBuilder(cacheBuilder)
Validates that the specified class implements the CacheBuilder interface.

Signature
public static void validateCacheBuilder(System.Type cacheBuilder)

Parameters
cacheBuilder
Type: System.Type
The class to validate.

Return Value
Type: void

validateKey(isDefault, key)
Validates a cache key. This method throws a Cache.InvalidParamException if the key is not valid. A valid key is not null
and contains alphanumeric characters.

Signature
public static void validateKey(Boolean isDefault, String key)

Parameters
isDefault
Type: Boolean
Set to true if the key references a default partition. Otherwise, set to false.
key
Type: String
The key to validate.

Return Value
Type: void

validateKeyValue(isDefault, key, value)


Validates a cache key and ensures that the cache value is non-null. This method throws a Cache.InvalidParamException if
the key or value is not valid. A valid key is not null and contains alphanumeric characters.

256
Apex Reference Guide Partition Class

Signature
public static void validateKeyValue(Boolean isDefault, String key, Object value)

Parameters
isDefault
Type: Boolean
Set to true if the key references a default partition. Otherwise, set to false.
key
Type: String
The key to validate.
value
Type: Object
The cache value to validate.

Return Value
Type: void

validateKeys(isDefault, keys)
Validates the specified cache keys. This method throws a Cache.InvalidParamException if the key is not valid. A valid key
is not null and contains alphanumeric characters.

Signature
public static void validateKeys(Boolean isDefault, Set<String> keys)

Parameters
isDefault
Type: Boolean
Set to true if the key references a default partition. Otherwise, set to false.
keys
Type: Set<String>
A set of key string values to validate.

Return Value
Type: void

validatePartitionName(name)
Validates the partition name — for example, that it is not null.

257
Apex Reference Guide Session Class

Signature
public static void validatePartitionName(String name)

Parameters
name
Type: String
The name of the partition to validate.

Return Value
Type: void

Session Class
Use the Cache.Session class to add, retrieve, and manage values in the session cache. The session cache is active as long as the
user’s Salesforce session is valid (the user is logged in, and the session is not expired).

Namespace
Cache

Usage
Cache Key Format
This table lists the format of the key parameter that some methods in this class take, such as put, get, and contains.

Key Format Description


namespace.partition.key Fully qualified key name.

key Refers to a partition marked as default when the


namespace.partition prefix is omitted.

local.partition.key Use the local prefix to refer to the org’s namespace when the
org doesn’t have a namespace defined. If the org has a namespace
defined, the local prefix also refers to that org’s namespace.

Note:
• If no default partition is specified in the org, calling a cache method without fully qualifying the key name causes a
Cache.Session.SessionCacheException to be thrown.
• The local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s
namespace. The cache put calls are not allowed in a partition that the invoking class doesn’t own.

258
Apex Reference Guide Session Class

Example
This class is the controller for a sample Visualforce page (shown in the subsequent code sample). The cached values are initially added
to the cache by the init() method, which the Visualforce page invokes when it loads through the action attribute. The cache
keys don’t contain the namespace.partition prefix. They all refer to a default partition in your org. The Visualforce page expects
a partition named myPartition. To run this sample, create a default partition in your org with the name myPartition.
The Visualforce page contains four output components. The first three components call get methods on the controller that return the
following values from the cache: a date, data based on the MyData inner class, and a counter. The next output component uses the
$Cache.Session global variable to get the cached string value for the key named output. Next, the $Cache.Session global
variable is used again in the Visualforce page to iterate over the elements of a cached value of type List. The size of the list is also
returned.
The Visualforce page also contains two buttons. The Rerender button invokes the go() method on the controller. This method increases
the values of the counter and the custom data in the cache. If you click Rerender, the two counters increase by one each time. The
go() method retrieves the values of these counters from the cache, increments their values by one, and stores them again in the
cache.
The Remove button deletes the date-time value (with key datetime) from the cache. As a result, the value next to Cached
datetime: is cleared on the page.

public class SessionCacheController {

// Inner class.
// Used as the data type of a cache value.
class MyData {
public String value { get; set; }
public Integer counter { get; set; }

public MyData(String value) {


this.value = value;
this.counter = 0;
}

public void inc() {


counter++;
}

override public String toString() {


return this.value + ':' + this.counter;
}
}

// Apex List.
// Used as the data type of a cached value.
private List<String> numbers =
new List<String> { 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE' };

// Constructor of the controller for the Visualforce page.


public SessionCacheController() {
}

// Adds various values to the cache.


// This method is called when the Visualforce page loads.
public void init() {

259
Apex Reference Guide Session Class

// All key values are not qualified by the namespace.partition


// prefix because they use the default partition.

// Add counter to the cache with initial value of 0


// or increment it if it's already there.
if (!Cache.Session.contains('counter')) {
Cache.Session.put('counter', 0);
} else {
Cache.Session.put('counter', getCounter() + 1);
}

// Add the datetime value to the cache only if it's not already there.
if (!Cache.Session.contains('datetime')) {
DateTime dt = DateTime.now();
Cache.Session.put('datetime', dt);
}

// Add the custom data to the cache only if it's not already there.
if (!Cache.Session.contains('data')) {
Cache.Session.put('data', new MyData('Some custom value'));
}

// Add a list of number to the cache if not already there.


if (!Cache.Session.contains('list')) {
Cache.Session.put('list', numbers);
}

// Add a string value to the cache if not already there.


if (!Cache.Session.contains('output')) {
Cache.Session.put('output', 'Cached text value');
}
}

// Return counter from the cache.


public Integer getCounter() {
return (Integer)Cache.Session.get('counter');
}

// Return datetime value from the cache.


public String getCachedDatetime() {
DateTime dt = (DateTime)Cache.Session.get('datetime');
return dt != null ? dt.format() : null;
}

// Return cached value whose type is the inner class MyData.


public String getCachedData() {
MyData mydata = (MyData)Cache.Session.get('data');
return mydata != null ? mydata.toString() : null;
}

// Method invoked by the Rerender button on the Visualforce page.


// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.

260
Apex Reference Guide Session Class

public PageReference go() {


// Increase the cached counter value or set it to 0
// if it's not cached.
if (Cache.Session.contains('counter')) {
Cache.Session.put('counter', getCounter() + 1);
} else {
Cache.Session.put('counter', 0);
}

// Get the custom data value from the cache.


MyData d = (MyData)Cache.Session.get('data');
// Only if the data is already in the cache, update it.
if (Cache.Session.contains('data')) {
d.inc();
Cache.Session.put('data', d);
}

return null;
}

// Method invoked by the Remove button on the Visualforce page.


// Removes the datetime cached value from the session cache.
public PageReference remove() {
Cache.Session.remove('datetime');

return null;
}
}

This is the Visualforce page that corresponds to the SessionCacheController class.


<apex:page controller="SessionCacheController" action="{!init}">

<apex:outputPanel id="output">
<br/>Cached datetime: <apex:outputText value="{!cachedDatetime}"/>
<br/>Cached data: <apex:outputText value="{!cachedData}"/>
<br/>Cached counter: <apex:outputText value="{!counter}"/>
<br/>Output: <apex:outputText value="{!$Cache.Session.local.myPartition.output}"/>

<br/>Repeat: <apex:repeat var="item"


value="{!$Cache.Session.local.myPartition.list}">
<apex:outputText value="{!item}"/>&nbsp;
</apex:repeat>
<br/>List size: <apex:outputText
value="{!$Cache.Session.local.myPartition.list.size}"/>
</apex:outputPanel>

<br/><br/>
<apex:form >
<apex:commandButton id="go" action="{!go}" value="Rerender" rerender="output"/>
<apex:commandButton id="remove" action="{!remove}" value="Remove datetime Key"
rerender="output"/>
</apex:form>

</apex:page>

261
Apex Reference Guide Session Class

This is the output of the page after clicking the Rerender button twice. The counter value could differ in your case if a key named
counter was already in the cache before running this sample.

Cached datetime:8/11/2015 1:58 PM


Cached data:Some custom value:2
Cached counter:2
Output:Cached text value
Repeat:ONE TWO THREE FOUR FIVE
List size:5

IN THIS SECTION:
Session Constants
The Session class provides a constant that you can use when setting the time-to-live (TTL) value.
Session Methods

SEE ALSO:
Apex Developer Guide: Platform Cache

Session Constants
The Session class provides a constant that you can use when setting the time-to-live (TTL) value.

Constant Description
MAX_TTL_SECS Represents the maximum amount of time, in seconds, to keep the cached value in the
session cache.

Session Methods
The following are methods for Session. All methods are static.

IN THIS SECTION:
contains(key)
Returns true if the session cache contains a cached value corresponding to the specified key.
contains(setOfKeys)
Returns true if the cache contains values for a specified set of keys.
get(key)
Returns the cached value corresponding to the specified key from the session cache.
get(keys)
Returns the cached values corresponding to the specified set of keys from the session cache.
get(cacheBuilder, key)
Returns the cached value corresponding to the specified key from the session cache. Use this method if your cached value is a class
that implements the CacheBuilder interface.

262
Apex Reference Guide Session Class

getAvgGetSize()
Returns the average item size of all the keys fetched from the session cache, in bytes.
getAvgGetTime()
Returns the average time taken to get a key from the session cache, in nanoseconds.
getAvgValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the session cache, in
bytes.
getCapacity()
Returns the percentage of session cache capacity that has been used.
getKeys()
Returns all keys that are stored in the session cache and visible to the invoking namespace.
getMaxGetSize()
Returns the maximum item size of all the keys fetched from the session cache, in bytes.
getMaxGetTime()
Returns the maximum time taken to get a key from the session cache, in nanoseconds.
getMaxValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the session cache,
in bytes.
getMissRate()
Returns the miss rate in the session cache.
getName()
Returns the name of the default cache partition.
getNumKeys()
Returns the total number of keys in the session cache.
getPartition(partitionName)
Returns a partition from the session cache that corresponds to the specified partition name.
isAvailable()
Returns true if the session cache is available for use. The session cache isn’t available when an active session isn’t present, such
as in asynchronous Apex or code called by asynchronous Apex. For example, if batch Apex causes an Apex trigger to execute, the
session cache isn’t available in the trigger because the trigger runs in asynchronous context.
put(key, value)
Stores the specified key/value pair as a cached entry in the session cache. The put method can write only to the cache in your org’s
namespace.
put(key, value, visibility)
Stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s visibility.
put(key, value, ttlSecs)
Stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s lifetime.
put(key, value, ttlSecs, visibility, immutable)
Stores the specified key/value pair as a cached entry in the session cache. This method also sets the cached value’s lifetime, visibility,
and whether it can be overwritten by another namespace.

263
Apex Reference Guide Session Class

remove(key)
Deletes the cached value corresponding to the specified key from the session cache.
remove(cacheBuilder, key)
Deletes the cached value corresponding to the specified key from the session cache. Use this method if your cached value is a class
that implements the CacheBuilder interface.

contains(key)
Returns true if the session cache contains a cached value corresponding to the specified key.

Signature
public static Boolean contains(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value
Type: Boolean
true if a cache entry is found. Othewise, false.

contains(setOfKeys)
Returns true if the cache contains values for a specified set of keys.

Signature
public static Map <String, Boolean> contains (Set<String> keys)

Parameters
setOfKeys
Type: Set <String>
A set of keys that uniquely identifies cached values. For information about the format of the key name, see Usage.

Return Value
Type: Map <String, Boolean>
Returns the cache key and corresponding Boolean value indicating that the key entry exists. The Boolean value is false if the key
entry doesn't exist.

Usage
The number of input keys cannot exceed the maximum limit of 10.

264
Apex Reference Guide Session Class

Example
In this example, the code checks for the presence of multiple keys on the default partition. It fetches the cache key and the corresponding
Boolean value for the key entry from the session cache of the default partition.
Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};
Map<String,Boolean> result = Cache.Session.contains(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('Is Key Present in the cache : ' + result.get(key));
}

In this example, the code checks for the presence of multiple keys on different partitions. It fetches the cache key and the corresponding
Boolean value for the key entry from the session cache of different partitions.
// Assuming there are three partitions p1, p2, p3 with default 'local' namespace

Set<String> keys = new Set<String>{'local.p1.key','local.p2.key', 'local.p3.key'};


Map<String,Boolean> result = Cache.Session.contains(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('Is Key Present in the cache : + result.get(key));
}

get(key)
Returns the cached value corresponding to the specified key from the session cache.

Signature
public static Object get(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.

Usage
Because Cache.Session.get() returns an object, we recommend that you cast the returned value to a specific type to facilitate
use of the returned value.
// Get a cached value
Object obj = Cache.Session.get('ns1.partition1.orderDate');
// Cast return value to a specific data type
DateTime dt2 = (DateTime)obj;

265
Apex Reference Guide Session Class

If a Cache.Session.get() call doesn’t find the referenced key, it returns null.

get(keys)
Returns the cached values corresponding to the specified set of keys from the session cache.

Signature
public static Map <String, Object> get (Set <String> keys)

Parameters
keys
Type: Set <String>
A set of keys that uniquely identify cached values. For information about the format of the key name, see Usage.

Return Value
Type: Map <String, Object>
Returns the cache key and corresponding value. Returns null when no corresponding value is found for an input key.

Usage
The number of input keys cannot exceed the maximum limit of 10.

Example
Fetch multiple keys from the session cache of the default partition.
Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};
Map<String,Object> result = Cache.Session.get(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

Fetch multiple keys from the session cache of different partitions.


// Assuming there are three partitions p1, p2, p3 with default 'local' namespace

Set<String> keys = new Set<String>{'local.p1.key','local.p2.key', 'local.p3.key'};


Map<String,Object> result = Cache.Session.get(keys);
for(String key : result.keySet()) {
system.debug('key: ' + key);
system.debug('value: ' + result.get(key));
}

get(cacheBuilder, key)
Returns the cached value corresponding to the specified key from the session cache. Use this method if your cached value is a class that
implements the CacheBuilder interface.

266
Apex Reference Guide Session Class

Signature
public static Object get(System.Type cacheBuilder, String key)

Parameters
cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely
identifies a cached value.

Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.

Usage
Because Cache.Session.get(cacheBuilder, key) returns an object, cast the returned value to a specific type to facilitate
use of the returned value.
return ((DateTime)Cache.Session.get(DateCache.class, 'datetime')).format();

getAvgGetSize()
Returns the average item size of all the keys fetched from the session cache, in bytes.

Signature
public static Long getAvgGetSize()

Return Value
Type: Long

getAvgGetTime()
Returns the average time taken to get a key from the session cache, in nanoseconds.

Signature
public static Long getAvgGetTime()

Return Value
Type: Long

267
Apex Reference Guide Session Class

getAvgValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the session cache, in bytes.

Signature
public static Long getAvgValueSize()

Return Value
Type: Long

getCapacity()
Returns the percentage of session cache capacity that has been used.

Signature
public static Double getCapacity()

Return Value
Type: Double
Used cache as a percentage number.

getKeys()
Returns all keys that are stored in the session cache and visible to the invoking namespace.

Signature
public static Set<String> getKeys()

Return Value
Type: Set<String>
A set containing all cache keys.

getMaxGetSize()
Returns the maximum item size of all the keys fetched from the session cache, in bytes.

Signature
public static Long getMaxGetSize()

Return Value
Type: Long

268
Apex Reference Guide Session Class

getMaxGetTime()
Returns the maximum time taken to get a key from the session cache, in nanoseconds.

Signature
public static Long getMaxGetTime()

Return Value
Type: Long

getMaxValueSize()
Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the session cache, in
bytes.

Signature
public static Long getMaxValueSize()

Return Value
Type: Long

getMissRate()
Returns the miss rate in the session cache.

Signature
public static Double getMissRate()

Return Value
Type: Double

getName()
Returns the name of the default cache partition.

Signature
public String getName()

Return Value
Type: String
The name of the default cache partition.

269
Apex Reference Guide Session Class

getNumKeys()
Returns the total number of keys in the session cache.

Signature
public static Long getNumKeys()

Return Value
Type: Long

getPartition(partitionName)
Returns a partition from the session cache that corresponds to the specified partition name.

Signature
public static cache.SessionPartition getPartition(String partitionName)

Parameters
partitionName
Type: String
A partition name that is qualified by the namespace, for example, namespace.partition.

Return Value
Type: Cache.SessionPartition

Example
After you get the session partition, you can add and retrieve the partition’s cache values.
// Get partition
Cache.SessionPartition sessionPart = Cache.Session.getPartition('myNs.myPartition');
// Retrieve cache value from the partition
if (sessionPart.contains('BookTitle')) {
String cachedTitle = (String)sessionPart.get('BookTitle');
}

// Add cache value to the partition


sessionPart.put('OrderDate', Date.today());

// Or use dot notation to call partition methods


String cachedAuthor =
(String)Cache.Session.getPartition('myNs.myPartition').get('BookAuthor');

270
Apex Reference Guide Session Class

isAvailable()
Returns true if the session cache is available for use. The session cache isn’t available when an active session isn’t present, such as in
asynchronous Apex or code called by asynchronous Apex. For example, if batch Apex causes an Apex trigger to execute, the session
cache isn’t available in the trigger because the trigger runs in asynchronous context.

Signature
public static Boolean isAvailable()

Return Value
Type: Boolean
true if the session cache is available. Otherwise, false.

put(key, value)
Stores the specified key/value pair as a cached entry in the session cache. The put method can write only to the cache in your org’s
namespace.

Signature
public static void put(String key, Object value)

Parameters
key
Type: String
A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.

Return Value
Type: void

put(key, value, visibility)


Stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s visibility.

Signature
public static void put(String key, Object value, Cache.Visibility visibility)

Parameters
key
Type: String

271
Apex Reference Guide Session Class

A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing
from any namespace.

Return Value
Type: void

put(key, value, ttlSecs)


Stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s lifetime.

Signature
public static void put(String key, Object value, Integer ttlSecs)

Parameters
key
Type: String
A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the session cache. The cached values remain in the cache as long as
the Salesforce session hasn’t expired. The maximum value is 28,800 seconds or eight hours. The minimum value is 300 seconds or
five minutes.

Return Value
Type: void

put(key, value, ttlSecs, visibility, immutable)


Stores the specified key/value pair as a cached entry in the session cache. This method also sets the cached value’s lifetime, visibility,
and whether it can be overwritten by another namespace.

272
Apex Reference Guide Session Class

Signature
public static void put(String key, Object value, Integer ttlSecs, cache.Visibility
visibility, Boolean immutable)

Parameters
key
Type: String
A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the session cache. The cached values remain in the cache as long as
the Salesforce session hasn’t expired. The maximum value is 28,800 seconds or eight hours. The minimum value is 300 seconds or
five minutes.
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing
from any namespace.
immutable
Type: Boolean
Indicates whether the cached value can be overwritten by another namespace (false) or not (true).

Return Value
Type: void

remove(key)
Deletes the cached value corresponding to the specified key from the session cache.

Signature
public static Boolean remove(String key)

Parameters
key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value
Type: Boolean

273
Apex Reference Guide SessionPartition Class

true if the cache value was successfully removed. Otherwise, false.

remove(cacheBuilder, key)
Deletes the cached value corresponding to the specified key from the session cache. Use this method if your cached value is a class that
implements the CacheBuilder interface.

Signature
public static Boolean remove(System.Type cacheBuilder, String key)

Parameters
cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely
identifies a cached value.

Return Value
Type: Boolean
true if the cache value was successfully removed. Otherwise, false.

SessionPartition Class
Contains methods to manage cache values in the session cache of a specific partition.

Namespace
Cache

Usage
This class extends Cache.Partition and inherits all of its non-static methods. Utility methods for creating and validating keys are not
supported and can be called only from the Cache.Partition parent class. For a list of Cache.Partition methods, see
Partition Methods.
To get a session partition, call Cache.Session.getPartition and pass in a fully qualified partition name, as follows.
Cache.SessionPartition sessionPartition =
Cache.Session.getPartition('namespace.myPartition');

See Cache Key Format for Partition Methods.

274
Apex Reference Guide SessionPartition Class

Example
This class is the controller for a sample Visualforce page (shown in the subsequent code sample). The controller shows how to use the
methods of Cache.SessionPartition to manage a cache value on a particular partition. The controller takes inputs from the
Visualforce page for the partition name, key name for a counter, and initial counter value. The controller contains default values for these
inputs. When you click Rerender on the Visualforce page, the go() method is invoked and increases the counter by one. When you
click Remove Key, the counter key is removed from the cache. The counter value gets reset to its initial value when it’s re-added to the
cache.
public class SessionPartitionController {

// Name of a partition in the local namespace


String partitionInput = 'local.myPartition';
// Name of the key
String counterKeyInput = 'counter';
// Key initial value
Integer counterInitValue = 0;
// Session partition object
Cache.SessionPartition sessionPartition;

// Constructor of the controller for the Visualforce page.


public SessionPartitionController() {
}

// Adds counter value to the cache.


// This method is called when the Visualforce page loads.
public void init() {
// Create the partition instance based on the partition name
sessionPartition = getPartition();

// Add counter to the cache with an initial value


// or increment it if it's already there.
if (!sessionPartition.contains(counterKeyInput)) {
sessionPartition.put(counterKeyInput, counterInitValue);
} else {
sessionPartition.put(counterKeyInput, getCounter() + 1);
}
}

// Returns the session partition based on the partition name


// given in the Visualforce page or the default value.
private Cache.SessionPartition getPartition() {
if (sessionPartition == null) {
sessionPartition = Cache.Session.getPartition(partitionInput);
}

return sessionPartition;
}

// Return counter from the cache.


public Integer getCounter() {
return (Integer)getPartition().get(counterKeyInput);
}

275
Apex Reference Guide SessionPartition Class

// Invoked by the Submit button to save input values


// supplied by the user.
public PageReference save() {
// Reset the initial key value in the cache
getPartition().put(counterKeyInput, counterInitValue);

return null;
}

// Method invoked by the Rerender button on the Visualforce page.


// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go() {
// Get the partition object
sessionPartition = getPartition();
// Increase the cached counter value or set it to 0
// if it's not cached.
if (sessionPartition.contains(counterKeyInput)) {
sessionPartition.put(counterKeyInput, getCounter() + 1);
} else {
sessionPartition.put(counterKeyInput, counterInitValue);
}

return null;
}

// Method invoked by the Remove button on the Visualforce page.


// Removes the datetime cached value from the session cache.
public PageReference remove() {
getPartition().remove(counterKeyInput);

return null;
}

// Get and set methods for accessing variables


// that correspond to the input text fields on
// the Visualforce page.
public String getPartitionInput() {
return partitionInput;
}

public String getCounterKeyInput() {


return counterKeyInput;
}

public Integer getCounterInitValue() {


return counterInitValue;
}

public void setPartitionInput(String partition) {


this.partitionInput = partition;
}

276
Apex Reference Guide Cache Exceptions

public void setCounterKeyInput(String keyName) {


this.counterKeyInput = keyName;
}

public void setCounterInitValue(Integer counterValue) {


this.counterInitValue = counterValue;
}
}

This is the Visualforce page that corresponds to the SessionPartitionController class.


<apex:page controller="SessionPartitionController" action="{!init}">

<apex:form >
<br/>Partition with Namespace Prefix: <apex:inputText value="{!partitionInput}"/>

<br/>Counter Key Name: <apex:inputText value="{!counterKeyInput}"/>


<br/>Counter Initial Value: <apex:inputText value="{!counterInitValue}"/>
<apex:commandButton action="{!save}" value="Save Key Input Values"/>
</apex:form>

<apex:outputPanel id="output">
<br/>Cached Counter: <apex:outputText value="{!counter}"/>
</apex:outputPanel>

<br/>
<apex:form >
<apex:commandButton id="go" action="{!go}" value="Rerender" rerender="output"/>
<apex:commandButton id="remove" action="{!remove}" value="Remove Key"
rerender="output"/>
</apex:form>

</apex:page>

SEE ALSO:
Apex Developer Guide: Platform Cache

Cache Exceptions
The Cache namespace contains exception classes.
All exception classes support built-in methods for returning the error message and exception type. See Exception Class and Built-In
Exceptions on page 3658 in the Apex Developer Guide.
The Cache namespace contains these exceptions.

Exception Thrown when


Cache.Session.SessionCacheException An error occurred while adding or retrieving a value in the session
cache.

Cache.Session.SessionCacheNoSessionException An attempt is made to access the cache when the session cache
isn’t available.

277
Apex Reference Guide Visibility Enum

Exception Thrown when


Cache.Org.OrgCacheException An attempt is made to access a partition that doesn’t exist or whose
name is invalid.

Cache.InvalidParamException An invalid parameter value is passed into a method of


Cache.Session or Cache.Org. This error occurs when:
• The key referenced is null or empty or is not alphanumeric.
• The key isn’t qualified with the namespace and partition in the
format <namespace>.<partition>.<key>.
• The key isn’t qualified in the format <key> for the default
partition, or for a key inserted through the partition object.
• The namespace referenced is null or empty.
• The partition name is null or empty or is not alphanumeric.
• Another referenced value is null.

Cache.ItemSizeLimitExceededException A cache put call is made with an item that exceeds the maximum
size limit. To fix this error, break the item into multiple, smaller items.

Cache.BulkApiKeysLimitExceededException The number of key parameters passed into a bulk method -


get(keys) or contains(setOfKeys) exceeds the
maximum limit of 10.

Cache.PlatformCacheInvalidOperationException A cache put or remove call is made that is not allowed. For
example, when calling put or remove inside a Visualforce
constructor.

Cache.CacheBuilderExecutionException This error occurs when the execution of the CacheBuilder fails; this
could be due to an error in parsing, a permissions error while
accessing records, or an issue with Apex callouts.

Cache.InvalidCacheBuilderException A get(CacheBuilder cb, String key),


remove(CacheBuilder cb, String key), or
validateCacheBuilder(CacheBuilder cb) method
is called but the cb parameter is a class that does not implement
the Cache.CacheBuilder interface.

Visibility Enum
Use the Cache.Visibility enumeration in the Cache.Session or Cache.Org methods to indicate whether a cached
value is visible only in the value’s namespace or in all namespaces.

Enum Values
The following are the values of the Cache.Visibility enum.

278
Apex Reference Guide Canvas Namespace

Value Description
ALL The cached value is available to Apex code executing
from any namespace. This is the default state.

NAMESPACE The cached value is available to Apex code executing


from the same namespace.
If a key has the Visibility.NAMESPACE
attribute, a get method initiated from a different
namespace returns null.

Canvas Namespace
The Canvas namespace provides an interface and classes for canvas apps in Salesforce.
The following are the interfaces and classes in the Canvas namespace.

IN THIS SECTION:
ApplicationContext Interface
Use this interface to retrieve application context information, such as the application version or URL.
CanvasLifecycleHandler Interface
Implement this interface to control context information and add custom behavior during the application render phase.
ContextTypeEnum Enum
Describes context data that can be excluded from canvas app context data. You specify which context types to exclude in the
excludeContextTypes() method in your CanvasLifecycleHandler implementation.
EnvironmentContext Interface
Use this interface to retrieve environment context information, such as the app display location or the configuration parameters.
RenderContext Interface
A wrapper interface that is used to retrieve application and environment context information.
Test Class
Contains methods for automated testing of your Canvas classes.
Canvas Exceptions
The Canvas namespace contains exception classes.

SEE ALSO:
Canvas Developer Guide

ApplicationContext Interface
Use this interface to retrieve application context information, such as the application version or URL.

279
Apex Reference Guide ApplicationContext Interface

Namespace
Canvas

Usage
The ApplicationContext interface provides methods to retrieve application information about the canvas app that’s being
rendered. Most of the methods are read-only. For this interface, you don’t need to create an implementation. Use the default
implementation that Salesforce provides.

IN THIS SECTION:
ApplicationContext Methods

ApplicationContext Methods
The following are methods for ApplicationContext.

IN THIS SECTION:
getCanvasUrl()
Retrieves the fully qualified URL of the canvas app.
getDeveloperName()
Retrieves the internal API name of the canvas app.
getName()
Retrieves the name of the canvas app.
getNamespace()
Retrieves the namespace prefix of the canvas app.
getVersion()
Retrieves the current version of the canvas app.
setCanvasUrlPath(newPath)
Overrides the URL of the canvas app for the current request.

getCanvasUrl()
Retrieves the fully qualified URL of the canvas app.

Signature
public String getCanvasUrl()

Return Value
Type: String

280
Apex Reference Guide ApplicationContext Interface

Usage
Use this method to get the URL of the canvas app, for example:
http://instance.salesforce.com:8080/canvas_app_path/canvas_app.jsp.

getDeveloperName()
Retrieves the internal API name of the canvas app.

Signature
public String getDeveloperName()

Return Value
Type: String

Usage
Use this method to get the API name of the canvas app. You specify this value in the API Name field when you expose the canvas
app by creating a connected app.

getName()
Retrieves the name of the canvas app.

Signature
public String getName()

Return Value
Type: String

Usage
Use this method to get the name of the canvas app.

getNamespace()
Retrieves the namespace prefix of the canvas app.

Signature
public String getNamespace()

Return Value
Type: String

281
Apex Reference Guide ApplicationContext Interface

Usage
Use this method to get the Salesforce namespace prefix that’s associated with the canvas app.

getVersion()
Retrieves the current version of the canvas app.

Signature
public String getVersion()

Return Value
Type: String

Usage
Use this method to get the current version of the canvas app. This value changes after you update and republish a canvas app in an
organization. If you are in a Developer Edition organization, using this method always returns the latest version.

setCanvasUrlPath(newPath)
Overrides the URL of the canvas app for the current request.

Signature
public void setCanvasUrlPath(String newPath)

Parameters
newPath
Type: String
The URL (not including domain) that you need to use to override the canvas app URL.

Return Value
Type: Void

Usage
Use this method to override the URL path and query string of the canvas app. Do not provide a fully qualified URL, because the provided
URL string will be appended to the original canvas URL domain.
For example, if the current canvas app URL is https://myserver.com:6000/myAppPath and you call
setCanvasUrlPath('/alternatePath/args?arg1=1&arg2=2'), the adjusted canvas app URL will be
https://myserver.com:6000/alternatePath/args?arg1=1&arg2=2.
If the provided path results in a malformed URL, or a URL that exceeds 2,048 characters, a System.CanvasException will be thrown.
This method overrides the canvas app URL for the current request and does not permanently change the canvas app URL as configured
in the UI for the Salesforce canvas app settings.

282
Apex Reference Guide CanvasLifecycleHandler Interface

CanvasLifecycleHandler Interface
Implement this interface to control context information and add custom behavior during the application render phase.

Namespace
Canvas

Usage
Use this interface to specify what canvas context information is provided to your app by implementing the excludeContextTypes()
method. Use this interface to call custom code when the app is rendered by implementing the onRender() method.
If you provide an implementation of this interface, you must implement excludeContextTypes() and onRender().

Example Implementation
The following example shows a simple implementation of CanvasLifecycleHandler that specifies that organization context information
will be excluded and prints a debug message when the app is rendered.
public class MyCanvasListener
implements Canvas.CanvasLifecycleHandler{
public Set<Canvas.ContextTypeEnum> excludeContextTypes(){
Set<Canvas.ContextTypeEnum> excluded = new Set<Canvas.ContextTypeEnum>();
excluded.add(Canvas.ContextTypeEnum.ORGANIZATION);
return excluded;
}

public void onRender(Canvas.RenderContext renderContext){


System.debug('Canvas lifecycle called.');
}
}

IN THIS SECTION:
CanvasLifecycleHandler Methods

SEE ALSO:
Canvas Developer Guide: Customizing Your App Lifecycle

CanvasLifecycleHandler Methods
The following are methods for CanvasLifecycleHandler.

IN THIS SECTION:
excludeContextTypes()
Lets the implementation exclude parts of the CanvasRequest context, if the application does not need it.

283
Apex Reference Guide CanvasLifecycleHandler Interface

onRender(renderContext)
Invoked when a canvas app is rendered. Provides the ability to set and retrieve canvas application and environment context information
during the application render phase.

excludeContextTypes()
Lets the implementation exclude parts of the CanvasRequest context, if the application does not need it.

Signature
public Set<Canvas.ContextTypeEnum> excludeContextTypes()

Return Value
Type: SET<Canvas.ContextTypeEnum>
This method must return null or a set of zero or more ContextTypeEnum values. Returning null enables all attributes by default.
ContextTypeEnum values that can be set are:
• Canvas.ContextTypeEnum.ORGANIZATION
• Canvas.ContextTypeEnum.RECORD_DETAIL
• Canvas.ContextTypeEnum.USER
See ContextTypeEnum on page 285 for more details on these values.

Usage
Implement this method to specify which attributes to disable in the context of the canvas app. A disabled attribute will set the associated
canvas context information to null.
Disabling attributes can help improve performance by reducing the size of the signed request and canvas context. Also, disabled attributes
do not need to be retrieved by Salesforce, which further improves performance.
See the Canvas Developer Guide for more information on context information in the Context object that’s provided in the CanvasRequest.

Example
This example implementation specifies that the organization information will be disabled in the canvas context.
public Set<Canvas.ContextTypeEnum> excludeContextTypes() {
Set<Canvas.ContextTypeEnum> excluded = new Set<Canvas.ContextTypeEnum>();
excluded.add(Canvas.ContextTypeEnum.ORGANIZATION);
return excluded;
}

SEE ALSO:
Canvas Developer Guide: Filtering CanvasRequest Context Data

onRender(renderContext)
Invoked when a canvas app is rendered. Provides the ability to set and retrieve canvas application and environment context information
during the application render phase.

284
Apex Reference Guide ContextTypeEnum Enum

Signature
public void onRender(Canvas.RenderContext renderContext)

Parameters
renderContext
Type: Canvas.RenderContext

Return Value
Type: Void

Usage
If implemented, this method is called whenever the canvas app is rendered. The implementation can set and retrieve context information
by using the provided Canvas.RenderContext.
This method is called whenever signed request or context information is retrieved by the client. See the Canvas Developer Guide for more
information on signed request authentication.

Example
This example implementation prints ‘Canvas lifecycle called.’ to the debug log when the canvas app is rendered.
public void onRender(Canvas.RenderContext renderContext) {
System.debug('Canvas lifecycle called.');
}

SEE ALSO:
Canvas Developer Guide: Controlling App Behavior

ContextTypeEnum Enum
Describes context data that can be excluded from canvas app context data. You specify which context types to exclude in the
excludeContextTypes() method in your CanvasLifecycleHandler implementation.

Namespace
Canvas

Enum Values
Value Description
ORGANIZATION Exclude context information about the organization in which the canvas app is
running.

RECORD_DETAIL Exclude context information about the object record on which the canvas app
appears.

285
Apex Reference Guide EnvironmentContext Interface

Value Description
USER Exclude context information about the current user.

EnvironmentContext Interface
Use this interface to retrieve environment context information, such as the app display location or the configuration parameters.

Namespace
Canvas

Usage
The EnvironmentContext interface provides methods to retrieve environment information about the current canvas app. For
this interface, you don’t need to create an implementation. Use the default implementation that Salesforce provides.

IN THIS SECTION:
EnvironmentContext Methods

EnvironmentContext Methods
The following are methods for EnvironmentContext.

IN THIS SECTION:
addEntityField(fieldName)
Adds a field to the list of object fields that are returned in the signed request Record object when the component appears on a
Visualforce page that’s placed on an object.
addEntityFields(fieldNames)
Adds a set of fields to the list of object fields that are returned in the signed request Record object when the component appears
on a Visualforce page that’s placed on an object.
getDisplayLocation()
Retrieves the display location where the canvas app is being called from. For example, a value of Visualforce page.
getEntityFields()
Retrieves the list of object fields that are returned in the signed request Record object when the component appears on a Visualforce
page that’s placed on an object.
getLocationUrl()
Retrieves the location URL of the canvas app.
getParametersAsJSON()
Retrieves the current custom parameters for the canvas app. Parameters are returned as a JSON string.
getSublocation()
Retrieves the display sublocation where the canvas app is being called from.

286
Apex Reference Guide EnvironmentContext Interface

setParametersAsJSON(jsonString)
Sets the custom parameters for the canvas app.

addEntityField(fieldName)
Adds a field to the list of object fields that are returned in the signed request Record object when the component appears on a Visualforce
page that’s placed on an object.

Signature
public void addEntityField(String fieldName)

Parameters
fieldName
Type: String
The object field name that you need to add to the list of returned fields., Using ‘*’ adds all fields that the user has permission to view.

Return Value
Type: Void

Usage
When you use the <apex:canvasApp> component to display a canvas app on a Visualforce page, and that page is associated with
an object (placed on the page layout, for example), you can specify fields to be returned from the related object. See the Canvas Developer
Guide for more information on the Record object.
Use addEntityField() to add a field to the list of object fields that are returned in the signed request Record object. By default
the list of fields includes ID. You can add fields by name or add all fields that the user has permission to view by calling
addEntityField('*').
You can inspect the configured list of fields by using Canvas.EnvironmentContext.getEntityFields().

Example
This example adds the Name and BillingAddress fields to the list of object fields. This example assumes the canvas app will appear in a
Visualforce page that's associated with the Account page layout.
Canvas.EnvironmentContext env = renderContext.getEnvironmentContext();

// Add Name and BillingAddress to fields (assumes we'll run from the Account detail page)
env.addEntityField('Name');
env.addEntityField('BillingAddress');

addEntityFields(fieldNames)
Adds a set of fields to the list of object fields that are returned in the signed request Record object when the component appears on a
Visualforce page that’s placed on an object.

287
Apex Reference Guide EnvironmentContext Interface

Signature
public void addEntityFields(Set<String> fieldNames)

Parameters
fieldNames
Type: SET<String>
The set of object field names that you need to add to the list of returned fields. If an item in the set is ‘*’, all fields that the user has
permission to view are added.

Return Value
Type: Void

Usage
When you use the <apex:canvasApp> component to display a canvas app on a Visualforce page, and that page is associated with
an object (placed on the page layout, for example), you can specify fields to be returned from the related object. See the Canvas Developer
Guide for more information on the Record object.
Use addEntityFields() to add a set of one or more fields to the list of object fields that are returned in the signed request Record
object. By default the list of fields includes ID. You can add fields by name or add all fields that the user has permission to view by adding
a set that includes ‘*’ as one of the strings.
You can inspect the configured list of fields by using Canvas.EnvironmentContext.getEntityFields().

Example
This example adds the Name, BillingAddress, and YearStarted fields to the list of object fields. This example assumes that the canvas app
will appear in a Visualforce page that’s associated with the Account page layout.
Canvas.EnvironmentContext env = renderContext.getEnvironmentContext();

// Add Name, BillingAddress and YearStarted to fields (assumes we'll run from the Account
detail page)
Set<String> fields = new Set<String>{'Name','BillingAddress','YearStarted'};
env.addEntityFields(fields);

getDisplayLocation()
Retrieves the display location where the canvas app is being called from. For example, a value of Visualforce page.

Signature
public String getDisplayLocation()

Return Value
Type: String
The return value can be one of the following strings:
• Chatter—The canvas app was called from the Chatter tab.

288
Apex Reference Guide EnvironmentContext Interface

• ChatterFeed—The canvas app was called from a Chatter canvas feed item.
• MobileNav—The canvas app was called from the navigation menu.
• OpenCTI—The canvas app was called from an Open CTI component.
• PageLayout—The canvas app was called from an element within a page layout. If the displayLocation is PageLayout, one of the
subLocation values might be returned.
• Publisher—The canvas app was called from a canvas custom quick action.
• ServiceDesk—The canvas app was called from a Salesforce Console component.
• Visualforce—The canvas app was called from a Visualforce page.
• None—The canvas app was called from the Canvas App Previewer.

Usage
Use this method to obtain the display location for the canvas app.

getEntityFields()
Retrieves the list of object fields that are returned in the signed request Record object when the component appears on a Visualforce
page that’s placed on an object.

Signature
public List<String> getEntityFields()

Return Value
Type: LIST<String>

Usage
When you use the <apex:canvasApp> component to display a canvas app on a Visualforce page, and that page is associated with
an object (placed on the page layout, for example), you can specify fields to be returned from the related object. See the Canvas Developer
Guide for more information on the Record object.
Use getEntityFields() to retrieve the list of object fields that are returned in the signed request Record object. By default the list of fields
includes ID. The list of fields can be configured by using the Canvas.EnvironmentContext.addEntityField(fieldName) or
Canvas.EnvironmentContext.addEntityFields(fieldNames) methods.

Example
This example gets the current list of object fields and retrieves each item in the list, printing each field name to the debug log.
Canvas.EnvironmentContext env = renderContext.getEnvironmentContext();

List<String> entityFields = env.getEntityFields();


for (String fieldVal : entityFields) {
System.debug('Environment Context entityField: ' + fieldVal);
}

If the canvas app that’s using this lifecycle code was run from the detail page of an Account, the debug log output might look like:
Environment Context entityField: Id

289
Apex Reference Guide EnvironmentContext Interface

getLocationUrl()
Retrieves the location URL of the canvas app.

Signature
public String getLocationUrl()

Return Value
Type: String

Usage
Use this method to obtain the URL of the page where the user accessed the canvas app. For example, if the user accessed your app by
clicking a link on the Chatter tab, this method returns the URL of the Chatter tab, which would be similar to
‘https://MyDomainName.my.salesforce.com/_ui/core/chatter/ui/ChatterPage’.

getParametersAsJSON()
Retrieves the current custom parameters for the canvas app. Parameters are returned as a JSON string.

Signature
public String getParametersAsJSON()

Return Value
Type: String

Usage
Use this method to get the current custom parameters for the canvas app. The parameters are returned in a JSON string that can be
de-serialized by using the System.JSON.deserializeUntyped(jsonString) method.
Custom parameters can be modified by using the Canvas.EnvironmentContext.setParametersAsJSON(jsonString) string.

Example
This example gets the current custom parameters, de-serializes them into a map, and prints the results to the debug log.
Canvas.EnvironmentContext env = renderContext.getEnvironmentContext();

// Get current custom params


Map<String, Object> currentParams =
(Map<String, Object>) JSON.deserializeUntyped(env.getParametersAsJSON());
System.debug('Environment Context custom paramters: ' + currentParams);

getSublocation()
Retrieves the display sublocation where the canvas app is being called from.

290
Apex Reference Guide EnvironmentContext Interface

Signature
public String getSublocation()

Return Value
Type: String
The return value can be one of the following strings:
• S1MobileCardFullview—The canvas app was called from a mobile card.
• S1MobileCardPreview—The canvas app was called from a mobile card preview. The user must click the preview to open the app.
• S1RecordHomePreview—The canvas app was called from a record detail page preview. The user must click the preview to open
the app.
• S1RecordHomeFullview—The canvas app was called from a page layout.

Usage
Use this method to obtain the display sublocation for the canvas app. Use only if the primary display location can be displayed on mobile
devices.

setParametersAsJSON(jsonString)
Sets the custom parameters for the canvas app.

Signature
public void setParametersAsJSON(String jsonString)

Parameters
jsonString
Type: String
The custom parameters that you need to set, serialized into a JSON format string.

Return Value
Type: Void

Usage
Use this method to set the current custom parameters for the canvas app. The parameters must be provided in a JSON string. You can
use the System.JSON.serialize(objectToSerialize) method to serialize a map into a JSON string.
Setting the custom parameters will overwrite the custom parameters that are set for the current request. If you need to modify the
current custom parameters, first get the current set of custom parameters by using getParametersAsJSON(), modify the retrieved
parameter set as needed, and then use this modified set in your call to setParametersAsJSON().
If the provided JSON string exceeds 32KB, a System.CanvasException will be thrown.

291
Apex Reference Guide RenderContext Interface

Example
This example gets the current custom parameters, adds a new newCustomParam parameter with a value of ‘TESTVALUE’, and sets
the current custom parameters.
Canvas.EnvironmentContext env = renderContext.getEnvironmentContext();

// Get current custom params


Map<String, Object> previousParams =
(Map<String, Object>) JSON.deserializeUntyped(env.getParametersAsJSON());

// Add a new custom param


previousParams.put('newCustomParam','TESTVALUE');

// Now replace the parameters with the current parameters plus our new custom param
env.setParametersAsJSON(JSON.serialize(previousParams));

RenderContext Interface
A wrapper interface that is used to retrieve application and environment context information.

Namespace
Canvas

Usage
Use this interface to retrieve application and environment context information for your canvas app. For this interface, you don’t need to
create an implementation. Use the default implementation that Salesforce provides.

IN THIS SECTION:
RenderContext Methods

RenderContext Methods
The following are methods for RenderContext.

IN THIS SECTION:
getApplicationContext()
Retrieves the application context information.
getEnvironmentContext()
Retrieves the environment context information.

getApplicationContext()
Retrieves the application context information.

292
Apex Reference Guide RenderContext Interface

Signature
public Canvas.ApplicationContext getApplicationContext()

Return Value
Type: Canvas.ApplicationContext

Usage
Use this method to get the application context information for your canvas app.

Example
The following example implementation of the CanvasLifecycleHandler onRender() method uses the provided RenderContext to retrieve
the application context information and then checks the namespace, version, and app URL.
public void onRender(Canvas.RenderContext renderContext){
Canvas.ApplicationContext app = renderContext.getApplicationContext();
if (!'MyNamespace'.equals(app.getNamespace())){
// This application is installed, add code as needed
...
}

// Check the application version


Double currentVersion = Double.valueOf(app.getVersion());

if (currentVersion <= 5){


// Add version specific code as needed
...
// Tell the canvas application to operate in deprecated mode
app.setCanvasUrlPath('/canvas?deprecated=true');
}
}

getEnvironmentContext()
Retrieves the environment context information.

Signature
public Canvas.EnvironmentContext getEnvironmentContext()

Return Value
Type: Canvas.EnvironmentContext

Usage
Use this method to get the environment context information for your canvas app.

293
Apex Reference Guide Test Class

Example
The following example implementation of the CanvasLifecycleHandler onRender() method uses the provided RenderContext to retrieve
the environment context information and then modifies the custom parameters.
public void onRender(Canvas.RenderContext renderContext) {
Canvas.EnvironmentContext env =
renderContext.getEnvironmentContext();

// Retrieve the custom params


Map<String, Object> previousParams = (Map<String, Object>)
JSON.deserializeUntyped(env.getParametersAsJSON());

previousParams.put('param1',1);
previousParams.put('param2',3.14159);

...

// Now, add in some opportunity record IDs


Opportunity[] o = [select id, name from opportunity];
previousParams.put('opportunities',o);

// Now, replace the parameters


env.setParametersAsJSON(JSON.serialize(previousParams));
}

Test Class
Contains methods for automated testing of your Canvas classes.

Namespace
Canvas

Usage
Use this class to test your implementation of Canvas.CanvasLifecycleHandler with mock test data. You can create a test
Canvas.RenderContext with mock application and environment context data and use this data to verify that your CanvasLifecycleHandler
is being invoked correctly.

IN THIS SECTION:
Test Constants
The Test class provides constants that are used as keys when you set mock application and environment context data.
Test Methods
The Test class provides methods for creating test contexts and invoking your CanvasLifecycleHandler with mock data.

SEE ALSO:
Canvas Developer Guide: Testing Your CanvasLifecycleHandler Implementation

294
Apex Reference Guide Test Class

Test Constants
The Test class provides constants that are used as keys when you set mock application and environment context data.
When you call Canvas.Test.mockRenderContext(applicationContextTestValues,
environmentContextTestValues), you need to provide maps of key-value pairs to represent your mock application and
environment context data. The Test class provides static constant strings that you can use as keys for various parts of the application
and environment context.

Constant Description
KEY_CANVAS_URL Represents the canvas app URL key in the ApplicationContext.

KEY_DEVELOPER_NAME Represents the canvas app developer or API name key in the ApplicationContext.

KEY_DISPLAY_LOCATION Represents the canvas app display location key in the EnvironmentContext.

KEY_LOCATION_URL Represents the canvas app location URL key in the EnvironmentContext.

KEY_NAME Represents the canvas app name key in the ApplicationContext.

KEY_NAMESPACE Represents the canvas app namespace key in the ApplicationContext.

KEY_SUB_LOCATION Represents the canvas app sublocation key in the EnvironmentContext.

KEY_VERSION Represents the canvas app version key in the ApplicationContext.

Test Methods
The Test class provides methods for creating test contexts and invoking your CanvasLifecycleHandler with mock data.
The following are methods for Test. All are static methods.

IN THIS SECTION:
mockRenderContext(applicationContextTestValues, environmentContextTestValues)
Creates and returns a test Canvas.RenderContext based on the provided application and environment context parameters.
testCanvasLifecycle(lifecycleHandler, mockRenderContext)
Calls the Canvas test framework to invoke a CanvasLifecycleHandler with the provided RenderContext.

mockRenderContext(applicationContextTestValues, environmentContextTestValues)
Creates and returns a test Canvas.RenderContext based on the provided application and environment context parameters.

Signature
public static Canvas.RenderContext mockRenderContext(Map<String,String>
applicationContextTestValues, Map<String,String> environmentContextTestValues)

Parameters
applicationContextTestValues
Type: Map<String,String>

295
Apex Reference Guide Test Class

Specifies a map of key-value pairs that provide mock application context data. Use constants that are provided by Canvas.Test as
keys. If null is provided for this parameter, the canvas framework generates some default mock application context values.
environmentContextTestValues
Type: Map<String,String>
Specifies a map of key-value pairs that provide mock environment context data. Use constants provided by Canvas.Test as keys. If
null is provided for this parameter, the canvas framework generates some default mock environment context values.

Return Value
Type: Canvas.RenderContext

Usage
Use this method to create a mock Canvas.RenderContext. Use the returned RenderContext in calls to
Canvas.Test.testCanvasLifecycle(lifecycleHandler, mockRenderContext) for testing
Canvas.CanvasLifecycleHandler implementations.

Example
The following example creates maps to represent mock application and environment context data and generates a test
Canvas.RenderContext. This test RenderContext can be used in a call to
Canvas.Test.testCanvasLifecycle(lifecycleHandler, mockRenderContext).
Map<String,String> appValues = new Map<String,String>();
appValues.put(Canvas.Test.KEY_NAMESPACE,'alternateNamespace');
appValues.put(Canvas.Test.KEY_VERSION,'3.0');

Map<String,String> envValues = new Map<String,String>();


envValues.put(Canvas.Test.KEY_DISPLAY_LOCATION,'Chatter');
envValues.put(Canvas.Test.KEY_LOCATION_URL,'https://MyDomainName.my.salesforce.com/_ui/core/chatter/ui/ChatterPage');

Canvas.RenderContext mock = Canvas.Test.mockRenderContext(appValues,envValues);

SEE ALSO:
Canvas Developer Guide: Testing Your CanvasLifecycleHandler Implementation

testCanvasLifecycle(lifecycleHandler, mockRenderContext)
Calls the Canvas test framework to invoke a CanvasLifecycleHandler with the provided RenderContext.

Signature
public static Void testCanvasLifecycle(Canvas.CanvasLifecycleHandler
lifecycleHandler,Canvas.RenderContext mockRenderContext)

Parameters
lifecycleHandler
Type: Canvas.CanvasLifecycleHandler

296
Apex Reference Guide Test Class

Specifies the CanvasLifecycleHandler implementation that you need to invoke.


mockRenderContext
Type: Canvas.RenderContext
Specifies the RenderContext information that you need to provide to the invoked CanvasLifecycleHandler. If null is provided for
this parameter, the canvas framework generates and uses a default mock RenderContext.

Return Value
Type: Void

Usage
Use this method to invoke an implementation of Canvas.CanvasLifecycleHandler.onRender(renderContext) with a mock
Canvas.RenderContext that you provide.

Example
The following example creates an Apex test class that uses maps to represent mock application and environment context data. The
mock RenderContext object is then used to invoke a CanvasLifecycleHandler object. In this example, the CanvasLifecycleHandler is
defined as MyCanvasListener, which is example implementation provided in Canvas.RenderContext.
@IsTest
global class CanvasRendercontextTest {
@IsTest
static void testRenderContext(){
// Set some application context data in a Map
Map<String,String> appValues = new Map<String,String>();
appValues.put(Canvas.Test.KEY_NAMESPACE,'alternateNamespace');
appValues.put(Canvas.Test.KEY_VERSION,'3.0');

// Set some environment context data in a MAp


Map<String,String> envValues = new Map<String,String>();
envValues.put(Canvas.Test.KEY_DISPLAY_LOCATION,'Chatter');

envValues.put(Canvas.Test.KEY_LOCATION_URL,'https://MyDomainName.my.salesforce.com/_ui/core/chatter/ui/ChatterPage');

// Create a mock RenderContext using the test application and environment context
data Maps
Canvas.RenderContext mock = Canvas.Test.mockRenderContext(appValues,envValues);

// Set some custom params on the mock RenderContext

mock.getEnvironmentContext().setParametersAsJSON('{\"param1\":1,\"boolParam\":true,\"stringParam\":\"test
string\"}');

// Create a CanvasLifecycleHandler
MyCanvasListener handler = new MyCanvasListener();

// Use the mock RenderContext to invoke the CanvasLifecycleHandler


Canvas.Test.testCanvasLifecycle(handler,mock);

297
Apex Reference Guide Canvas Exceptions

}
}

SEE ALSO:
Canvas Developer Guide: Testing Your CanvasLifecycleHandler Implementation

Canvas Exceptions
The Canvas namespace contains exception classes.
All exception classes support built-in methods for returning the error message and exception type. See Exception Class and Built-In
Exceptions.
The Canvas namespace contains this exception:

Exception Description
Canvas.CanvasRenderException Use this class in your implementation of
Canvas.CanvasLifecycleHandler.onRender(renderContext). To show
an error to the user in your onRender() implementation, throw a
Canvas.CanvasRenderException, and the canvas framework will
render the error message to the user. This exception will be managed only
within the onRender() method.

Example
The following example implementation of onRender() catches a CanvasException that was thrown because a canvas URL was set
with a string that exceeded the maximum length. A CanvasRenderException is created and thrown to display the error to the user.
public class MyCanvasListener
implements Canvas.CanvasLifecycleHandler {

public void onRender(Canvas.RenderContext renderContext) {


Canvas.ApplicationContext app = renderContext.getApplicationContext();

// Code to generate a URL string that is too long

// ...

// Try to set the canvas app URL using the invalid URL string
try {
app.setCanvasUrlPath(aUrlPathThatIsTooLong);
} catch (CanvasException e) {
// Display error to user by throwing a new CanvasRenderException
throw new Canvas.CanvasRenderException(e.getMessage());
}
}
}

See the Canvas Developer Guide for additional examples that use CanvasRenderException.

298
Apex Reference Guide ChatterAnswers Namespace

ChatterAnswers Namespace
The ChatterAnswers namespace provides an interface for creating Account records.
The following is the interface in the ChatterAnswers namespace.

IN THIS SECTION:
AccountCreator Interface
Creates Account records that will be associated with Chatter Answers users.

AccountCreator Interface
Creates Account records that will be associated with Chatter Answers users.

Namespace
ChatterAnswers

Usage
The ChatterAnswers.AccountCreator is specified in the registrationClassName attribute of a
chatteranswers:registration Visualforce component. This interface is called by Chatter Answers and allows for custom
creation of Account records used for portal users.
To implement the ChatterAnswers.AccountCreator interface, you must first declare a class with the implements
keyword as follows:
public class ChatterAnswersRegistration implements ChatterAnswers.AccountCreator {

Next, your class must provide an implementation for the following method:
public String createAccount(String firstname, String lastname, Id siteAdminId) {
// Your code here
}

The implemented method must be declared as global or public.

IN THIS SECTION:
AccountCreator Methods
AccountCreator Example Implementation

AccountCreator Methods
The following are methods for AccountCreator.

IN THIS SECTION:
createAccount(firstName, lastName, siteAdminId)
Accepts basic user information and creates an Account record. The implementation of this method returns the account ID.

299
Apex Reference Guide AccountCreator Interface

createAccount(firstName, lastName, siteAdminId)


Accepts basic user information and creates an Account record. The implementation of this method returns the account ID.

Signature
public String createAccount(String firstName, String lastName, Id siteAdminId)

Parameters
firstName
Type: String
The first name of the user who is registering.
lastName
Type: String
The last name of the user who is registering.
siteAdminId
Type: ID
The user ID of the Site administrator, used for notification if any exceptions occur.

Return Value
Type: String

AccountCreator Example Implementation


This is an example implementation of the ChatterAnswers.AccountCreator interface. The createAccount method
implementation accepts user information and creates an Account record. The method returns a String value for the Account ID.
public class ChatterAnswersRegistration implements ChatterAnswers.AccountCreator {
public String createAccount(String firstname, String lastname, Id siteAdminId) {
Account a = new Account(name = firstname + ' ' + lastname, ownerId = siteAdminId);

insert a;
return a.Id;
}
}

This example tests the code above.


@isTest
private class ChatterAnswersCreateAccountTest {
static testMethod void validateAccountCreation() {
User[] user = [SELECT Id, Firstname, Lastname from User WHERE UserType='Standard'];

if (user.size() == 0) { return; }
String firstName = user[0].FirstName;
String lastName = user[0].LastName;
String userId = user[0].Id;
String accountId = new ChatterAnswersRegistration().createAccount(firstName,
lastName, userId);

300
Apex Reference Guide CommerceBuyGrp Namespace

Account acct = [SELECT name, ownerId from Account where Id =: accountId];


System.assertEquals(firstName + ' ' + lastName, acct.name);
System.assertEquals(userId, acct.ownerId);
}
}

CommerceBuyGrp Namespace
The CommerceBuyGrp namespace provides classes and methods for retrieving information about the buyer groups associated with
a user.
The following are the classes in the CommerceBuyGrp namespace.

IN THIS SECTION:
BuyerGroupEvaluationService Class
The BuyerGroupEvaluationService class allows you define and execute custom business logic for dynamically assigning
users to buyer groups. Unlike out-of-the-box configurations limited to account, market, or data segment-based buyer groups, this
service supports extensibility and empowers you to implement tailored buyer group evaluation strategies. It supports both guest
and logged-in user scenarios, enabling highly customizable and context-specific buyer group determination.
BuyerGroupRequest Class
Contains methods to retrieve account and store details used to identify the buyer groups associated with a user.
BuyerGroupResponse Class
Contains constructors and methods to retrieve the buyer groups associated with a user.

SEE ALSO:
Salesforce B2B Commerce and D2C Commerce: Assign Users to Buyer Groups
B2B Commerce and D2C Commerce Developer Guide: Available Domain Extensions

BuyerGroupEvaluationService Class
The BuyerGroupEvaluationService class allows you define and execute custom business logic for dynamically assigning
users to buyer groups. Unlike out-of-the-box configurations limited to account, market, or data segment-based buyer groups, this service
supports extensibility and empowers you to implement tailored buyer group evaluation strategies. It supports both guest and logged-in
user scenarios, enabling highly customizable and context-specific buyer group determination.

Namespace
CommerceBuyGrp

Consideration
When implementing the BuyerGroupEvaluationService, remember these key points:
• The number of buyer groups that can be assigned to a user is determined by the limit set in your Salesforce org. See Shopper Buyer
Groups and Accounts Data Limits Groups.

301
Apex Reference Guide BuyerGroupEvaluationService Class

• Supported for B2B stores and D2C stores with custom checkout enabled. It isn't available for stores using managed checkout. See
Configure Custom Checkout for a B2B or D2C Store.
• Buyer group assignments may not take effect immediately if caching is enabled. To make sure the buyer group extensibility service
functions properly and to avoid caching-related issues, disable both the Salesforce Content Delivery Network (CDN) and Salesforce
Edge Network.
Test these changes in your sandbox org before applying them in production. Go to My Domain Settings and disable both options
for enhanced domains.
See Considerations for the Salesforce CDN and Considerations for Salesforce Edge Network.

Usage
Use the BuyerGroupEvaluationService to implement custom logic for assigning users to buyer groups. By integrating your
logic with this service, you can evaluate and assign buyer groups in real time based on criteria specific to your organization.
• Define Custom Logic—Create your own business rules to evaluate and assign users to appropriate Buyer Groups.
• Integration with the Service—Integrate your custom logic into the BuyerGroupEvaluationService to dynamically
determine buyer group membership at runtime.
• Test and Validate—Test your implementation to ensure it behaves as expected and doesn’t introduce errors or inconsistencies in
group assignments.

Example
For an example implementation of the CommerceBuyGrp.BuyerGroupEvaluationService class, see Commerce Extensibility.

IN THIS SECTION:
BuyerGroupEvaluationService Methods

BuyerGroupEvaluationService Methods
The following are methods for BuyerGroupEvaluationService.

IN THIS SECTION:
getBuyerGroupIds(request)
Retrieves a list of evaluated buyer group IDs assigned to a user based on custom or predefined business logic.

getBuyerGroupIds(request)
Retrieves a list of evaluated buyer group IDs assigned to a user based on custom or predefined business logic.

Signature
public CommerceBuyGrp.BuyerGroupResponse
getBuyerGroupIds(CommerceBuyGrp.BuyerGroupRequest request)

302
Apex Reference Guide BuyerGroupRequest Class

Parameters
request
Type: CommerceBuyGrp.BuyerGroupRequest

Return Value
Type: CommerceBuyGrp.BuyerGroupResponseCommerceBuyGrp.BuyerGroupResponse

BuyerGroupRequest Class
Contains methods to retrieve account and store details used to identify the buyer groups associated with a user.

Namespace
CommerceBuyGrp

IN THIS SECTION:
BuyerGroupRequest Methods

BuyerGroupRequest Methods
The following are methods for BuyerGroupRequest.

IN THIS SECTION:
getAccountId()
Returns the account ID of a user.
getStoreId()
Returns the ID of the web store.
getRequestContextParameters()
Returns a map of user context parameters evaluated at runtime, includingisGuestUser, locale, and
guest_uuid_essential_{siteId}.

getAccountId()
Returns the account ID of a user.

Signature
public String getAccountId()

Return Value
Type: String

303
Apex Reference Guide BuyerGroupResponse Class

getStoreId()
Returns the ID of the web store.

Signature
public String getStoreId()

Return Value
Type: String

getRequestContextParameters()
Returns a map of user context parameters evaluated at runtime, includingisGuestUser, locale, and
guest_uuid_essential_{siteId}.

Signature
public Map<String,Object> getRequestContextParameters()

Return Value
Type: Map<String,Object>
Here's a list of context parameters to include in the request:

Name Type Description


guest_uuid_ String Specifies the multiple key-value pair representing guest UUID
essential_{siteId} cookie for each store. Generated by the client as a unique device
identifier where siteId is the 15-digit ID for the site associated
with the webstore.

isGuestUser Boolean Indicates whether the user in context is a guest user (true) or an
authenticated user (false).

locale String Specifies the user's locale.

BuyerGroupResponse Class
Contains constructors and methods to retrieve the buyer groups associated with a user.

Namespace
CommerceBuyGrp

IN THIS SECTION:
BuyerGroupResponse Constructors
BuyerGroupResponse Methods

304
Apex Reference Guide BuyerGroupResponse Class

BuyerGroupResponse Constructors
The following are constructors for BuyerGroupResponse.

IN THIS SECTION:
BuyerGroupResponse(buyerGroupIds)
Creates a new instance of the CommerceBuyGrp.BuyerGroupResponse class using the specified buyerGroupIds
payload parameter.
BuyerGroupResponse()
Creates a new instance of the CommerceBuyGrp.BuyerGroupResponse class.

BuyerGroupResponse(buyerGroupIds)
Creates a new instance of the CommerceBuyGrp.BuyerGroupResponse class using the specified buyerGroupIds payload
parameter.

Signature
public BuyerGroupResponse(Set<String> buyerGroupIds)

Parameters
buyerGroupIds
Type: Set<String>
List of buyer group IDs for a user.

BuyerGroupResponse()
Creates a new instance of the CommerceBuyGrp.BuyerGroupResponse class.

Signature
public BuyerGroupResponse()

BuyerGroupResponse Methods
The following are methods for BuyerGroupResponse.

IN THIS SECTION:
getBuyerGroupIds()
Retrieves a list of evaluated buyer group IDs assigned to a user.
setBuyerGroupIds(buyerGroupIds)
Sets a list of evaluated buyer group IDs assigned to a user.
setError(errorMessage, localizedErrorMessage)
Sets the error message to be returned when the evaluation of buyer group IDs fails.

305
Apex Reference Guide BuyerGroupResponse Class

getBuyerGroupIds()
Retrieves a list of evaluated buyer group IDs assigned to a user.

Signature
public Set<String> getBuyerGroupIds()

Return Value
Type: Set<String>

setBuyerGroupIds(buyerGroupIds)
Sets a list of evaluated buyer group IDs assigned to a user.

Signature
public void setBuyerGroupIds(Set<String> buyerGroupIds)

Parameters
buyerGroupIds
Type: Set<String>

Return Value
Type: void

setError(errorMessage, localizedErrorMessage)
Sets the error message to be returned when the evaluation of buyer group IDs fails.

Signature
public void setError(String errorMessage, String localizedErrorMessage)

Parameters
errorMessage
Type: String
The message stating the reason for the error.
localizedErrorMessage
Type: String
The translated error message.

Return Value
Type: void

306
Apex Reference Guide CommerceExtension Namespace

CommerceExtension Namespace
Use the CommerceExtension namespace to define resolution strategies for registered Commerce extensions.
The following are the classes in the CommerceExtension namespace.

IN THIS SECTION:
ExtensionInfo Class
Contains static methods to expose extension-related context information.
Resolution Class
Resolution of a resolution strategy, which conditionally invokes default domain logic, logic provided by an extension provider, or no
logic.
ResolutionException Class
Exception indicating a problem with the execution of a resolution strategy.
ResolutionStates Enum
Potential resolution states for a resolution strategy.
ResolutionStrategy Interface
Interface for a resolution strategy.

ExtensionInfo Class
Contains static methods to expose extension-related context information.

Namespace
CommerceExtension on page 307

Example

// The Sample Extension Provider registered with developer name as


// 'tax_extension_provider_for_us' will be selected for execution for en_US locale

if(CommerceExtension.ExtensionInfo.getLocaleString() == 'en_US') {
return new CommerceExtension.Resolution('tax_extension_provider_for_us');
}
// The Sample Extension Provider registered with developer name as
// 'tax_extension_provider_for_canada' will be selected for execution for en_CA
locale
if(CommerceExtension.ExtensionInfo.getLocaleString() == 'en_CA') {
return new CommerceExtension.Resolution('tax_extension_provider_for_canada');

}
// The default Salesforce Internal Tax Api will return an empty response for German
locale
if(CommerceExtension.ExtensionInfo.getLocaleString() == 'de') {
return new CommerceExtension.Resolution(CommerceExtension.ResolutionStates.OFF);

307
Apex Reference Guide ExtensionInfo Class

IN THIS SECTION:
ExtensionInfo Methods

ExtensionInfo Methods
The following are methods for ExtensionInfo.

IN THIS SECTION:
getClientApiVersion()
Returns the version number of the Client API for the extension context.
getCustomParameterField(fieldName)
Returns a custom parameter field value, if available, for the extension context.
getLocaleString()
Returns the locale for the extension context.
isCustomParametersAvailable()
Indicates whether custom parameters are available for the extension context.

getClientApiVersion()
Returns the version number of the Client API for the extension context.

Signature
public static Double getClientApiVersion()

Return Value
Type: Double
Version number of the Client API for the extension context.

getCustomParameterField(fieldName)
Returns a custom parameter field value, if available, for the extension context.

Signature
public static String getCustomParameterField(String fieldName)

Parameters
fieldName
Type: String
Custom parameter field name.

308
Apex Reference Guide Resolution Class

Return Value
Type: String
Custom parameter field value for the extension context.

getLocaleString()
Returns the locale for the extension context.

Signature
public static String getLocaleString()

Return Value
Type: String
Locale for the extension context.

isCustomParametersAvailable()
Indicates whether custom parameters are available for the extension context.

Signature
public static Boolean isCustomParametersAvailable()

Return Value
Type: Boolean
Value indicating if custom parameters are available in the extension context (true) or not (false).

Resolution Class
Resolution of a resolution strategy, which conditionally invokes default domain logic, logic provided by an extension provider, or no
logic.

Namespace
CommerceExtension on page 307

Example
public class TaxServiceExtensionResolverSample extends commercestoretax.TaxService implements
CommerceExtension.ResolutionStrategy {
public CommerceExtension.Resolution resolve() {
// The Sample Extension Provider registered with developer name as
'tax_extension_provider_for_us' will be selected for execution for en_US locale
if(CommerceExtension.ExtensionInfo.getLocaleString() == 'en_US') {
return new CommerceExtension.Resolution('tax_extension_provider_for_us');

309
Apex Reference Guide Resolution Class

}
// The Sample Extension Provider registered with developer name as
'tax_extension_provider_for_canada' will be selected for execution for en_CA locale
if(CommerceExtension.ExtensionInfo.getLocaleString() == 'en_CA') {
return new CommerceExtension.Resolution('tax_extension_provider_for_canada');

}
// The default Salesforce Internal Tax Api will return an empty response for German
locale
if(CommerceExtension.ExtensionInfo.getLocaleString() == 'de') {
return new CommerceExtension.Resolution(CommerceExtension.ResolutionStates.OFF);

}
// The default Salesforce Internal Tax Api will be selected for execution for all
other locales than US, Canada and Germany
return new CommerceExtension.Resolution();
}
}

IN THIS SECTION:
Resolution Constructors
Resolution Methods

Resolution Constructors
The following are constructors for Resolution.

IN THIS SECTION:
Resolution(resolutionState)
Constructor that takes a CommerceExtension.ResolutionStates object as an argument.
Resolution(providerName)
Constructor that takes the name of an extension provider as an argument.
Resolution()
Default constructor for the Resolution class.

Resolution(resolutionState)
Constructor that takes a CommerceExtension.ResolutionStates object as an argument.

Signature
public Resolution(CommerceExtension.ResolutionStates resolutionState)

Parameters
resolutionState
Type: CommerceExtension.ResolutionStates on page 314

310
Apex Reference Guide Resolution Class

Resolution state.

Resolution(providerName)
Constructor that takes the name of an extension provider as an argument.

Signature
public Resolution(String providerName)

Parameters
providerName
Type: String
Name of the extension provider.

Resolution()
Default constructor for the Resolution class.

Signature
public Resolution()

Resolution Methods
The following are methods for Resolution.

IN THIS SECTION:
getProviderName()
Returns the name of an extension provider.
getResolutionState()
Returns the resolution state of the resolution.

getProviderName()
Returns the name of an extension provider.

Signature
public String getProviderName()

Return Value
Type: String
Name of an extension provider.

311
Apex Reference Guide ResolutionException Class

getResolutionState()
Returns the resolution state of the resolution.

Signature
public CommerceExtension.ResolutionStates getResolutionState()

Return Value
Type: CommerceExtension.ResolutionStates on page 314
Resolution state of the resolution.

ResolutionException Class
Exception indicating a problem with the execution of a resolution strategy.

Namespace
CommerceExtension on page 307

IN THIS SECTION:
ResolutionException Constructors
ResolutionException Methods

ResolutionException Constructors
The following are constructors for ResolutionException.

IN THIS SECTION:
ResolutionException(errorMessage, exception)
Constructor that takes two arguments: an error message and an exception.
ResolutionException(exception)
Constructor that takes an exception as an argument,
ResolutionException(errorMessage)
Constructor that takes an error message as an argument.
ResolutionException()
Default constructor for the ResolutionException class.

ResolutionException(errorMessage, exception)
Constructor that takes two arguments: an error message and an exception.

Signature
public ResolutionException(String errorMessage, Exception exception)

312
Apex Reference Guide ResolutionException Class

Parameters
errorMessage
Type: String
Error message.
exception
Type: Exception
Exception.

ResolutionException(exception)
Constructor that takes an exception as an argument,

Signature
public ResolutionException(Exception exception)

Parameters
exception
Type: Exception
Exception.

ResolutionException(errorMessage)
Constructor that takes an error message as an argument.

Signature
public ResolutionException(String errorMessage)

Parameters
errorMessage
Type: String
Error message.

ResolutionException()
Default constructor for the ResolutionException class.

Signature
public ResolutionException()

ResolutionException Methods
The following are methods for the ResolutionException class.

313
Apex Reference Guide ResolutionStates Enum

IN THIS SECTION:
getTypeName()
Returns the type of the exception.

getTypeName()
Returns the type of the exception.

Signature
public String getTypeName()

Return Value
Type: String
The type of the Exception.

ResolutionStates Enum
Potential resolution states for a resolution strategy.

Enum Values
The following are the values of the CommerceExtension.ResolutionStates enum.

Value Description
EXECUTE_DEFAULT Run the default domain logic (without running extension provider logic).

EXECUTE_REGISTERED Run the extension provider logic provided by the Apex class registered for the
endpoint provider name.

OFF Don’t run any domain logic (default logic or logic provided by an extension provider).

ResolutionStrategy Interface
Interface for a resolution strategy.

Namespace
CommerceExtension on page 307

Usage
When you implement this interface, you can register your apex class just like an extension provider class. Your class can then conditionally
decide how to handle each extension invocation. You can delegate to a specific extension provider, you can execute default domain
logic, or you can execute no logic at all.

314
Apex Reference Guide ResolutionStrategy Interface

IN THIS SECTION:
ResolutionStrategy Methods
ResolutionStrategy Example Implementation

ResolutionStrategy Methods
The following are methods for ResolutionStrategy.

IN THIS SECTION:
resolve()
Returns a resolution object, which indicates how the resolution strategy was resolved. The resolution indicates whether default logic,
extension provider logic, or no logic is executed.

resolve()
Returns a resolution object, which indicates how the resolution strategy was resolved. The resolution indicates whether default logic,
extension provider logic, or no logic is executed.

Signature
public CommerceExtension.Resolution resolve()

Return Value
Type: CommerceExtension.Resolution on page 309
Resolution object that indicates how the resolution strategy was resolved.

ResolutionStrategy Example Implementation


This is an example implementation of the CommerceExtension.ResolutionStrategy interface.
// This sample is for the situation when different tax behaviors need to be
// implemented for different locales.
//
// These tax behaviors can be -
// 1. ResolutionState - EXECUTE_DEFAULT (the default Salesforce Internal Tax Api).
// 2. ResolutionState - EXECUTE_REGISTERED (extended or overridden implementations
// via the extension point from the default Salesforce Internal Tax Api)
// 3. ResolutionState - OFF (In this case, the default Salesforce Internal Tax Api
// will return an empty response).
//
// An Extension Provider is a custom apex class which extends or overrides the
// default Salesforce Internal Tax Api.
//
// An Extension Resolver is a custom apex class which selects different resolution
// states (EXECUTE_DEFAULT, EXECUTE_REGISTERED and OFF) for different locales
// to execute respective implementations (Extension Providers or the Default
// Salesforce Internal Tax Api).

315
Apex Reference Guide CommerceOrders Namespace

// Your custom apex extension providers and the resolver must be registered with
// the tax extension point and then the resolver must be registered and mapped to
// the web store via appropriate setup.
//
// You can have as many Extension Providers registered as per your use case and
// select them in your resolver for different locales.
//
// Please follow the corresponding salesforce documentation on how to use locales.
// For more information related to that, please see the corresponding documentation.

// This must implement the commercestoretax.TaxService class in order to be


// processed by the tax service flow. It must also implement the
// CommerceExtension.ResolutionStrategy in order to work as a extension resolver
// and get the different locales and resolutions.
//
public class TaxServiceExtensionResolverSample
extends commercestoretax.TaxService
implements CommerceExtension.ResolutionStrategy {

public CommerceExtension.Resolution resolve() {


// The Sample Extension Provider registered with developer name as
// 'tax_extension_provider_for_us' will be selected for execution for en_US locale

if (CommerceExtension.ExtensionInfo.getLocaleString() == 'en_US') {
return new CommerceExtension.Resolution('tax_extension_provider_for_us');
}
// The Sample Extension Provider registered with developer name as
// 'tax_extension_provider_for_canada' will be selected for execution for en_CA
locale
if (CommerceExtension.ExtensionInfo.getLocaleString() == 'en_CA') {
return new CommerceExtension.Resolution('tax_extension_provider_for_canada');

}
// The default Salesforce Internal Tax Api will return an empty response for German
locale
if (CommerceExtension.ExtensionInfo.getLocaleString() == 'de') {
return new CommerceExtension.Resolution(
CommerceExtension.ResolutionStates.OFF
);
}
// The default Salesforce Internal Tax Api will be selected for execution for
// all other locales than US, Canada and Germany
return new CommerceExtension.Resolution();
}
}

CommerceOrders Namespace
The CommerceOrders namespace provides classes and methods to place orders with integrated pricing, configuration, and validation.
See CommerceOrders namespace for more information about the available classes and methods.

316
Apex Reference Guide CommercePayments Namespace

CommercePayments Namespace
Use the CommercePayments namespace to provide a safe and customizable platform for managing customer payments and
refunds.
To review CommercePayments use cases and walkthroughs, go to Use Cases for the CommercePayments Namespace.
The following are the classes in the CommercePayments namespace.

IN THIS SECTION:
AbstractResponse Class
Contains the normalized response fields from payment gateways that are common to all the other gateway responses.
AbstractTransactionResponse Class
Abstract class for storing normalized information sent from payment gateways about a payment transaction. Holds the common
response fields sent from payment gateways for authorization, sale, capture, and refund transactions.
AddressRequest Class
Contains address request data that is sent to a gateway adapter during a service call.
AlternativePaymentMethodRequest Class
The class contains information about the alternative payment method that are required for a gateway to process the request.
AlternativePaymentMethodResponse Class
The class contains the response details of the alternative payment method.
AuditParamsRequest
AuditParamsRequest is used for audit parameters in a transaction request. This is an abstract request class that is extended
by the BaseRequest class.
AuthApiPaymentMethodRequest Class
Sends information about a payment method to a gateway adapter during an authorization service call.
AuthorizationRequest Class
Sends information about an authorization request to a gateway adapter during a service call. This class extends the BaseRequest
class and inherits all its methods.
AuthorizationResponse Class
Response sent by the payment gateway adapter for an authorization service.
AuthorizationReversalRequest Class
Sends information about an authorization reversal request to a gateway adapter during a service call.
AuthorizationReversalResponse Class
Response sent by the payment gateway following a payment authorization reversal service.
BaseApiPaymentMethodRequest Class
Abstract class used to send information about a payment method to a gateway adapter during a service call.
BaseNotification Class
Abstract class for storing notification information sent from payment gateways.
BasePaymentMethodRequest Class
Abstract class for storing information about payment methods.
BaseRequest Class
BaseRequest is extended by all the request classes.

317
Apex Reference Guide CommercePayments Namespace

CaptureNotification Class
When a payment gateway sends a notification for a capture transaction, the payment gateway adapter creates the
CaptureNotification object to store information about the notification.
CaptureRequest Class
Represents a capture request. This class extends the BaseRequest class and inherits all its methods.
CaptureResponse Class
The payment gateway adapter sends this response for the capture request type. This class extends AbstractResponse and
inherits its methods.
CardCategory Enum
Defines whether the payment method represents a credit card or a debit card.
CardPaymentMethodRequest Class
Sends data related to a card payment method to a gateway adapter during a service call.
CardPaymentMethodResponse Class
This class contains details about the card payment method.
CardType Enum
Specifies the credit card issuer.
CustomMetadataTypeInfo Class
Access information about custom metadata. The PaymentGatewayAdapter can send CustomMetadataTypeInfo to
transaction requests through the response object’s SalesforceResultCodeInfo.
GatewayErrorResponse Class
Use to respond with an error indication following errors from the PaymentGateway adapter, such as request-forbidden responses,
custom validation errors, or expired API tokens.
GatewayNotificationResponse Class
When the payment gateway sends a notification to the payments platform, the platform responds with a
GatewayNotificationResponse indicating whether the platform succeeded or failed at receiving the notification.
GatewayResponse Interface
Generic payment gateway response interface. This class extends the CaptureResponse on page 380,
AbstractTransactionResponse on page 323, and AbstractResponse on page 320 classes and inherits all their
properties. It has no unique methods or parameters.
NotificationClient Class
Communicates with the payment platform regarding the gateway’s notification.
NotificationSaveResult Class
Contains the result of the payment platform’s attempt to record data from the gateway’s notification.
NotificationStatus Enum
Shows whether the payments platform successfully received the notification from the gateway.
PaymentGatewayAdapter Interface
PaymentGatewayAdapters can implement this interface in order to process requests.
PaymentGatewayAsyncAdapter Interface
Implement the interface to allow customers to process payments asynchronously.
PaymentGatewayContext Class
Wraps the information related to a payment request.

318
Apex Reference Guide CommercePayments Namespace

PaymentGatewayNotificationContext Class
Wraps the information related to a gateway notification.
PaymentGatewayNotificationRequest Class
Contains the notification request data from the gateway.
PaymentMethodDetailsResponse Class
This class contains the details about the payment method.
PaymentMethodTokenizationRequest Class
Stores data about a request to tokenize a card payment method. The tokenization process occurs in the payment gateway. This
process replaces sensitive customer data, such as a card number or CVV, with unique identification symbols. The symbols are used
while the data is handled by Salesforce, the payment gateway, and the customer bank, allowing Salesforce to store the token without
storing sensitive customer data.
PaymentMethodTokenizationResponse Class
Gateway response sent by payment gateway adapters for the payment method tokenization request. The response includes the
payment method’s token ID value.
PaymentsHttp Class
Makes an HTTP request to start the interaction with the payment gateway.
PostAuthApiPaymentMethodRequest Class
Sends information about a payment method to a gateway adapter during a postauthorization service call.
PostAuthorizationRequest Class
Sends information about a postauthorization request to a gateway adapter during a service call.
PostAuthorizationResponse Class
Response sent by the payment gateway adapter for a postauthorization service.
ReferencedRefundNotification Class
When a payment gateway sends a notification for a refund transaction, the payment gateway adapter creates the
ReferencedRefundNotification object to store information about notification.
ReferencedRefundRequest
Access information about the referenced refund requests. Extends the RefundRequest class.
ReferencedRefundResponse Class
The payment gateway adapter sends this response for the ReferencedRefund request type.
RefundRequest Class
Sends data related to a refund to the payment gateway adapter.
RequestType Enum
Defines the type of payment transaction request made to the payment gateway.
SaleApiPaymentMethodRequest Class
Sends data related to a card payment method to a gateway adapter during a sale service call.
SaleRequest Class
Stores information about a sales request.
SaleResponse Class
Response sent by payment gateway adapters for a sales service.
SalesforceResultCode Enum
Defines the gateway call status values in Salesforce based on the call status values that the payment gateway returned.

319
Apex Reference Guide AbstractResponse Class

SalesforceResultCodeInfo
Stores Salesforce result code information from payment gateway adapters.

AbstractResponse Class
Contains the normalized response fields from payment gateways that are common to all the other gateway responses.

Namespace
CommercePayments

Usage
You must specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes
no arguments. For example:
CommercePayments.AbstractResponse abr = new CommercePayments.AbstractResponse();
This class can’t be instantiated on its own. This class implements the GatewayResponse class. Other GatewayResponse classes extend
this class to inherit common properties.

IN THIS SECTION:
AbstractResponse Methods

AbstractResponse Methods
The following are methods for AbstractResponse.

IN THIS SECTION:
setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.
setGatewayDate(gatewayDate)
Sets the date that the transaction occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the payment request. Maximum length of 255 characters.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code may be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.

320
Apex Reference Guide AbstractResponse Class

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String
Code sent by gateways that use an address verification system.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the transaction occurred. Some gateways don’t send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime
Date and time of the gateway communication.

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the payment request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String
Information on error messages sent from the gateway.

Return Value
Type: void

321
Apex Reference Guide AbstractResponse Class

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code may be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be used to map a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the gateway’s result code. Use this field to learn more about why the gateway returned a certain result code.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce uses
the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: commercepayments.SalesforceResultCodeInfo on page 465

322
Apex Reference Guide AbstractTransactionResponse Class

Description of the Salesforce result code value.

Return Value
Type: void

AbstractTransactionResponse Class
Abstract class for storing normalized information sent from payment gateways about a payment transaction. Holds the common response
fields sent from payment gateways for authorization, sale, capture, and refund transactions.

Namespace
CommercePayments

Usage
Specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes no arguments.
For example:
CommercePayments.AbstractTransactionResponse atr = new
CommercePayments.AbstractTransactionResponse();

IN THIS SECTION:
AbstractTransactionResponse Methods

AbstractTransactionResponse Methods
The following are methods for AbstractTransactionResponse.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount. Must be a non-negative value.
setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code that the gateway returned. Maximum length of 64 characters.
setGatewayDate(gatewayDate)
Sets the date that the notification occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the notification request. Maximum length of 255 characters.
setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. You can map the result code to a Salesforce-specific result code. Maximum length of 64 characters.

323
Apex Reference Guide AbstractTransactionResponse Class

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information.

setAmount(amount)
Sets the transaction amount. Must be a non-negative value.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount of the transaction.

Return Value
Type: void

setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code that the gateway returned. Maximum length of 64 characters.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String
Used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment
gateway.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the notification occurred. Some gateways don’t send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

324
Apex Reference Guide AbstractTransactionResponse Class

Parameters
gatewayDate
Type: Datetime
The date that the transaction occurred.

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the notification request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String
The message that the gateway returned with the transaction request. Contains additional information about the transaction.

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String
Provides information about the gateway communication.

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.

325
Apex Reference Guide AbstractTransactionResponse Class

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique transaction ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. You can map the result code to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be mapped to a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Provides additional information about the result code and why the gateway returned the specific code. Descriptions vary between
different gateways.

Return Value
Type: void

326
Apex Reference Guide AddressRequest Class

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: commercepayments.SalesforceResultCodeInfo on page 465
Payment gateways have many response codes for payment calls. Salesforce uses the result code information to map payment
gateway codes to a predefined set of standard Salesforce result codes.

Return Value
Type: void

AddressRequest Class
Contains address request data that is sent to a gateway adapter during a service call.

Namespace
CommercePayments

Usage
Contains information about the payment method’s address. Use this information in authorization, sale, and tokenization requests. The
payment gateway adapter uses information in an AddressRequest object to construct a JSON request to send to the payment gateway.
The constructor of this class takes no arguments. For example:
CommercePayments.AddressRequest adr = new CommercePayments.AddressRequest();

IN THIS SECTION:
AddressRequest Constructors
AddressRequest Properties
AddressRequest Methods

AddressRequest Constructors
The following are constructors for AddressRequest.

327
Apex Reference Guide AddressRequest Class

IN THIS SECTION:
AddressRequest(street, city, state, country, postalCode)
Constructs a sample address. This constructor is intended for test usage and throws an exception if used outside of the Apex test
context.

AddressRequest(street, city, state, country, postalCode)


Constructs a sample address. This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Signature
global AddressRequest(String street, String city, String state, String country, String
postalCode)

Parameters
street
Type: String
Street for the payment method's address.
city
Type: String
City for the payment method's address.
state
Type: String
State for the payment method's address.
country
Type: String
Country for the payment method's address.
postalCode
Type: String
Postal code for the payment method's address.

AddressRequest Properties
The following are properties for AddressRequest.

IN THIS SECTION:
city
City of the payment method address.
companyName
Company name of the payment method address.
country
Country for the payment method address.

328
Apex Reference Guide AddressRequest Class

postalCode
Postal code for the payment method address.
state
State for the payment method address.
street
Street for the payment method address.

city
City of the payment method address.

Signature
global String city {get; set;}

Property Value
Type: String

companyName
Company name of the payment method address.

Signature
global String companyName {get; set;}

Property Value
Type: String

country
Country for the payment method address.

Signature
global String country {get; set;}

Property Value
Type: String

postalCode
Postal code for the payment method address.

Signature
global String postalCode {get; set;}

329
Apex Reference Guide AddressRequest Class

Property Value
Type: String

state
State for the payment method address.

Signature
global String state {get; set;}

Property Value
Type: String

street
Street for the payment method address.

Signature
global String street {get; set;}

Property Value
Type: String

AddressRequest Methods
The following are methods for AddressRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type AddressRequest by determining the equality of external objects in a list. This method
is dynamic and is based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type AddressRequest.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type AddressRequest by determining the equality of external objects in a list. This method is
dynamic and is based on the equals method in Java.

Signature
global Boolean equals(Object obj)

330
Apex Reference Guide AlternativePaymentMethodRequest Class

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type AddressRequest.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

AlternativePaymentMethodRequest Class
The class contains information about the alternative payment method that are required for a gateway to process the request.

Namespace
CommercePayments

Example

commercepayments.PostAuthApiPaymentMethodRequest apiPaymentMethod
=(commercepayments.PostAuthApiPaymentMethodRequest) postAuthRequest.paymentMethod;
commercepayments.AlternativePaymentMethodRequest alternativePaymentMethod=
(commercepayments.AlternativePaymentMethodRequest) apiPaymentMethod.alternativePaymentMethod;
String gatewayToken = (String)alternativePaymentMethod.gatewayToken;

331
Apex Reference Guide AlternativePaymentMethodRequest Class

String gatewayTokenDetails = (String)alternativePaymentMethod.gatewayTokenDetails;


String name = (String)alternativePaymentMethod.name;
String accountId = (String)alternativePaymentMethod.accountId;
String email = (String)alternativePaymentMethod.email;

IN THIS SECTION:
AlternativePaymentMethodRequest Constructors
AlternativePaymentMethodRequest Properties
AlternativePaymentMethodRequest Methods

AlternativePaymentMethodRequest Constructors
The following are constructors for AlternativePaymentMethodRequest.

IN THIS SECTION:
AlternativePaymentMethodRequest(gatewayToken)
Creates a new instance of the CommercePayments.AlternativePaymentMethodRequest class.

AlternativePaymentMethodRequest(gatewayToken)
Creates a new instance of the CommercePayments.AlternativePaymentMethodRequest class.

Signature
public AlternativePaymentMethodRequest(String gatewayToken)

Parameters
gatewayToken
Type: String
A unique, alphanumeric ID, called a token, that a payment gateway generates when it first processes a payment. The token replaces
the actual payment data so that the data is kept secure. This token is stored as encrypted text, and can be used for recurring payments.

AlternativePaymentMethodRequest Properties
The following are properties for AlternativePaymentMethodRequest.

IN THIS SECTION:
accountId
Salesforce account ID to which this payment method is linked.
email
Email address of the card holder.
gatewayToken
A unique, alphanumeric ID, that a payment gateway generates when it first processes a payment.

332
Apex Reference Guide AlternativePaymentMethodRequest Class

gatewayTokenDetails
Information about the gateway token.
name
Name that you assign to the PaymentMethod object.

accountId
Salesforce account ID to which this payment method is linked.

Signature
public String accountId {get; set;}

Property Value
Type: String

email
Email address of the card holder.

Signature
public String email {get; set;}

Property Value
Type: String

gatewayToken
A unique, alphanumeric ID, that a payment gateway generates when it first processes a payment.
The token replaces the actual payment data so that the data is kept secure. This token is stored as encrypted text, and can be used for
recurring payments.

Signature
public String gatewayToken {get; set;}

Property Value
Type: String

gatewayTokenDetails
Information about the gateway token.

Signature
public String gatewayTokenDetails {get; set;}

333
Apex Reference Guide AlternativePaymentMethodRequest Class

Property Value
Type: String

name
Name that you assign to the PaymentMethod object.

Signature
public String name {get; set;}

Property Value
Type: String

AlternativePaymentMethodRequest Methods
The following are methods for AlternativePaymentMethodRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type AlternativePaymentMethodRequest by determining the equality of external
objects in a list. This method is dynamic and based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type AlternativePaymentMethodRequest by determining the uniqueness of the external
object records in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type AlternativePaymentMethodRequest by determining the equality of external objects
in a list. This method is dynamic and based on the equals method in Java.

Signature
public Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

334
Apex Reference Guide AlternativePaymentMethodResponse Class

hashCode()
Maintains the integrity of lists of type AlternativePaymentMethodRequest by determining the uniqueness of the external
object records in a list.

Signature
public Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
public String toString()

Return Value
Type: String

AlternativePaymentMethodResponse Class
The class contains the response details of the alternative payment method.

Namespace
CommercePayments

Example

commercepayments.AlternativePaymentMethodResponse response = new


commercepayments.AlternativePaymentMethodResponse();
response.setEmail('alternativePaymentMethod');
response.setEmail('[email protected]');
response.setGatewayToken('NMoPoIOnTZSaRaWcV7gUUXe');
response.setGatewayTokenDetails('gateway token details');

IN THIS SECTION:
AlternativePaymentMethodResponse Methods

AlternativePaymentMethodResponse Methods
The following are methods for AlternativePaymentMethodResponse.

335
Apex Reference Guide AlternativePaymentMethodResponse Class

IN THIS SECTION:
setAccountId(accountId)
Sets the ID of the Salesforce payments account to which the payment method is linked.
setComments(comments)
Sets the notes about the payment method added by users.
setEmail(email)
Sets the email ID of the card holder.
setGatewayToken(gatewayToken)
Sets the token ID that a payment gateway generates when it first processes a payment.
setGatewayTokenDetails(gatewayTokenDetails)
Sets the details about the payment gateway token.
setName(name)
Sets the name that is assigned to the PaymentMethod object.

setAccountId(accountId)
Sets the ID of the Salesforce payments account to which the payment method is linked.

Signature
public void setAccountId(Id accountId)

Parameters
accountId
Type: Id
Salesforce payments account ID.

Return Value
Type: void

setComments(comments)
Sets the notes about the payment method added by users.

Signature
public void setComments(String comments)

Parameters
comments
Type: String
Notes about the payment method added by users, maximum 1000 characters.

336
Apex Reference Guide AlternativePaymentMethodResponse Class

Return Value
Type: void

setEmail(email)
Sets the email ID of the card holder.

Signature
public void setEmail(String email)

Parameters
email
Type: String
Email ID of the card holder.

Return Value
Type: void

setGatewayToken(gatewayToken)
Sets the token ID that a payment gateway generates when it first processes a payment.

Signature
public void setGatewayToken(String gatewayToken)

Parameters
gatewayToken
Type: String
A unique, alphanumeric ID, called a token, that a payment gateway generates when it first processes a payment. The token replaces
the actual payment data so that the data is kept secure. This token is stored as encrypted text, and can be used for recurring payments.

Return Value
Type: void

setGatewayTokenDetails(gatewayTokenDetails)
Sets the details about the payment gateway token.

Signature
public void setGatewayTokenDetails(String gatewayTokenDetails)

337
Apex Reference Guide AuditParamsRequest

Parameters
gatewayTokenDetails
Type: String
Detailed information about the gateway token.

Return Value
Type: void

setName(name)
Sets the name that is assigned to the PaymentMethod object.

Signature
public void setName(String name)

Parameters
name
Type: String
Name that you assign to the payment method object.

Return Value
Type: void

AuditParamsRequest
AuditParamsRequest is used for audit parameters in a transaction request. This is an abstract request class that is extended by
the BaseRequest class.

Namespace
CommercePayments

Usage
AuditParamsRequest is an abstract class that holds attributes related to audit parameters such as email, IP address, MAC address,
and phone number. This class can't be instantiated on its own. All CommercePayments request classes extend this class.

IN THIS SECTION:
AuditParamsRequest Constructors
AuditParamsRequest Properties

338
Apex Reference Guide AuditParamsRequest

AuditParamsRequest Constructors
The following are constructors for AuditParamsRequest.

IN THIS SECTION:
AuditParamsRequest(email, macAddress, ipAddress, phone)
This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

AuditParamsRequest(email, macAddress, ipAddress, phone)


This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Signature
AuditParamsRequest(String email, String macAddress, String ipAddress, String phone)

Parameters
email
Type: String
Email of the client that initiated the request.
macAddress
Type: String
Mac address of the customer’s device. Gateways often use this data in risk checks.
ipAddress
Type: String
The customer’s IP address. Gateways often use this data in risk checks.
phone
Type: String
Phone number of the client that initiated the request.

AuditParamsRequest Properties
The following are properties for AuditParamsRequest.

IN THIS SECTION:
email
Email of the client that initiated the request.
ipAddress
The customer’s IP address. Gateways often use this data in risk checks.
macAddress
Mac address of the customer’s device. Gateways often use this data in risk checks.
phone
Phone number of the client that initiated the request.

339
Apex Reference Guide AuthApiPaymentMethodRequest Class

email
Email of the client that initiated the request.

Property Value
Type: String

ipAddress
The customer’s IP address. Gateways often use this data in risk checks.

Property Value
Type: String

macAddress
Mac address of the customer’s device. Gateways often use this data in risk checks.

Property Value
Type: String

phone
Phone number of the client that initiated the request.

Property Value
Type: String

AuthApiPaymentMethodRequest Class
Sends information about a payment method to a gateway adapter during an authorization service call.

Namespace
CommercePayments

Usage
Contains information about the payment method that is used for an authorization request. It contains all available payment methods
as fields, but populates only one field for each request. The gateway adapter uses this class when constructing an authorization request.
An object of this class is available through the paymentMethod field on the AuthorizationRequest Class object.

IN THIS SECTION:
AuthApiPaymentMethodRequest Constructors
AuthApiPaymentMethodRequest Properties

340
Apex Reference Guide AuthApiPaymentMethodRequest Class

AuthApiPaymentMethodRequest Constructors
The following are constructors for AuthApiPaymentMethodRequest.

IN THIS SECTION:
AuthApiPaymentMethodRequest(cardPaymentMethodRequest)
Constructs a sample cardPaymentMethodRequest. This constructor is intended for test usage and throws an exception if
used outside of the Apex test context.
AuthApiPaymentMethodRequest()
Constructor for AuthApiPaymentMethodRequest.

AuthApiPaymentMethodRequest(cardPaymentMethodRequest)
Constructs a sample cardPaymentMethodRequest. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

Signature
global AuthApiPaymentMethodRequest(commercepayments.CardPaymentMethodRequest
cardPaymentMethodRequest)

Parameters
cardPaymentMethodRequest
Type: commercepayments.CardPaymentMethodRequest on page 385
Contains information about the card payment method. Used to send information to a gateway adapter during a service call.

AuthApiPaymentMethodRequest()
Constructor for AuthApiPaymentMethodRequest.

Signature
global AuthApiPaymentMethodRequest()

AuthApiPaymentMethodRequest Properties
The following are properties for AuthApiPaymentMethodRequest.

IN THIS SECTION:
cardPaymentMethod
The card payment method object used in a payment method request.

cardPaymentMethod
The card payment method object used in a payment method request.

341
Apex Reference Guide AuthorizationRequest Class

Signature
global commercepayments.CardPaymentMethodRequest cardPaymentMethod {get; set;}

Property Value
Type: commercepayments.CardPaymentMethodRequest on page 385

AuthorizationRequest Class
Sends information about an authorization request to a gateway adapter during a service call. This class extends the BaseRequest
class and inherits all its methods.

Namespace
CommercePayments

Usage
This class contains information about a transaction authorization request. The gateway adapter reads fields from this class while
constructing an authorization JSON request to send to the payment gateway. An object of this class is available by calling
getPaymentRequest() in the PaymentGatewayContext Class.

Example
Creating a buildAuthRequest class to store information about the authorization request.
private String buildAuthRequest(commercepayments.AuthorizationRequest authRequest) {
// Multiply amount by 100.0 to convert to cents
String requestBody =
createRequestBody(String.ValueOf((authRequest.amount*100.0).intValue()), authRequest);
return requestBody;

private String createRequestBody(String amount, commercepayments.AuthorizationRequest


authRequest) {
JSONGenerator jsonGeneratorInstance = JSON.createGenerator(true);
String currencyIso = authRequest.currencyIsoCode;
commercepayments.AuthApiPaymentMethodRequest paymentMethod =
authRequest.paymentMethod;
commercepayments.GatewayErrorResponse error;
// Write data to the JSON string.
jsonGeneratorInstance.writeStartObject();
jsonGeneratorInstance.writeStringField('merchantAccount', '{!$Credential.Username}');

jsonGeneratorInstance.writeStringField('reference', authRequest.comments == null


? 'randomstring' : authRequest.comments);

if(currencyIso == null) {
currencyIso = UserInfo.getDefaultCurrency();
}

jsonGeneratorInstance.writeFieldName('amount');

342
Apex Reference Guide AuthorizationRequest Class

jsonGeneratorInstance.writeStartObject();
jsonGeneratorInstance.writeStringField('value', amount);
jsonGeneratorInstance.writeStringField('currency', currencyIso);
jsonGeneratorInstance.writeEndObject();

commercepayments.CardPaymentMethodRequest cardPaymentMethod;
if(paymentMethod != null) {
cardPaymentMethod = paymentMethod.cardPaymentMethod;
if (cardPaymentMethod != null) {
if (cardPaymentMethod.CardCategory != null) {
if (commercepayments.CardCategory.CreditCard ==
cardPaymentMethod.CardCategory) {
jsonGeneratorInstance.writeFieldName('card');
jsonGeneratorInstance.writeStartObject();
if (cardPaymentMethod.cvv != null)
jsonGeneratorInstance.writeStringField('cvc',
String.ValueOf(cardPaymentMethod.cvv));
if (cardPaymentMethod.cardholdername != null)
jsonGeneratorInstance.writeStringField('holderName',
cardPaymentMethod.cardholdername);
if (cardPaymentMethod.cardnumber != null)
jsonGeneratorInstance.writeStringField('number',
cardPaymentMethod.cardnumber);
if (cardPaymentMethod.expiryMonth != null &&
cardPaymentMethod.expiryYear != null ) {
String expMonth =
((String.ValueOf(cardPaymentMethod.expiryMonth)).length() == 1 ? '0' : '') +
String.ValueOf(cardPaymentMethod.expiryMonth);
jsonGeneratorInstance.writeStringField('expiryMonth', expMonth);

jsonGeneratorInstance.writeStringField('expiryYear',
String.ValueOf(cardPaymentMethod.expiryYear));
}
jsonGeneratorInstance.writeEndObject();
} else {
//Support for other card type
}
} else {
throw new SampleValidationException('Required Field Missing :
CardCategory');
}
} else {
throw new SampleValidationException('Required Field Missing :
CardPaymentMethod');
}
} else {
throw new SampleValidationException('Required Field Missing : PaymentMethod');

}
jsonGeneratorInstance.writeEndObject();
return jsonGeneratorInstance.getAsString();
}

343
Apex Reference Guide AuthorizationRequest Class

IN THIS SECTION:
AuthorizationRequest Constructors
AuthorizationRequest Properties
AuthorizationRequest Methods

AuthorizationRequest Constructors
The following are constructors for AuthorizationRequest.

IN THIS SECTION:
AuthorizationRequest(amount)
Constructor for building the amount in an authorization request. This constructor is intended for test usage and throws an exception
if used outside of the Apex test context.

AuthorizationRequest(amount)
Constructor for building the amount in an authorization request. This constructor is intended for test usage and throws an exception if
used outside of the Apex test context.

Signature
global AuthorizationRequest(Double amount)

Parameters
amount
Type: Double
The amount of the authorization.

AuthorizationRequest Properties
The following are properties for AuthorizationRequest.

IN THIS SECTION:
accountId
The customer account where the authorization is performed.
amount
The total amount of the authorization. Can be positive or negative.
comments
Comments about the authorization. Users can enter comments to provide additional information.
currencyIsoCode
The ISO currency code for the authorization request.
paymentMethod
The payment method used to process the authorization in the authorization request.

344
Apex Reference Guide AuthorizationRequest Class

accountId
The customer account where the authorization is performed.

Signature
global String accountId {get; set;}

Property Value
Type: String

amount
The total amount of the authorization. Can be positive or negative.

Signature
global Double amount {get; set;}

Property Value
Type: Double

comments
Comments about the authorization. Users can enter comments to provide additional information.

Signature
global String comments {get; set;}

Property Value
Type: String

currencyIsoCode
The ISO currency code for the authorization request.

Signature
global String currencyIsoCode {get; set;}

Property Value
Type: String

paymentMethod
The payment method used to process the authorization in the authorization request.

345
Apex Reference Guide AuthorizationRequest Class

Signature
global AuthApiPaymentMethodRequest paymentMethod {get; set;}

Property Value
Type: AuthApiPaymentMethodRequest on page 340

AuthorizationRequest Methods
The following are methods for AuthorizationRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type AuthorizationRequest by determining the equality of external objects in a list. This
method is dynamic and based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type AuthorizationRequest by determining the uniqueness of the external object in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type AuthorizationRequest by determining the equality of external objects in a list. This
method is dynamic and based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type AuthorizationRequest by determining the uniqueness of the external object in a list.

Signature
global Integer hashCode()

346
Apex Reference Guide AuthorizationResponse Class

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

AuthorizationResponse Class
Response sent by the payment gateway adapter for an authorization service.

Namespace
CommercePayments

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.AuthorizationResponse authr = new
CommercePayments.AuthorizationResponse();
Contains information about the payment gateway’s response following an authorization transaction. The gateway adapter uses the
payment gateway’s response to populate the AuthorizationResponse fields. The payments platform uses the information from
this class to construct the authorization gateway response shown to the user.

Example
private commercepayments.GatewayResponse createAuthResponse(HttpResponse response, Double
amount) {
Map<String, Object> mapOfResponseValues = (Map
<String, Object>) JSON.deserializeUntyped(response.getBody());

commercepayments.AuthorizationResponse authResponse = new


commercepayments.AuthorizationResponse();

String resultCode = (String)mapOfResponseValues.get('resultCode');

if(resultCode != null){
system.debug('Response - success');
if(resultCode.equals('Authorised')){
system.debug('status - authorised');

347
Apex Reference Guide AuthorizationResponse Class

authResponse.setGatewayAuthCode((String)mapOfResponseValues.get('authCode'));

authResponse.setSalesforceResultCodeInfo(new
commercepayments.SalesforceResultCodeInfo(commercepayments.SalesforceResultCode.Success));

} else {
//Sample returns 200 with refused status in some cases
system.debug('status - refused');

authResponse.setGatewayResultCodeDescription((String)mapOfResponseValues.get('refusalReason'));

authResponse.setSalesforceResultCodeInfo(new
commercepayments.SalesforceResultCodeInfo(commercepayments.SalesforceResultCode.Decline));

authResponse.setGatewayReferenceNumber((String)mapOfResponseValues.get('pspReference'));
authResponse.setAmount(amount);
authResponse.setGatewayDate(system.now());
return authResponse;
} else {
system.debug('Response - failed');
system.debug('Validation error');
String statusCode = (String)mapOfResponseValues.get('errorType');
String message = (String)mapOfResponseValues.get('message');
commercepayments.GatewayErrorResponse error = new
commercepayments.GatewayErrorResponse(statusCode, message);
return error;
}
}

IN THIS SECTION:
AuthorizationResponse Methods

AuthorizationResponse Methods
The following are methods for AuthorizationResponse.

IN THIS SECTION:
setAmount(amount)
Sets the amount of the authorization. Must be a non-zero value.
setAuthorizationExpirationDate(authExpDate)
Sets the expiration date of the authorization request.
setGatewayAuthCode(gatewayAuthCode)
Sets the authorization code that the gateway returned. Maximum length of 64 characters.
setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.

348
Apex Reference Guide AuthorizationResponse Class

setGatewayDate(gatewayDate)
Sets the date that the authorization occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the authorization request. Maximum length of 255 characters.
setGatewayReferenceDetails(gatewayReferenceDetails)
Stores data that you can use for subsequent authorizations. You can use any data that isn’t normalized in financial entities. This field
has a maximum length of 1000 characters and can store data as JSON or XML.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse)
Sets information from the gateway about the tokenized payment method.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

setAmount(amount)
Sets the amount of the authorization. Must be a non-zero value.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double

Return Value
Type: void

setAuthorizationExpirationDate(authExpDate)
Sets the expiration date of the authorization request.

Signature
global void setAuthorizationExpirationDate(Datetime authExpDate)

349
Apex Reference Guide AuthorizationResponse Class

Parameters
authExpDate
Type: Datetime

Return Value
Type: void

setGatewayAuthCode(gatewayAuthCode)
Sets the authorization code that the gateway returned. Maximum length of 64 characters.

Signature
global void setGatewayAuthCode(String gatewayAuthCode)

Parameters
gatewayAuthCode
Type: String
The authorization code returned by the gateway.

Return Value
Type: void

setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String
Used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment
gateway.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the authorization occurred. Some gateways don’t send this value.

350
Apex Reference Guide AuthorizationResponse Class

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the authorization request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Stores data that you can use for subsequent authorizations. You can use any data that isn’t normalized in financial entities. This field has
a maximum length of 1000 characters and can store data as JSON or XML.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.

351
Apex Reference Guide AuthorizationResponse Class

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique authorization ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be used to map a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the gateway’s result code. Use this field to learn more about why the gateway returned a certain result code.

Return Value
Type: void

352
Apex Reference Guide AuthorizationReversalRequest Class

setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse)
Sets information from the gateway about the tokenized payment method.

Signature
global void
setPaymentMethodTokenizationResponse(commercepayments.PaymentMethodTokenizationResponse
paymentMethodTokenizationResponse)

Parameters
paymentMethodTokenizationResponse
PaymentMethodTokenizationResponse on page 423
Gateway response sent by payment gateway adapters for the payment method tokenization request.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce uses
the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: SalesforceResultCodeInfo on page 465
Description of the Salesforce result code value.

Return Value
Type: void

AuthorizationReversalRequest Class
Sends information about an authorization reversal request to a gateway adapter during a service call.

Namespace
CommercePayments on page 317

353
Apex Reference Guide AuthorizationReversalRequest Class

Example
Add your reversal classes to your payment gateway adapter. We recommend adding AuthorizationReversal as a possible
requestType value when calling processRequest on the gateway’s response.
global commercepayments.GatewayResponse processRequest(commercepayments.paymentGatewayContext
gatewayContext) {
commercepayments.RequestType requestType = gatewayContext.getPaymentRequestType();

commercepayments.GatewayResponse response;

try {
//add other requestType values here
//..
else if (requestType == commercepayments.RequestType.AuthorizationReversal) {
response =
createAuthReversalResponse((commercepayments.AuthorizationReversalRequest)gatewayContext.getPaymentRequest());}

return response;

Then, add a class that sets the amount of the authorization reversal request, as well as gateway information and the Salesforce result
code.
global commercepayments.GatewayResponse
createAuthReversalResponse(commercepayments.AuthorizationReversalRequest authReversalRequest)
{
commercepayments.AuthorizationReversalResponse authReversalResponse = new
commercepayments.AuthorizationReversalResponse();
if(authReversalRequest.amount!=null )
{
authReversalResponse.setAmount(authReversalRequest.amount);
}
else
{
throw new SalesforceValidationException('Required Field Missing : Amount');

system.debug('Response - success');
authReversalResponse.setGatewayDate(system.now());
authReversalResponse.setGatewayResultCode('00');
authReversalResponse.setGatewayResultCodeDescription('Transaction Normal');
authReversalResponse.setGatewayReferenceNumber('SF'+getRandomNumber(6));

authReversalResponse.setSalesforceResultCodeInfo(SUCCESS_SALESFORCE_RESULT_CODE_INFO);
return authReversalResponse;
}

IN THIS SECTION:
AuthorizationReversalRequest Constructors
AuthorizationReversalRequest Properties

354
Apex Reference Guide AuthorizationReversalRequest Class

AuthorizationReversalRequest Methods

AuthorizationReversalRequest Constructors
The following are constructors for AuthorizationReversalRequest.

IN THIS SECTION:
AuthorizationReversalRequest(amount, authorizationId)
Constructor for building the amount in an authorization reversal request. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.

AuthorizationReversalRequest(amount, authorizationId)
Constructor for building the amount in an authorization reversal request. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.

Signature
global AuthorizationReversalRequest(Double amount, String authorizationId)

Parameters
amount
Type: Double
The amount of the authorization reversal request.
authorizationId
Type: String
The authorization request to be reversed.

AuthorizationReversalRequest Properties
The following are properties for AuthorizationReversalRequest.

IN THIS SECTION:
accountId
References the customer account for the transaction where the authorization reversal was performed.
amount
The total amount of the authorization reversal request. Can be positive or negative.
paymentAuthorizationId
References the payment authorization to be reversed.

accountId
References the customer account for the transaction where the authorization reversal was performed.

355
Apex Reference Guide AuthorizationReversalRequest Class

Signature
global String accountId {get; set;}

Property Value
Type: String

amount
The total amount of the authorization reversal request. Can be positive or negative.

Signature
global Double amount {get; set;}

Property Value
Type: Double

paymentAuthorizationId
References the payment authorization to be reversed.

Signature
global String paymentAuthorizationId {get; set;}

Property Value
Type: String

AuthorizationReversalRequest Methods
The following are methods for AuthorizationReversalRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type AuthorizationReversalRequest by determining the equality of external objects
in a list. This method is dynamic and based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type AuthorizationReversalRequest by determining the uniqueness of the external
object in a list.
toString()
Converts a date to a string.

356
Apex Reference Guide AuthorizationReversalResponse Class

equals(obj)
Maintains the integrity of lists of type AuthorizationReversalRequest by determining the equality of external objects in a
list. This method is dynamic and based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type AuthorizationReversalRequest by determining the uniqueness of the external object
in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

AuthorizationReversalResponse Class
Response sent by the payment gateway following a payment authorization reversal service.

357
Apex Reference Guide AuthorizationReversalResponse Class

Namespace
CommercePayments

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.AuthorizationReversalResponse authRevRes = new
CommercePayments.AuthorizationResponse();
Contains information about the payment gateway’s response following an authorization reversal transaction. The gateway adapter uses
the payment gateway’s response to populate the AuthorizationReversalResponse fields. The payments platform uses the
information from this class to construct the authorization gateway response shown to the user.

Example
This class builds an authorization reversal response that contains the amount of the original reversal request, gateway information, and
the Salesforce result code.
global commercepayments.GatewayResponse
createAuthReversalResponse(commercepayments.AuthorizationReversalRequest authReversalRequest)
{
commercepayments.AuthorizationReversalResponse authReversalResponse = new
commercepayments.AuthorizationReversalResponse();
if(authReversalRequest.amount!=null )
{
authReversalResponse.setAmount(authReversalRequest.amount);
}
else
{
throw new SalesforceValidationException('Required Field Missing : Amount');

system.debug('Response - success');
authReversalResponse.setGatewayDate(system.now());
authReversalResponse.setGatewayResultCode('00');
authReversalResponse.setGatewayResultCodeDescription('Transaction Normal');
authReversalResponse.setGatewayReferenceNumber('SF'+getRandomNumber(6));

authReversalResponse.setSalesforceResultCodeInfo(SUCCESS_SALESFORCE_RESULT_CODE_INFO);
return authReversalResponse;
}

IN THIS SECTION:
AuthorizationReversalResponse Methods

AuthorizationReversalResponse Methods
The following are methods for AuthorizationReversalResponse.

358
Apex Reference Guide AuthorizationReversalResponse Class

IN THIS SECTION:
setAmount(amount)
Contains the amount of the authorization reversal. Must be a non-zero value.
setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (Address Verification System) result code that the gateway returned. Maximum length of 64 characters.
setGatewayDate(gatewayDate)
Sets the date that the authorization reversal request occurred in the payment gateway. Some gateways don't send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the authorization reversal request. Maximum length of 255 characters.
setGatewayReferenceDetails(gatewayReferenceDetails)
Stores data that you can use for subsequent authorizations. You can use any data that isn’t normalized in financial entities. This field
has a maximum length of 1000 characters and can store data as JSON or XML.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets a unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

setAmount(amount)
Contains the amount of the authorization reversal. Must be a non-zero value.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double

Return Value
Type: void

setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (Address Verification System) result code that the gateway returned. Maximum length of 64 characters.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

359
Apex Reference Guide AuthorizationReversalResponse Class

Parameters
gatewayAvsCode
Type: String
Used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment
gateway.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the authorization reversal request occurred in the payment gateway. Some gateways don't send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the authorization reversal request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Stores data that you can use for subsequent authorizations. You can use any data that isn’t normalized in financial entities. This field has
a maximum length of 1000 characters and can store data as JSON or XML.

360
Apex Reference Guide AuthorizationReversalResponse Class

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets a unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique reference ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be used to map a Salesforce-specific result code.

Return Value
Type: void

361
Apex Reference Guide BaseApiPaymentMethodRequest Class

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the gateway’s result code. Use this field to learn more about why the gateway returned a certain result code.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce uses
the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: SalesforceResultCodeInfo
Description of the Salesforce result code value.

Return Value
Type: void

BaseApiPaymentMethodRequest Class
Abstract class used to send information about a payment method to a gateway adapter during a service call.

Namespace
CommercePayments

362
Apex Reference Guide BaseApiPaymentMethodRequest Class

Usage
BaseApiPaymentMethodRequest is the base class for SaleApiPaymentMethodRequest and
AuthApiPaymentMethodRequest.

IN THIS SECTION:
BaseApiPaymentMethodRequest Constructors
BaseApiPaymentMethodRequest Properties
BaseApiPaymentMethodRequest Methods

BaseApiPaymentMethodRequest Constructors
The following are constructors for BaseApiPaymentMethodRequest.

IN THIS SECTION:
BaseApiPaymentMethodRequest(address, id, saveForFuture)
Constructs a payment method. This constructor is intended for test usage and throws an exception if used outside of the Apex test
context.

BaseApiPaymentMethodRequest(address, id, saveForFuture)


Constructs a payment method. This constructor is intended for test usage and throws an exception if used outside of the Apex test
context.

Signature
global BaseApiPaymentMethodRequest(commercepayments.AddressRequest address, String id,
Boolean saveForFuture)

Parameters
address
Type: commercepayments.AddressRequest on page 327
Sends data related on address request to a gateway adapter during a service call.
id
Type: String
saveForFuture
Type: Boolean
Indicates whether Salesforce saves the payment method for future use.

BaseApiPaymentMethodRequest Properties
The following are properties for BaseApiPaymentMethodRequest.

363
Apex Reference Guide BaseApiPaymentMethodRequest Class

IN THIS SECTION:
address
The payment method’s address.
id
ID of the payment method request.
saveForFuture
Indicates whether the payment method is saved as a record in Salesforce for future use.

address
The payment method’s address.

Signature
global commercepayments.AddressRequest address {get; set;}

Property Value
Type: AddressRequest on page 327

id
ID of the payment method request.

Signature
global String id {get; set;}

Property Value
Type: String

saveForFuture
Indicates whether the payment method is saved as a record in Salesforce for future use.

Signature
global Boolean saveForFuture {get; set;}

Property Value
Type: Boolean

BaseApiPaymentMethodRequest Methods
The following are methods for BaseApiPaymentMethodRequest.

364
Apex Reference Guide BaseApiPaymentMethodRequest Class

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type BaseApiPaymentMethodRequest by determining the equality of external objects in
a list. This method is dynamic and is based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type BaseApiPaymentMethodRequest by determining the uniqueness of the external
object records in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type BaseApiPaymentMethodRequest by determining the equality of external objects in a
list. This method is dynamic and is based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type BaseApiPaymentMethodRequest by determining the uniqueness of the external object
records in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

365
Apex Reference Guide BaseNotification Class

Return Value
Type: String

BaseNotification Class
Abstract class for storing notification information sent from payment gateways.

Namespace
CommercePayments

Usage
An abstract class that contains the common fields from payment gateways. BaseNotification can’t be instantiated on its own.
The constructor of this class takes no arguments. For example:
CommercePayments.BaseNotification bnt = new CommercePayments.BaseNotification();

Example
commercepayments.BaseNotification notification = null;
if ('CAPTURE'.equals(eventCode)) {
notification = new commercepayments.CaptureNotification();
} else if ('REFUND'.equals(eventCode)) {
notification = new commercepayments.ReferencedRefundNotification();
}

IN THIS SECTION:
BaseNotification Methods

BaseNotification Methods
The following are methods for BaseNotification.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount. Must be a non-negative value.
setGatewayDate(gatewayDate)
Sets the date that the notification occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the notification request. Maximum length of 255 characters.
setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.

366
Apex Reference Guide BaseNotification Class

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setId(id)
Sets the ID of the notification sent by the gateway.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the information about the Salesforce-specific result code used to match a result code from a payment gateway.
setStatus(status)
Sets the status of the notification sent by the gateway.

setAmount(amount)
Sets the transaction amount. Must be a non-negative value.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount of the transaction.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the notification occurred. Some gateways don’t send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime
The date that the notification occurred.

Return Value
Type: void

367
Apex Reference Guide BaseNotification Class

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the notification request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String
The message that the gateway returned with the notification request. Contains additional information about the notification.

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String
Provides information about the gateway communication.

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique transaction ID created by the payment gateway.

368
Apex Reference Guide BaseNotification Class

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be used to map a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Provides additional information about the result code and why the gateway returned the code. Descriptions vary between different
gateways.

Return Value
Type: void

setId(id)
Sets the ID of the notification sent by the gateway.

Signature
global void setId(String id)

369
Apex Reference Guide BasePaymentMethodRequest Class

Parameters
id
Type: String

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the information about the Salesforce-specific result code used to match a result code from a payment gateway.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: commercepayments.SalesforceResultCodeInfo on page 465
Payment gateways have many response codes for payment calls. Salesforce uses the result code information to map payment
gateway codes to a predefined set of standard Salesforce result codes.

Return Value
Type: void

setStatus(status)
Sets the status of the notification sent by the gateway.

Signature
global void setStatus(commercepayments.NotificationStatus status)

Parameters
status
Type: commercepayments.NotificationStatus on page 408
Shows whether the payments platform successfully received the notification from the gateway.

Return Value
Type: void

BasePaymentMethodRequest Class
Abstract class for storing information about payment methods.

370
Apex Reference Guide BasePaymentMethodRequest Class

Namespace
CommercePayments

Usage
The BasePaymentMethodRequest class contains fields common to CardPaymentMethodRequest on page 385
.

IN THIS SECTION:
BasePaymentMethodRequest Methods

BasePaymentMethodRequest Methods
The following are methods for BasePaymentMethodRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type BasePaymentMethodRequest by determining the equality of external objects in a list.
This method is dynamic and based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type BasePaymentMethodRequest by determining the uniqueness of the external object
records in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type BasePaymentMethodRequest by determining the equality of external objects in a list. This
method is dynamic and based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

371
Apex Reference Guide BaseRequest Class

hashCode()
Maintains the integrity of lists of type BasePaymentMethodRequest by determining the uniqueness of the external object
records in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

BaseRequest Class
BaseRequest is extended by all the request classes.

Namespace
CommercePayments

IN THIS SECTION:
BaseRequest Methods

BaseRequest Methods
The following are methods for BaseRequest.

IN THIS SECTION:
BaseRequest(AdditionalData, IdempotencyKey)
Used for testing.

BaseRequest(AdditionalData, IdempotencyKey)
Used for testing.

372
Apex Reference Guide CaptureNotification Class

Signature
global Void BaseRequest(String AdditionalData, Map<String, String> IdempotencyKey)

Parameters
AdditionalData
Type: String
Contains additional data that may be required for a payment request. The additionalData object consists of key-value pairs.
You can retrieve the additionalData object from the request object: Map<String, String>
additionalData=request.additionalData
IdempotencyKey
Type: Map<String, String>
Unique value that's generated by a client and sent to the server in the request. The server stores the value and uses the it to keep
track of the request status.

Return Value
Type: Void

CaptureNotification Class
When a payment gateway sends a notification for a capture transaction, the payment gateway adapter creates the
CaptureNotification object to store information about the notification.

Namespace
CommercePayments

Usage
CaptureNotification is used in asynchronous payment gateway adapters.
Specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes no arguments.
For example:
CommercePayments.CaptureNotification crn = new CommercePayments.CaptureNotification();

Example
commercepayments.BaseNotification notification = null;
if ('CAPTURE'.equals(eventCode)) {
notification = new commercepayments.CaptureNotification();
} else if ('REFUND'.equals(eventCode)) {
notification = new commercepayments.ReferencedRefundNotification();
}

IN THIS SECTION:
CaptureNotification Methods

373
Apex Reference Guide CaptureNotification Class

CaptureNotification Methods
The following are methods for CaptureNotification.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount. Must be a non-negative value.
setGatewayDate(gatewayDate)
Sets the date that the transaction occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the payment request. Maximum length of 255 characters.
setGatewayReferenceDetails(gatewayReferenceDetails)
Sets additional data that you can use for subsequent transactions. You can use any data that isn’t normalized in financial entities.
This field has a maximum length of 1000 characters and can store data as JSON or XML.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a gateway returned. Maximum length of 1000 characters.
setId(id)
Sets the ID of a notification sent by the payment gateway.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.
setStatus(status)
Sets the notification status to the same value that was sent by the gateway.

setAmount(amount)
Sets the transaction amount. Must be a non-negative value.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount to be debited or captured.

Return Value
Type: void

374
Apex Reference Guide CaptureNotification Class

setGatewayDate(gatewayDate)
Sets the date that the transaction occurred. Some gateways don’t send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime
Date and time of the gateway communication.

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the payment request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String
Information on error messages sent from the gateway.

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets additional data that you can use for subsequent transactions. You can use any data that isn’t normalized in financial entities. This
field has a maximum length of 1000 characters and can store data as JSON or XML.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String

375
Apex Reference Guide CaptureNotification Class

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique transaction ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code can be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Map this value to a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

376
Apex Reference Guide CaptureNotification Class

Parameters
gatewayResultCodeDescription
Type: String
Description of the gateway’s result code. Use this field to learn more about why the gateway returned a certain result code.

Return Value
Type: void

setId(id)
Sets the ID of a notification sent by the payment gateway.

Signature
global void setId(String id)

Parameters
id
Type: String

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce uses
the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: commercepayments.SalesforceResultCodeInfo on page 465
Description of the Salesforce result code value.

Return Value
Type: void

setStatus(status)
Sets the notification status to the same value that was sent by the gateway.

377
Apex Reference Guide CaptureRequest Class

Signature
global void setStatus(commercepayments.NotificationStatus status)

Parameters
status
Type: NotificationStatus on page 408
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Return Value
Type: void

CaptureRequest Class
Represents a capture request. This class extends the BaseRequest class and inherits all its methods.

Namespace
CommercePayments on page 317

Usage
The CaptureRequest class’s buildCaptureRequest method creates a CaptureRequest object to store payment information,
such as value and currency, as JSON strings.

Example
Builds a CaptureRequest object for a multicurrency org.
private String buildCaptureRequest(commercepayments.CaptureRequest captureRequest) {
Boolean IS_MULTICURRENCY_ORG = UserInfo.isMultiCurrencyOrganization();
QueryUtils qBuilderForAuth = new QueryUtils(PaymentAuthorization.SObjectType);
// Add required fields
qBuilderForAuth.getSelectClause().addField('GatewayRefNumber', false);
if (IS_MULTICURRENCY_ORG) {
// addField also takes a boolean to enable translation (uses label instead of
actual value)
qBuilderForAuth.getSelectClause().addField('CurrencyIsoCode', false);
}

IN THIS SECTION:
CaptureRequest Constructors
CaptureRequest Properties

378
Apex Reference Guide CaptureRequest Class

CaptureRequest Constructors
The following are constructors for CaptureRequest.

IN THIS SECTION:
CaptureRequest(amount, authorizationId)
This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

CaptureRequest(amount, authorizationId)
This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Parameters
amount
Type: Double
The amount to be debited or captured.
authorizationId
Type: String
Represents a payment authorization record.

CaptureRequest Properties
The following are properties for CaptureRequest.

IN THIS SECTION:
accountId
Account ID value. References an account record.
amount
Amount of currency that needs to be captured.
paymentAuthorizationId
ID value that references a PaymentAuthorization.

accountId
Account ID value. References an account record.

Property Value
Type: String

amount
Amount of currency that needs to be captured.

379
Apex Reference Guide CaptureResponse Class

Property Value
Type: Double

paymentAuthorizationId
ID value that references a PaymentAuthorization.

Property Value
Type: String

CaptureResponse Class
The payment gateway adapter sends this response for the capture request type. This class extends AbstractResponse and inherits
its methods.

Namespace
CommercePayments on page 317

Usage
You must specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes
no arguments. For example:
CommercePayments.Capture Response ctr = new CommercePayments.CaptureResponse();

IN THIS SECTION:
CaptureResponse Methods

CaptureResponse Methods
The following are methods for CaptureResponse.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount.
setAsync(async)
Indicates whether the payment gateway adapter used in the payment capture was asynchronous (True) or synchronous (False).
setGatewayAvsCode(gatewayAvsCode)
Sets the payment gateway’s AVS (address verification system) code.
setGatewayDate(gatewayDate)
Sets the payment gateway’s date.
setGatewayMessage(gatewayMessage)
Sets information or messages that the gateway returned.

380
Apex Reference Guide CaptureResponse Class

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.
setGatewayResultCode(gatewayResultCode)
Sets the payment gateway’s result code.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets the payment gateway’s result code description.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets Salesforce result code information.

setAmount(amount)
Sets the transaction amount.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount to be debited or captured.

Return Value
Type: void

setAsync(async)
Indicates whether the payment gateway adapter used in the payment capture was asynchronous (True) or synchronous (False).

Signature
global void setAsync(Boolean async)

Parameters
async
Type: Boolean

Return Value
Type: void

381
Apex Reference Guide CaptureResponse Class

setGatewayAvsCode(gatewayAvsCode)
Sets the payment gateway’s AVS (address verification system) code.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String
Payment gateways that use an AVS system return this code.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the payment gateway’s date.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime
The date that communication happened with the gateway.

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets information or messages that the gateway returned.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String
Information or error messages returned by the gateway.

382
Apex Reference Guide CaptureResponse Class

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String
Provides information about the gateway communication.

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique transaction ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets the payment gateway’s result code.

Signature
global void setGatewayResultCode(String gatewayResultCode)

383
Apex Reference Guide CardCategory Enum

Parameters
gatewayResultCode
Type: String
The gateway result code. You must map this to a Salesforce result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets the payment gateway’s result code description.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the GatewayResultCode. Provides additional context about the result code that the gateway returned.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets Salesforce result code information.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
SalesforceResultCodeInfoType: commercepayments.SalesforceResultCodeInfo
Description of the Salesforce result code value.

Return Value
Type: void

CardCategory Enum
Defines whether the payment method represents a credit card or a debit card.

384
Apex Reference Guide CardPaymentMethodRequest Class

Namespace
CommercePayments on page 317

Enum Values
The following are the values of the commercepayments.CardCategory enum.

Value Description
CreditCard Shows that the payment method is a credit card.

DebitCard Shows that the payment method is a debit card.

CardPaymentMethodRequest Class
Sends data related to a card payment method to a gateway adapter during a service call.

Namespace
CommercePayments on page 317

Usage
This class contains details about the card used as a payment method for authorization, sale, or tokenization transaction requests. The
gateway adapter reads the fields of this class object while constructing a transaction JSON request to send to the payment gateway.
The object of this class is available as the cardPaymentMethod field in the SaleApiPaymentMethodRequest Class,
AuthApiPaymentMethodRequest Class, and PaymentMethodTokenizationRequest Class.

Example: This code sample retrieves the cardPaymentMethodRequest object from the paymentMethod class.
commercepayments.CardPaymentMethodRequest cardPaymentMethod =
paymentMethod.cardPaymentMethod;

IN THIS SECTION:
CardPaymentMethodRequest Constructors
CardPaymentMethodRequest Properties
CardPaymentMethodRequest Methods

CardPaymentMethodRequest Constructors
The following are constructors for CardPaymentMethodRequest.

IN THIS SECTION:
CardPaymentMethodRequest(cardCategory)
Sets the cardCategory value for the card payment method request.

385
Apex Reference Guide CardPaymentMethodRequest Class

CardPaymentMethodRequest(cardCategory)
Sets the cardCategory value for the card payment method request.

Signature
global CardPaymentMethodRequest(commercepayments.CardCategory cardCategory)

Parameters
cardCategory
Type: CardCategory on page 384
Defines whether the card payment method is a credit card or a debit card.

CardPaymentMethodRequest Properties
The following are properties for CardPaymentMethodRequest.

IN THIS SECTION:
accountId
Customer account for this payment method.
autoPay
Indicates whether a token is being requested so that the payment method can be used for recurring payments.
cardCategory
Indicates whether a card payment method is for a credit card or debit card.
cardHolderFirstName
The first name of the cardholder for the card payment method.
cardHolderLastName
The last name of the cardholder for the card payment method.
cardHolderName
Full name of the cardholder on the card payment method.
cardNumber
System-defined unique ID for the card payment method.
cardType
Defines the credit card bank. Possible values are AmericanExpress, DinersClub, JCB, Maestro, MasterCard,
andVisa.
cvv
The card security code for the credit or debit card on a card payment method.
email
Email address of the cardholder for the credit or debit card on a card payment method.
expiryMonth
Expiration month for the credit or debit card on a card payment method.
expiryYear
Expiration year of the credit or debit card for the card payment method.

386
Apex Reference Guide CardPaymentMethodRequest Class

inputCardType
Input field for the card type. This field doesn’t store the card type directly, but instead populates CardBin, LastFour, and
DisplayCardNumber based on the value entered in inputCardType.
startMonth
The credit or debit card becomes valid on the first day of the startMonth in the startYear
startYear
Year during which the credit or debit card becomes valid.

accountId
Customer account for this payment method.

Signature
global String accountId {get; set;}

Property Value
Type: String

autoPay
Indicates whether a token is being requested so that the payment method can be used for recurring payments.

Signature
global Boolean autoPay {get; set;}

Property Value
Type: Boolean

cardCategory
Indicates whether a card payment method is for a credit card or debit card.

Signature
global commercepayments.CardCategory cardCategory {get; set;}

Property Value
Type: CardCategory on page 384

cardHolderFirstName
The first name of the cardholder for the card payment method.

387
Apex Reference Guide CardPaymentMethodRequest Class

Signature
global String cardHolderFirstName {get; set;}

Property Value
Type: String

cardHolderLastName
The last name of the cardholder for the card payment method.

Signature
global String cardHolderLastName {get; set;}

Property Value
Type: String

cardHolderName
Full name of the cardholder on the card payment method.

Signature
global String cardHolderName {get; set;}

Property Value
Type: String

cardNumber
System-defined unique ID for the card payment method.

Signature
global String cardNumber {get; set;}

Property Value
Type: String

cardType
Defines the credit card bank. Possible values are AmericanExpress, DinersClub, JCB, Maestro, MasterCard, andVisa.

Signature
global commercepayments.CardType cardType {get; set;}

388
Apex Reference Guide CardPaymentMethodRequest Class

Property Value
Type: CardType

cvv
The card security code for the credit or debit card on a card payment method.

Signature
global String cvv {get; set;}

Property Value
Type: String

email
Email address of the cardholder for the credit or debit card on a card payment method.

Signature
global String email {get; set;}

Property Value
Type: String

expiryMonth
Expiration month for the credit or debit card on a card payment method.

Signature
global Integer expiryMonth {get; set;}

Property Value
Type: Integer

expiryYear
Expiration year of the credit or debit card for the card payment method.

Signature
global Integer expiryYear {get; set;}

Property Value
Type: Integer

389
Apex Reference Guide CardPaymentMethodRequest Class

inputCardType
Input field for the card type. This field doesn’t store the card type directly, but instead populates CardBin, LastFour, and DisplayCardNumber
based on the value entered in inputCardType.

Signature
global String inputCardType {get; set;}

Property Value
Type: String

startMonth
The credit or debit card becomes valid on the first day of the startMonth in the startYear

Signature
global Integer startMonth {get; set;}

Property Value
Type: Integer

startYear
Year during which the credit or debit card becomes valid.

Signature
global Integer startYear {get; set;}

Property Value
Type: Integer

CardPaymentMethodRequest Methods
The following are methods for CardPaymentMethodRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type CardPaymentMethodRequest by determining the equality of external objects in a list.
This method is dynamic and based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type CardPaymentMethodRequest.
toString()
Converts a date to a string.

390
Apex Reference Guide CardPaymentMethodResponse Class

equals(obj)
Maintains the integrity of lists of type CardPaymentMethodRequest by determining the equality of external objects in a list. This
method is dynamic and based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type CardPaymentMethodRequest.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

CardPaymentMethodResponse Class
This class contains details about the card payment method.

Namespace
CommercePayments

391
Apex Reference Guide CardPaymentMethodResponse Class

IN THIS SECTION:
CardPaymentMethodResponse Methods

CardPaymentMethodResponse Methods
The following are methods for CardPaymentMethodResponse.

IN THIS SECTION:
setAccountId(accountId)
Sets the Salesforce payments account to which this payment method is linked.
setAutoPay(autoPay)
Sets whether a token for recurring payments is being requested or not.
setCardBin(cardBin)
Sets the card Bank Identification Number (BIN).
setCardCategory(cardCategory)
Sets the card category.
setCardHolderFirstName(cardHolderFirstName)
Sets the first name of the card holder.
setCardHolderLastName(cardHolderLastName)
Sets the last name of the card holder.
setCardHolderName(cardHolderName)
Sets the name of the card holder.
setCardLastFour(cardLastFour)
Sets the last four digits of the card.
setCardType(cardType)
Specifies the type of the credit card issuer.
setCardTypeCategory(cardTypeCategory)
Sets the credit card issuer.
setComments(comments)
Sets the notes added by a user for card payment.
setDisplayCardNumber(displayCardNumber)
Sets the display card number.
setEmail(email)
Sets the email address of the card holder.
setExpiryMonth(expiryMonth)
Sets the month of expiry of the card.
setExpiryYear(expiryYear)
Sets the year of expiry of the card.
setNickName(nickName)
Sets the nickname of the card.

392
Apex Reference Guide CardPaymentMethodResponse Class

setStartMonth(startMonth)
Sets the month the card becomes active.
setStartYear(startYear)
Sets the year the card becomes active.

setAccountId(accountId)
Sets the Salesforce payments account to which this payment method is linked.

Signature
public void setAccountId(Id accountId)

Parameters
accountId
Type: Id
Salesforce Payments account to which this payment method is linked.

Return Value
Type: void

setAutoPay(autoPay)
Sets whether a token for recurring payments is being requested or not.

Signature
public void setAutoPay(Boolean autoPay)

Parameters
autoPay
Type: Boolean
Indicates whether a token for recurring payments is being requested (true) or not (false). The token lets the payment method
be used for recurring payments.

Return Value
Type: void

setCardBin(cardBin)
Sets the card Bank Identification Number (BIN).

Signature
public void setCardBin(String cardBin)

393
Apex Reference Guide CardPaymentMethodResponse Class

Parameters
cardBin
Type: String
Bank Identification Number (BIN). The BIN is the first 4-6 numbers on a payment card that identifies the card issuer.

Return Value
Type: void

setCardCategory(cardCategory)
Sets the card category.

Signature
public void setCardCategory(commercepayments.CardCategory cardCategory)

Parameters
cardCategory
Type: CommercePayments.CardCategory
Specifies whether it is a credit card or debit card.

Return Value
Type: void

setCardHolderFirstName(cardHolderFirstName)
Sets the first name of the card holder.

Signature
public void setCardHolderFirstName(String cardHolderFirstName)

Parameters
cardHolderFirstName
Type: String
First name of the card holder.

Return Value
Type: void

setCardHolderLastName(cardHolderLastName)
Sets the last name of the card holder.

394
Apex Reference Guide CardPaymentMethodResponse Class

Signature
public void setCardHolderLastName(String cardHolderLastName)

Parameters
cardHolderLastName
Type: String
Last name of the card holder.

Return Value
Type: void

setCardHolderName(cardHolderName)
Sets the name of the card holder.

Signature
public void setCardHolderName(String cardHolderName)

Parameters
cardHolderName
Type: String
Card holder name.

Return Value
Type: void

setCardLastFour(cardLastFour)
Sets the last four digits of the card.

Signature
public void setCardLastFour(String cardLastFour)

Parameters
cardLastFour
Type: String
Last four digits of the card.

Return Value
Type: void

395
Apex Reference Guide CardPaymentMethodResponse Class

setCardType(cardType)
Specifies the type of the credit card issuer.

Signature
public void setCardType(String cardType)

Parameters
cardType
Type: String
Type of the credit card issuer.

Return Value
Type: void

setCardTypeCategory(cardTypeCategory)
Sets the credit card issuer.

Signature
public void setCardTypeCategory(commercepayments.CardType cardTypeCategory)

Parameters
cardTypeCategory
Type: CommercePayments.CardType
Credit card issuer.

Return Value
Type: void

setComments(comments)
Sets the notes added by a user for card payment.

Signature
public void setComments(String comments)

Parameters
comments
Type: String
Details about a record added by a user, maximum is 1000 characters.

396
Apex Reference Guide CardPaymentMethodResponse Class

Return Value
Type: void

setDisplayCardNumber(displayCardNumber)
Sets the display card number.

Signature
public void setDisplayCardNumber(String displayCardNumber)

Parameters
displayCardNumber
Type: String
Displayed card number.

Return Value
Type: void

setEmail(email)
Sets the email address of the card holder.

Signature
public void setEmail(String email)

Parameters
email
Type: String
Email address of the card holder.

Return Value
Type: void

setExpiryMonth(expiryMonth)
Sets the month of expiry of the card.

Signature
public void setExpiryMonth(Integer expiryMonth)

397
Apex Reference Guide CardPaymentMethodResponse Class

Parameters
expiryMonth
Type: Integer
Month of expiry of the card.

Return Value
Type: void

setExpiryYear(expiryYear)
Sets the year of expiry of the card.

Signature
public void setExpiryYear(Integer expiryYear)

Parameters
expiryYear
Type: Integer
Year of expiry of the card.

Return Value
Type: void

setNickName(nickName)
Sets the nickname of the card.

Signature
public void setNickName(String nickName)

Parameters
nickName
Type: String
Card nickname.

Return Value
Type: void

setStartMonth(startMonth)
Sets the month the card becomes active.

398
Apex Reference Guide CardType Enum

Signature
public void setStartMonth(Integer startMonth)

Parameters
startMonth
Type: Integer
Determines from which month the card becomes active.

Return Value
Type: void

setStartYear(startYear)
Sets the year the card becomes active.

Signature
public void setStartYear(Integer startYear)

Parameters
startYear
Type: Integer
Determines from which year the card becomes active.

Return Value
Type: void

CardType Enum
Specifies the credit card issuer.

Enum Values
The following are the values of the commercepayments.CardType enum.

Value Description
AmericanExpress American Express card

DinersClub Diners Club card

Jcb Japan Credit Bureau (JCB) card

Maestro Maestro card

MasterCard Master card

399
Apex Reference Guide CustomMetadataTypeInfo Class

Value Description
Visa Visa card

CustomMetadataTypeInfo Class
Access information about custom metadata. The PaymentGatewayAdapter can send CustomMetadataTypeInfo to
transaction requests through the response object’s SalesforceResultCodeInfo.

Namespace
CommercePayments on page 317

IN THIS SECTION:
CustomMetadataTypeInfo Constructors
CustomMetadataTypeInfo Methods

CustomMetadataTypeInfo Constructors
The following are constructors for CustomMetadataTypeInfo.

IN THIS SECTION:
CustomMetadataTypeInfo(cmtRecordId, cmtSfResultCodeFieldName)
Constructor for providing custom metadata type information.

CustomMetadataTypeInfo(cmtRecordId, cmtSfResultCodeFieldName)
Constructor for providing custom metadata type information.

Signature
global CustomMetadataTypeInfo(String cmtRecordId, String cmtSfResultCodeFieldName)

Parameters
cmtRecordId
Type: String
ID of the matchedcustom metadata type record
cmtSfResultCodeFieldName
Type: String
Field that contains the Salesforce result code values. Belongs to the custom metadata type.

CustomMetadataTypeInfo Methods
The following are methods for CustomMetadataTypeInfo.

400
Apex Reference Guide GatewayErrorResponse Class

GatewayErrorResponse Class
Use to respond with an error indication following errors from the PaymentGateway adapter, such as request-forbidden responses,
custom validation errors, or expired API tokens.

Namespace
CommercePayments on page 317

Usage
Use GatewayErrorResponse to create an object that stores information about error responses sent by the payment gateway
adapter.

Example
If GatewayResponse receives an exception rather than a valid request, it calls GatewayErrorResponse to create an error
object with information about the exception.
global commercepayments.GatewayResponse processRequest(commercepayments.paymentGatewayContext
gatewayContext) {
commercepayments.RequestType requestType = gatewayContext.getPaymentRequestType();

commercepayments.GatewayResponse response;
try {
if (requestType == commercepayments.RequestType.Authorize) {
response =
createAuthResponse((commercepayments.AuthorizationRequest)gatewayContext.getPaymentRequest());

} else if (requestType == commercepayments.RequestType.Capture) {


response =
createCaptureResponse((commercepayments.CaptureRequest)gatewayContext.getPaymentRequest())
;
} else if (requestType == commercepayments.RequestType.ReferencedRefund) {
response =
createRefundResponse((commercepayments.ReferencedRefundRequest)gatewayContext.getPaymentRequest());

}
return response;
} catch(SalesforceValidationException e) {
commercepayments.GatewayErrorResponse error = new
commercepayments.GatewayErrorResponse('400', e.getMessage());
return error;
}
}

IN THIS SECTION:
GatewayErrorResponse Constructors

401
Apex Reference Guide GatewayNotificationResponse Class

GatewayErrorResponse Constructors
The following are constructors for GatewayErrorResponse.

IN THIS SECTION:
GatewayErrorResponse(errorCode, errorMessage)
Constructor to create a GatewayErrorResponse object that accepts errorCode and errorMessage.

GatewayErrorResponse(errorCode, errorMessage)
Constructor to create a GatewayErrorResponse object that accepts errorCode and errorMessage.

Signature
global GatewayErrorResponse(String errorCode, String errorMessage)

Parameters
errorCode
Type: String
Should match with the HTTP status code to be returned to the user. Here are a few examples.
• If the status code is for a bad request, the errorCode should be 400.
• If the status code is for a forbidden request, errorCode should be 403.
• If errorCode isn’t a valid HTTP status code, a 500 internal server error is returned.

Note: errorCode must have a value, otherwise the platform throws an error.

errorMessage
Type: String
The message response to users following an error.

Note: errorMessage must have a value, otherwise the platform throws an error.

GatewayNotificationResponse Class
When the payment gateway sends a notification to the payments platform, the platform responds with a
GatewayNotificationResponse indicating whether the platform succeeded or failed at receiving the notification.

Namespace
CommercePayments on page 317

Usage
You must specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes
no arguments. For example:

402
Apex Reference Guide GatewayNotificationResponse Class

CommercePayments.GatewayNotificationResponse gnr = new


CommercePayments.GatewayNotificationResponse();
When an asynchronous payment gateway sends a notification, the gateway requires the platform to acknowledge that it has either
succeeded or failed in receiving the notification. Payment gateway adapters use this class to construct the acknowledgment response,
which gateways expect for a notification. GatewayNotificationResponse is the return type of the processNotification
method.

Example
commercepayments.GatewayNotificationResponse gnr = new
commercepayments.GatewayNotificationResponse();
if (saveResult.isSuccess()) {
system.debug('Notification accepted by platform');
} else {
system.debug('Errors in the result '+ Blob.valueOf(saveResult.getErrorMessage()));
}
gnr.setStatusCode(200);
gnr.setResponseBody(Blob.valueOf('[accepted]'));
return gnr;

IN THIS SECTION:
GatewayNotificationResponse Methods

GatewayNotificationResponse Methods
The following are methods for GatewayNotificationResponse.

IN THIS SECTION:
setResponseBody(responseBody)
Sets the body of the response to the gateway. Some gateways expect the payments platform to acknowledge the notification with
a response regardless of whether the notification was accepted.
setStatusCode(statusCode)
Sets the HTTP status code sent to the gateway as part of the payments platform’s response notification.

setResponseBody(responseBody)
Sets the body of the response to the gateway. Some gateways expect the payments platform to acknowledge the notification with a
response regardless of whether the notification was accepted.

Signature
global void setResponseBody(Blob responseBody)

Parameters
responseBody
Type: Blob

403
Apex Reference Guide GatewayNotificationResponse Class

Common response values include accepted for successfully receiving the response. For example:
commercepayments.GatewayNotificationResponse gnr = new
commercepayments.GatewayNotificationResponse();
if (saveResult.isSuccess()) {
system.debug('Notification accepted by platform');
} else {
system.debug('Errors in the result '+ Blob.valueOf(saveResult.getErrorMessage()));
}
gnr.setStatusCode(200);
gnr.setResponseBody(Blob.valueOf('[accepted]'));
return gnr;

Return Value
Type: void

setStatusCode(statusCode)
Sets the HTTP status code sent to the gateway as part of the payments platform’s response notification.

Signature
global void setStatusCode(Integer statusCode)

Parameters
statusCode
Type: Integer
The status code will vary based on the type of payments platform response. Users should configure their
GatewayNotificationResponse class to account for all values that their payments platform can possibly return. For
example:
commercepayments.GatewayNotificationResponse gnr = new
commercepayments.GatewayNotificationResponse();
if (saveResult.isSuccess()) {
system.debug('Notification accepted by platform');
} else {
system.debug('Errors in the result '+ Blob.valueOf(saveResult.getErrorMessage()));
}
gnr.setStatusCode(200);
gnr.setResponseBody(Blob.valueOf('[accepted]'));
return gnr;

Return Value
Type: void

404
Apex Reference Guide GatewayResponse Interface

GatewayResponse Interface
Generic payment gateway response interface. This class extends the CaptureResponse on page 380,
AbstractTransactionResponse on page 323, and AbstractResponse on page 320 classes and inherits all their properties.
It has no unique methods or parameters.

Namespace
CommercePayments on page 317

IN THIS SECTION:
GatewayResponse Example Implementation

GatewayResponse Example Implementation


This is an example implementation of the commercepayments.GatewayResponse interface.
/**
* Abstract function to build gateway response for a Transaction
* The input is the response from gateway
* It creates and returns GatewayResponse from the HttpResponse
*/
public abstract commercepayments.GatewayResponse buildResponse(HttpResponse response);

/**
* Function to process transaction requests
* Steps involved are:
* 1. Build HttpRequest with the input Request from gateway context
* 2. Send request and get the response from gateway
* 3. Parse the response from gateway and return GatewayResponse
*/
public commercepayments.GatewayResponse execute(){
HttpRequest req;
try{
//Building a new request
req = buildRequest();
} catch(PayeezeValidationException e) {
return getValidationExceptionError(e);
}
commercepayments.PaymentsHttp http = new commercepayments.PaymentsHttp();
HttpResponse res = null;
try{
//Sending the request
res = http.send(req);
} catch(CalloutException ce) {
return getCalloutExceptionError(ce);
}
try{
//Parsing the response from gateway
return buildResponse(res);
} catch(Exception e) {

405
Apex Reference Guide NotificationClient Class

return getParseExceptionError(e);
}
}

For additional context, review the complete Sample Gateway Adapter in the CommercePayments Gateway Reference Implementation.

NotificationClient Class
Communicates with the payment platform regarding the gateway’s notification.

Namespace
CommercePayments on page 317

Usage
Specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes no arguments.
For example:
CommercePayments.NotificationClient ntc = new CommercePayments.NotificationClient();
This class is used in asynchronous payment gateway adapters. The notification client contains API for communicating with the payments
platform regarding the gateway’s notification. When the gateway sends a notification, the gateway adapter invokes the record
method in NotificationClient to request that the platform updates notification details.

Example
The NotificationSaveResult class creates a saveResult object to store the result of the save request made to the payment
gateway.
commercepayments.NotificationSaveResult saveResult =
commercepayments.NotificationClient.record(notification);

IN THIS SECTION:
NotificationClient Methods

NotificationClient Methods
The following are methods for NotificationClient.

IN THIS SECTION:
record(notification)
Stores the results of a notification request.

record(notification)
Stores the results of a notification request.

406
Apex Reference Guide NotificationSaveResult Class

Signature
global static commercepayments.NotificationSaveResult
record(commercepayments.BaseNotification notification)

Parameters
notification
Type: BaseNotification on page 366

Return Value
Type: NotificationSaveResult on page 407

NotificationSaveResult Class
Contains the result of the payment platform’s attempt to record data from the gateway’s notification.

Namespace
CommercePayments on page 317

Usage
This class is used with asynchronous payments. It is the return type of the NotificiationClient.record operation and
contains the result of the payment platform’s attempt to save notification details.
The constructor of this class takes no arguments. For example:
CommercePayments.NotificationSaveResult nsr = new
CommercePayments.NotificationSaveResult();

Example
commercepayments.NotificationSaveResult saveResult =
commercepayments.NotificationClient.record(notification);

IN THIS SECTION:
NotificationSaveResult Methods

NotificationSaveResult Methods
The following are methods for NotificationSaveResult.

IN THIS SECTION:
getErrorMessage()
Gets the error message, if any, from the payment platform regarding its attempt to save the notification sent from the payment
gateway.

407
Apex Reference Guide NotificationStatus Enum

getStatusCode()
Gets the status code from the payment platform’s attempt to save the notification sent from the payment gateway.
isSuccess()
Gets the status of whether the payment platform successfully saved the notification sent from the payment gateway.

getErrorMessage()
Gets the error message, if any, from the payment platform regarding its attempt to save the notification sent from the payment gateway.

Signature
global String getErrorMessage()

Return Value
Type: String

getStatusCode()
Gets the status code from the payment platform’s attempt to save the notification sent from the payment gateway.

Signature
global Integer getStatusCode()

Return Value
Type: Integer

isSuccess()
Gets the status of whether the payment platform successfully saved the notification sent from the payment gateway.

Signature
global Boolean isSuccess()

Return Value
Type: Boolean

NotificationStatus Enum
Shows whether the payments platform successfully received the notification from the gateway.

Usage
When the gateway sends a notification for a payment request, the payments platform delegates the notification request to the gateway
adapter. First, the adapter evaluates the signature from the notification request. If the signature is valid, the adapter builds a notification

408
Apex Reference Guide PaymentGatewayAdapter Interface

object to store information about the notification. During this process, the adapter sets the NotificationStatus to Failed
or Success based on information from the notification request.

Enum Values
The following are the values of the commercepayments.NotificationStatus enum.

Value Description
Failed The payments platform couldn’t receive the notification due to an error.

Success The payments platform received the notification.

PaymentGatewayAdapter Interface
PaymentGatewayAdapters can implement this interface in order to process requests.

Namespace
CommercePayments on page 317

IN THIS SECTION:
PaymentGatewayAdapter Methods

PaymentGatewayAdapter Methods
The following are methods for PaymentGatewayAdapter.

IN THIS SECTION:
processRequest(var1)
The entry point for processing payment requests. Returns the response from the payment gateway.

processRequest(var1)
The entry point for processing payment requests. Returns the response from the payment gateway.

Signature
global commercepayments.GatewayResponse
processRequest(commercepayments.PaymentGatewayContext var1)

Parameters
var1
Type: commercepayments.PaymentGatewayContext
You can retrieve the request type and the request from the Context object.

409
Apex Reference Guide PaymentGatewayAsyncAdapter Interface

Return Value
Type: commercepayments.GatewayResponse
The response from the payment gateway.

PaymentGatewayAsyncAdapter Interface
Implement the interface to allow customers to process payments asynchronously.

Namespace
CommercePayments on page 317

Usage
Implementing an asynchronous adapter also requires the processNotification method from the GatewayNotificationResponse
on page 402 class.

Example
global with sharing class SampleAsyncAdapter
implements commercepayments.PaymentGatewayAsyncAdapter,
commercepayments.PaymentGatewayAdapter {

global SampleAsyncAdapter() {
}

global commercepayments.GatewayResponse processRequest(


commercepayments.paymentGatewayContext gatewayContext) {
}

global commercepayments.GatewayNotificationResponse processNotification(


commercepayments.PaymentGatewayNotificationContext gatewayNotificationContext) {
}
}

IN THIS SECTION:
PaymentGatewayAsyncAdapter Methods
PaymentGatewayAsyncAdapter Example Implementation

PaymentGatewayAsyncAdapter Methods
The following are methods for PaymentGatewayAsyncAdapter.

IN THIS SECTION:
processNotification(paymentGatewayNotificationContext)
Entry point for processing notifications from payment gateways.

410
Apex Reference Guide PaymentGatewayAsyncAdapter Interface

processNotification(paymentGatewayNotificationContext)
Entry point for processing notifications from payment gateways.

Signature
global commercepayments.GatewayNotificationResponse
processNotification(commercepayments.PaymentGatewayNotificationContext var1)

Parameters
paymentGatewayNotificationContext
Type: PaymentGatewayNotificationContext on page 415
The PaymentGatewayNotificationContext object wraps all the information related to a gateway notification.

Return Value
Type: GatewayNotificationResponse on page 402
When the payment gateway sends a notification to the payments platform, the platform responds with a
GatewayNotificationResponse indicating whether the platform succeeded or failed at receiving the notification.

PaymentGatewayAsyncAdapter Example Implementation


This is a sample implementation of the commercepayments.PaymentGatewayAsyncAdapter interface.
global with sharing class AdyenAdapter implements
commercepayments.PaymentGatewayAsyncAdapter, commercepayments.PaymentGatewayAdapter {
global AdyenAdapter() {}

global commercepayments.GatewayResponse
processRequest(commercepayments.paymentGatewayContext gatewayContext) {
}

global commercepayments.GatewayNotificationResponse
processNotification(commercepayments.PaymentGatewayNotificationContext
gatewayNotificationContext) {
}
}

commercepayments.RequestType requestType = gatewayContext.getPaymentRequestType();


if (requestType == commercepayments.RequestType.Capture) {
req.setEndpoint('/pal/servlet/Payment/v52/capture');
body =
buildCaptureRequest((commercepayments.CaptureRequest)gatewayContext.getPaymentRequest());
} else if (requestType == commercepayments.RequestType.ReferencedRefund) {
req.setEndpoint('/pal/servlet/Payment/v52/refund');
body =
buildRefundRequest((commercepayments.ReferencedRefundRequest)gatewayContext.getPaymentRequest());
}

req.setBody(body);
req.setMethod('POST');

411
Apex Reference Guide PaymentGatewayAsyncAdapter Interface

commercepayments.PaymentsHttp http = new commercepayments.PaymentsHttp();


HttpResponse res = null;
try {
res = http.send(req);
} catch(CalloutException ce) {
commercepayments.GatewayErrorResponse error = new
commercepayments.GatewayErrorResponse('500', ce.getMessage());
return error;
}

if ( requestType == commercepayments.RequestType.Capture) {
response = createCaptureResponse(res);
} else if ( requestType == commercepayments.RequestType.ReferencedRefund) {
response = createRefundResponse(res);
}
return response;

commercepayments.PaymentGatewayNotificationRequest notificationRequest =
gatewayNotificationContext.getPaymentGatewayNotificationRequest();
Blob request = notificationRequest.getRequestBody();
Map<String, Object> jsonReq = (Map<String,
Object>)JSON.deserializeUntyped(request.toString());
List<Object> notificationItems = (List<Object>)jsonReq.get('notificationItems');
Map<String, Object> notificationRequestItem =
(Map<String, Object>)((Map<String,
Object>)notificationItems[0]).get('NotificationRequestItem');
Boolean success = Boolean.valueOf(notificationRequestItem.get('success'));
String pspReference = (String)notificationRequestItem.get('pspReference');
String eventCode = (String)notificationRequestItem.get('eventCode');
Double amount = (Double)((Map<String,
Object>)notificationRequestItem.get('amount')).get('value');

commercepayments.NotificationStatus notificationStatus = null;


if (success) {
notificationStatus = commercepayments.NotificationStatus.Success;
} else {
notificationStatus = commercepayments.NotificationStatus.Failed;
}
commercepayments.BaseNotification notification = null;
if ('CAPTURE'.equals(eventCode)) {
notification = new commercepayments.CaptureNotification();
} else if ('REFUND'.equals(eventCode)) {
notification = new commercepayments.ReferencedRefundNotification();
}
notification.setStatus(notificationStatus);
notification.setGatewayReferenceNumber(pspReference);
notification.setAmount(amount);

commercepayments.NotificationSaveResult saveResult =
commercepayments.NotificationClient.record(notification);

commercepayments.GatewayNotificationResponse gnr = new


commercepayments.GatewayNotificationResponse();
if (saveResult.isSuccess()) {

412
Apex Reference Guide PaymentGatewayContext Class

system.debug('Notification accepted by platform');


} else {
system.debug('Errors in the result '+ Blob.valueOf(saveResult.getErrorMessage()));
}
gnr.setStatusCode(200);
gnr.setResponseBody(Blob.valueOf('[accepted]'));
return gnr;

PaymentGatewayContext Class
Wraps the information related to a payment request.

Namespace
CommercePayments on page 317

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.PaymentGatewayContext pgc = new
CommercePayments.PaymentGatewayContext();

Example
global commercepayments.GatewayResponse processRequest(commercepayments.PaymentGatewayContext
gatewayContext) {
commercepayments.RequestType requestType = gatewayContext.getPaymentRequestType();
if (requestType == commercepayments.RequestType.Capture) {
commercepayments.CaptureRequest captureRequest = (commercepayments.CaptureRequest)
gatewayContext.getPaymentRequest();
}
}

IN THIS SECTION:
PaymentGatewayContext Constructors
PaymentGatewayContext Methods

PaymentGatewayContext Constructors
The following are constructors for PaymentGatewayContext.

IN THIS SECTION:
PaymentGatewayContext(request, requestType)
Constructor to enable instance creation. This constructor is intended for test usage and throws an exception if used outside of the
Apex test context.

413
Apex Reference Guide PaymentGatewayContext Class

PaymentGatewayContext(request, requestType)
Constructor to enable instance creation. This constructor is intended for test usage and throws an exception if used outside of the Apex
test context.

Signature
global PaymentGatewayContext(commercepayments.PaymentGatewayRequest request, String
requestType)

Parameters
request
Type: commercepayments.PaymentGatewayRequest
Raw payload. Sensitive attributes are masked to ensure PCI compliance.
requestType
Type: commercepayments.RequestType Enum
Defines the type of request made to the gateway

PaymentGatewayContext Methods
The following are methods for PaymentGatewayContext.

IN THIS SECTION:
getPaymentRequest()
Returns the payment request object.
getPaymentRequestType()
Returns the payment request type.

getPaymentRequest()
Returns the payment request object.

Signature
global commercepayments.PaymentGatewayRequest getPaymentRequest()

Return Value
Type: PaymentGatewayRequest

getPaymentRequestType()
Returns the payment request type.

Signature
global String getPaymentRequestType()

414
Apex Reference Guide PaymentGatewayNotificationContext Class

Return Value
Type: String

PaymentGatewayNotificationContext Class
Wraps the information related to a gateway notification.

Namespace
CommercePayments on page 317

Usage
This class is used with asynchronous payments. It wraps all of the information related to a notification from the payment gateway. The
payments platform provides its context to the payment gateway adapters.
The constructor of this class takes no arguments. For example:
CommercePayments.PaymentGatewayNotificationContext pgnc = new
CommercePayments.PaymentGatewayNotificationContext();

Example
global commercepayments.GatewayNotificationResponse
processNotification(commercepayments.PaymentGatewayNotificationContext
gatewayNotificationContext) {
commercepayments.PaymentGatewayNotificationRequest notificationRequest =
gatewayNotificationContext.getPaymentGatewayNotificationRequest();
}

IN THIS SECTION:
PaymentGatewayNotificationContext Methods

PaymentGatewayNotificationContext Methods
The following are methods for PaymentGatewayNotificationContext.

IN THIS SECTION:
getPaymentGatewayNotificationRequest()
Returns the payment gateway’s notification request.

getPaymentGatewayNotificationRequest()
Returns the payment gateway’s notification request.

415
Apex Reference Guide PaymentGatewayNotificationRequest Class

Signature
global commercepayments.PaymentGatewayNotificationRequest
getPaymentGatewayNotificationRequest()

Return Value
Type: PaymentGatewayNotificationRequest on page 416

PaymentGatewayNotificationRequest Class
Contains the notification request data from the gateway.

Namespace
CommercePayments on page 317

Usage
When the payment gateway sends a notification for a payment request, the payments platform sends the notification request to the
gateway adapter. If the notification payload contains an eventCode of CAPTURE, the adapter constructs a
CaptureNotification. If the notification payload contains an eventCode of REFUND, the adapter constructs a
ReferencedRefundNotification. If the notification payload contains eventCode of AUTHORISATION, the adapter
constructs a GatewayNotificationResponse.
You can obtain a notification request from PaymentGatewayNotificationContext on page 415 by invoking its
getPaymentGatewayNotificationRequest method.

Example
global commercepayments.GatewayNotificationResponse
processNotification(commercepayments.PaymentGatewayNotificationContext
gatewayNotificationContext) {
commercepayments.PaymentGatewayNotificationRequest notificationRequest =
gatewayNotificationContext.getPaymentGatewayNotificationRequest();
}

IN THIS SECTION:
PaymentGatewayNotificationRequest Properties
PaymentGatewayNotificationRequest Methods

PaymentGatewayNotificationRequest Properties
The following are properties for PaymentGatewayNotificationRequest.

IN THIS SECTION:
requestBody
Body of the notification request sent by the payment gateway.

416
Apex Reference Guide PaymentMethodDetailsResponse Class

requestBody
Body of the notification request sent by the payment gateway.

Signature
global Blob requestBody {get; set;}

Property Value
Type: Blob

PaymentGatewayNotificationRequest Methods
The following are methods for PaymentGatewayNotificationRequest.

IN THIS SECTION:
getHeaders()
Gets HTTP headers from the notification request sent by the payment gateway.
getRequestBody()
Stores the notification request body information from the payment gateway’s notification request.

getHeaders()
Gets HTTP headers from the notification request sent by the payment gateway.

Signature
global Map<String,String> getHeaders()

Return Value
Type: Map<String,String>

getRequestBody()
Stores the notification request body information from the payment gateway’s notification request.

Signature
global Blob getRequestBody()

Return Value
Type: Blob

PaymentMethodDetailsResponse Class
This class contains the details about the payment method.

417
Apex Reference Guide PaymentMethodDetailsResponse Class

Namespace
CommercePayments

Example

commercepayments.AlternativePaymentMethodResponse alternativePaymentMethodResponse = new


commercepayments.AlternativePaymentMethodResponse();
alternativePaymentMethodResponse.setEmail('alternativePaymentMethod');
alternativePaymentMethodResponse.setEmail('[email protected]');
alternativePaymentMethodResponse.setGatewayToken('NMoPoIOnTZSaRaWcV7gUUXe');
alternativePaymentMethodResponse.setGatewayTokenDetails('gateway token details');
commercepayments.PaymentMethodDetailsResponse response = new
commercepayments.PaymentMethodDetailsResponse();
response.setAlternativePaymentMethod(alternativePaymentMethodResponse);

IN THIS SECTION:
PaymentMethodDetailsResponse Methods

PaymentMethodDetailsResponse Methods
The following are methods for PaymentMethodDetailsResponse.

IN THIS SECTION:
setAlternativePaymentMethod(alternativePaymentMethod)
Sets the alternative payment method details.
setCardPaymentMethod(cardPaymentMethod)
Sets the details about the card payment method.

setAlternativePaymentMethod(alternativePaymentMethod)
Sets the alternative payment method details.

Signature
public void setAlternativePaymentMethod(commercepayments.AlternativePaymentMethodResponse
alternativePaymentMethod)

Parameters
alternativePaymentMethod
Type: CommercePayments.AlternativePaymentMethodResponse
Details of the alternative payment method.

Return Value
Type: void

418
Apex Reference Guide PaymentMethodTokenizationRequest Class

setCardPaymentMethod(cardPaymentMethod)
Sets the details about the card payment method.

Signature
public void setCardPaymentMethod(commercepayments.CardPaymentMethodResponse
cardPaymentMethod)

Parameters
cardPaymentMethod
Type: CommercePayments.CardPaymentMethodResponse
Details about the card payment method.

Return Value
Type: void

PaymentMethodTokenizationRequest Class
Stores data about a request to tokenize a card payment method. The tokenization process occurs in the payment gateway. This process
replaces sensitive customer data, such as a card number or CVV, with unique identification symbols. The symbols are used while the
data is handled by Salesforce, the payment gateway, and the customer bank, allowing Salesforce to store the token without storing
sensitive customer data.

Namespace
CommercePayments on page 317

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.PaymentMethodTokenizationRequest pmtr = new
CommercePayments.PaymentMethodTokenizationRequest();
This class holds all the required details about the tokenize request. Gateway adapters read the information in this class while constructing
a tokenization JSON request, which is sent to the payment gateway.

Example
The following code is used within your payment gateway adapter Apex class.
Use the GatewayResponse class's processRequest method to build responses based on the request type that it receives
from an instance of PaymentGatewayContext on page 413. If the request type is Tokenize, GatewayResponse on
page 405 calls the createTokenizeResponse method and passes an instance of the

419
Apex Reference Guide PaymentMethodTokenizationRequest Class

PaymentMethodTokenizationRequest class. The passed PaymentMethodTokenizationRequest object contains


the address and cardPaymentMethod information that the payment gateway needs to manage the tokenization process. For example:
global commercepayments.GatewayResponse processRequest(commercepayments.paymentGatewayContext
gatewayContext) {
commercepayments.RequestType requestType = gatewayContext.getPaymentRequestType();

commercepayments.GatewayResponse response;
try
{
if (requestType == commercepayments.RequestType.Tokenize) {
response =
createTokenizeResponse((commercepayments.PaymentMethodTokenizationRequest)gatewayContext.getPaymentRequest());

}
//Add other else if statements for different request types as needed.
return response;
}
catch(SalesforceValidationException e)
{
commercepayments.GatewayErrorResponse error = new
commercepayments.GatewayErrorResponse('400', e.getMessage());
return error;
}
}

Configure the createTokenizeResponse method to accept an instance of PaymentMethodTokenizationRequest.


Then, build an instance of PaymentMethodTokenizationResponse based on the values received from the payment gateway.
public commercepayments.GatewayResponse
createTokenizeResponse(commercepayments.PaymentMethodTokenizationRequest tokenizeRequest)
{
commercepayments.PaymentMethodTokenizationResponse tokenizeResponse = new
commercepayments.PaymentMethodTokenizationResponse();
tokenizeResponse.setGatewayTokenEncrypted(encryptedValue);
tokenizeResponse.setGatewayTokenDetails(tokenDetails);
tokenizeResponse.setGatewayAvsCode(avsCode);
tokenizeResponse.setGatewayMessage(gatewayMessage);
tokenizeResponse.setGatewayResultCode(resultcode);
tokenizeResponse.setGatewayResultCodeDescription(resultCodeDescription);
tokenizeResponse.setSalesforceResultCodeInfo(resultCodeInfo);
tokenizeResponse.setGatewayDate(system.now());
return tokenizeResponse;
}

The tokenizeResponse contains the results of the gateway's tokenization process, and if successful, the tokenized value.

IN THIS SECTION:
PaymentMethodTokenizationRequest Constructors
PaymentMethodTokenizationRequest Properties
PaymentMethodTokenizationRequest Methods

420
Apex Reference Guide PaymentMethodTokenizationRequest Class

PaymentMethodTokenizationRequest Constructors
The following are constructors for PaymentMethodTokenizationRequest.

IN THIS SECTION:
PaymentMethodTokenizationRequest(paymentGatewayId)
Payment gateway ID constructor used with paymentMethodTokenizationRequest. This constructor is intended for test
usage and throws an exception if used outside of the Apex test context.
PaymentMethodTokenizationRequest()
The following are constructors for PaymentMethodTokenizationRequest.

PaymentMethodTokenizationRequest(paymentGatewayId)
Payment gateway ID constructor used with paymentMethodTokenizationRequest. This constructor is intended for test
usage and throws an exception if used outside of the Apex test context.

Signature
global PaymentMethodTokenizationRequest(String paymentGatewayId)

Parameters
paymentGatewayId
Type: String
The payment method’s payment gateway ID that will be tokenized.

PaymentMethodTokenizationRequest()
The following are constructors for PaymentMethodTokenizationRequest.

Signature
global PaymentMethodTokenizationRequest()

PaymentMethodTokenizationRequest Properties
The following are properties for PaymentMethodTokenizationRequest.

IN THIS SECTION:
address
The card payment method address to be tokenized.
cardPaymentMethod
The card payment method containing data to be tokenized.

address
The card payment method address to be tokenized.

421
Apex Reference Guide PaymentMethodTokenizationRequest Class

Signature
global commercepayments.AddressRequest address {get; set;}

Property Value
Type: AddressRequest on page 327

cardPaymentMethod
The card payment method containing data to be tokenized.

Signature
global commercepayments.CardPaymentMethodRequest cardPaymentMethod {get; set;}

Property Value
Type: CardPaymentMethodRequest on page 385

PaymentMethodTokenizationRequest Methods
The following are methods for PaymentMethodTokenizationRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type PaymentMethodTokenizationRequest by determining the equality of external
objects in a list. This method is dynamic and is based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type PaymentMethodTokenizationRequest by determining the uniquness of the
external object records in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type PaymentMethodTokenizationRequest by determining the equality of external objects
in a list. This method is dynamic and is based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

422
Apex Reference Guide PaymentMethodTokenizationResponse Class

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type PaymentMethodTokenizationRequest by determining the uniquness of the external
object records in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

PaymentMethodTokenizationResponse Class
Gateway response sent by payment gateway adapters for the payment method tokenization request. The response includes the payment
method’s token ID value.

Namespace
CommercePayments on page 317

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.PaymentMethodTokenizationResponse pmtr = new
CommercePayments.PaymentMethodTokenizationResponse();
After the payment gateway processes a tokenization request, the fields of PaymentMethodTokenizationResponse receive
and store information from the gateway's response. The gateway's response shows whether the tokenization request was successful,
the token value, and any additional messages or information about the tokenization process. You can then pass an instance of
PaymentMethodTokenizationResponse to an authorization response or a sale response. This class is mapped to a response
class in the Java layer.

423
Apex Reference Guide PaymentMethodTokenizationResponse Class

Example
This constructor builds a new instance of the PaymentMethodTokenizationResponse class.
commercepayments.PaymentMethodTokenizationResponse tokenizeResponse = new
commercepayments.PaymentMethodTokenizationResponse();

PaymentMethodTokenizationResponse contains only setter methods. Each setter accepts a value from the payment gateway
and use it to set an attribute of PaymentMethodTokenizationResponse.
The most important method in PaymentMethodTokenizationResponse is setGatewayTokenEncrypted, which
uses Salesforce encryption to set an encrypted token value for a payment method. The setGatewayTokenEncrypted method
is available in Salesforce API v52.0 and later. We recommend using it to ensure your tokenized payment method values are encrypted
and secure. While the setGatewayToken method (available in earlier API versions) also returns a payment method token, the
tokenized value isn't encrypted.
If the instantiated class already has a gateway token, setGatewayTokenEncrypted throws an error.
/** @description Method to set Gateway token to persist in Encrypted Text */
global void setGatewayTokenEncrypted(String gatewayTokenEncrypted) {
if (gatewayTokenSet) {
throwTokenError();
}
this.delegate.setGatewayTokenEncrypted(gatewayTokenEncrypted);
gatewayTokenEncryptedSet = true;
}

A typical instantiation of PaymentMethodTokenizationResponse sets the encrypted gateway token alongside the other
tokenization response values sent by the gateway.
public commercepayments.GatewayResponse
createTokenizeResponse(commercepayments.PaymentMethodTokenizationRequest tokenizeRequest)
{
commercepayments.PaymentMethodTokenizationResponse tokenizeResponse = new
commercepayments.PaymentMethodTokenizationResponse();
tokenizeResponse.setGatewayTokenEncrypted(gatewayTokenEncrypted);
tokenizeResponse.setGatewayTokenDetails(gatewayTokenDetails);
tokenizeResponse.setGatewayAvsCode(gatewayAvsCode);
tokenizeResponse.setGatewayMessage(gatewayMessage);
tokenizeResponse.setGatewayResultCode(gatewayResultCode);
tokenizeResponse.setGatewayResultCodeDescription(gatewayResultCodeDescription);
tokenizeResponse.setSalesforceResultCodeInfo(SUCCESS_SALESFORCE_RESULT_CODE_INFO);

tokenizeResponse.setGatewayDate(system.now());
return tokenizeResponse;
}

After you've built a PaymentMethodTokenizationResponse object and set the encrypted gateway token, pass the object to the
setPaymentMethodTokenizationResponse method of an authorization response or a sale response.
Authorization Response
public commercepayments.GatewayResponse
createAuthResponse(commercepayments.AuthorizationRequest authRequest) {
commercepayments.AuthorizationResponse authResponse = new
commercepayments.AuthorizationResponse();
commercepayments.PaymentMethodTokenizationResponse

424
Apex Reference Guide PaymentMethodTokenizationResponse Class

paymentMethodTokenizationResponse = new
commercepayments.PaymentMethodTokenizationResponse();
if(authRequest.amount!=null )
{
authResponse.setAmount(authRequest.amount);
}
else
{
throw new SalesforceValidationException('Required Field Missing : Amount');

authResponse.setGatewayResultCode('00');
authResponse.setGatewayResultCodeDescription('Transaction Normal');
authResponse.setGatewayAuthCode('SF'+getRandomNumber(6));
authResponse.setGatewayReferenceNumber(getRandomNumber(10));
authResponse.setSalesforceResultCodeInfo(SUCCESS_SALESFORCE_RESULT_CODE_INFO);

authResponse.setGatewayDate(system.now());

paymentMethodTokenizationResponse.setGatewayTokenEncrypted(gatewayTokenEncrypted);

authResponse.setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse);
return authResponse;
}

Sale Response
public commercepayments.GatewayResponse
createSaleResponse(commercepayments.SaleRequest saleRequest) {
commercepayments.SaleResponse saleResponse = new commercepayments.SaleResponse();

commercepayments.PaymentMethodTokenizationResponse
paymentMethodTokenizationResponse = new
commercepayments.PaymentMethodTokenizationResponse();
if(saleRequest.amount!=null )
{
saleResponse.setAmount(saleRequest.amount);
}
else
{
throw new SalesforceValidationException('Required Field Missing : Amount');

system.debug('Response - success');
saleResponse.setGatewayDate(system.now());
saleResponse.setGatewayResultCode('00');
saleResponse.setGatewayResultCodeDescription('Transaction Normal');
saleResponse.setGatewayReferenceNumber('SF'+getRandomNumber(6));
saleResponse.setSalesforceResultCodeInfo(SUCCESS_SALESFORCE_RESULT_CODE_INFO);

paymentMethodTokenizationResponse.setGatewayTokenEncrypted(gatewayTokenEncrypted);

425
Apex Reference Guide PaymentMethodTokenizationResponse Class

saleResponse.setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse);
return saleResponse;
}

IN THIS SECTION:
PaymentMethodTokenizationResponse Methods

PaymentMethodTokenizationResponse Methods
The following are methods for PaymentMethodTokenizationResponse.

IN THIS SECTION:
setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.
setGatewayDate(gatewayDate)
Sets the date that the tokenization occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the tokenization request. Maximum length of 255 characters.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code may be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setGatewayToken(gatewayToken)
Sets the gateway token value that the gateway returned.
setGatewayTokenDetails(gatewayTokenDetails)
Sets any additional information that the gateway returned about the payment token.
setGatewayTokenEncrypted(gatewayTokenEncrypted)
Sets the value of the gatewayTokenEncrypted field on a CardPaymentMethod or DigitalWallet object.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String

426
Apex Reference Guide PaymentMethodTokenizationResponse Class

Used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment
gateway.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the tokenization occurred. Some gateways don’t send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the tokenization request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code may be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

427
Apex Reference Guide PaymentMethodTokenizationResponse Class

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be used to map a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Provides additional information about the result code and why the gateway returned the specific code. Descriptions will vary between
different gateways.

Return Value
Type: void

setGatewayToken(gatewayToken)
Sets the gateway token value that the gateway returned.

Signature
global void setGatewayToken(String gatewayToken)

Parameters
gatewayToken
Type: String
The gateway token that the payment gateway sends following a tokenization request.
For the CardPaymentMethod and DigitalWallet objects, use the gatewyTokenEncrypted parameter, which encrypts the
token value.

Return Value
Type: void

428
Apex Reference Guide PaymentMethodTokenizationResponse Class

setGatewayTokenDetails(gatewayTokenDetails)
Sets any additional information that the gateway returned about the payment token.

Signature
global void setGatewayTokenDetails(String gatewayTokenDetails)

Parameters
gatewayTokenDetails
Type: String

Return Value
Type: void

setGatewayTokenEncrypted(gatewayTokenEncrypted)
Sets the value of the gatewayTokenEncrypted field on a CardPaymentMethod or DigitalWallet object.

Signature
global void setGatewayTokenEncrypted(String gatewayTokenEncrypted)

Parameters
gatewayTokenEncrypted
Type: String
The gateway token that the payment gateway sends following a tokenization request. Salesforce Payments uses Salesforce encryption
to encrypt the token value.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce uses
the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: SalesforceResultCodeInfo on page 465

429
Apex Reference Guide PaymentsHttp Class

Description of the Salesforce result code value.

Return Value
Type: void

PaymentsHttp Class
Makes an HTTP request to start the interaction with the payment gateway.

Namespace
CommercePayments on page 317

Usage
You must specify the CommercePayments namespace when creating an instance of this class. The constructor of this class takes
no arguments. For example:
CommercePayments.PaymentsHttp payhttp = new CommercePayments.PaymentsHttp();

IN THIS SECTION:
PaymentsHttp Methods
PaymentsHttp Constructors

PaymentsHttp Methods
The following are methods for PaymentsHttp. All methods are instance methods.

IN THIS SECTION:
send(Request)
Sends an HttpRequest and returns the response.

send(Request)
Sends an HttpRequest and returns the response.

Signature
global HttpResponse send(HttpRequest request)

Parameters
request
Type: System.HttpRequest

430
Apex Reference Guide PostAuthApiPaymentMethodRequest Class

Return Value
Type: System.HttpResponse

PaymentsHttp Constructors
The following are constructors for PaymentsHttp.

IN THIS SECTION:
PaymentsHttp()
Initiates an HTTP request and response.

PaymentsHttp()
Initiates an HTTP request and response.

Signature
global PaymentsHttp()

PostAuthApiPaymentMethodRequest Class
Sends information about a payment method to a gateway adapter during a postauthorization service call.

Namespace
CommercePayments

Usage
Contains information about the payment method that is used for a postauthorization request. It contains all available payment methods
as fields, but populates only one field for each request. The gateway adapter uses this class when constructing a postauthorization
request. An object of this class is available through the paymentMethod field on the PostAuthorizationRequest Class
object.

IN THIS SECTION:
PostAuthApiPaymentMethodRequest Constructors
Lists the constructors for the PostAuthApiPaymentMethodRequest.
PostAuthApiPaymentMethodRequest Properties
Lists the properties for PostAuthApiPaymentMethodRequest.

PostAuthApiPaymentMethodRequest Constructors
Lists the constructors for the PostAuthApiPaymentMethodRequest.
The following are constructors for PostAuthApiPaymentMethodRequest.

431
Apex Reference Guide PostAuthApiPaymentMethodRequest Class

IN THIS SECTION:
PostAuthApiPaymentMethodRequest(cardPaymentMethodRequest)
Constructs a sample cardPaymentMethodRequest. This constructor is intended for test usage and throws an exception if
used outside of the Apex test context.
PostAuthApiPaymentMethodRequest(AlternativePaymentMethodRequest)
Constructs a sample alternativePaymentMethodRequest. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.
PostAuthApiPaymentMethodRequest()
Constructor for PostAuthApiPaymentMethodRequest.

PostAuthApiPaymentMethodRequest(cardPaymentMethodRequest)
Constructs a sample cardPaymentMethodRequest. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

Signature
global PostAuthApiPaymentMethodRequest(commercepayments.CardPaymentMethodRequest
cardPaymentMethodRequest)

Parameters
cardPaymentMethodRequest
Type: commercepayments.CardPaymentMethodRequest on page 385
Contains information about the card payment method. Used to send information to a gateway adapter during a service call.

PostAuthApiPaymentMethodRequest(AlternativePaymentMethodRequest)
Constructs a sample alternativePaymentMethodRequest. This constructor is intended for test usage and throws an exception
if used outside of the Apex test context.

Signature
global
PostAuthApiPaymentMethodRequest(commercepayments.AlternativePaymentMethodRequestPaymentMethodRequest)

Parameters
alternativePaymentMethodRequest
Type: commercepayments.AlternativePaymentMethodRequest on page 385
Contains information about the alternative payment method. Used to send information to a gateway adapter during a service call.

PostAuthApiPaymentMethodRequest()
Constructor for PostAuthApiPaymentMethodRequest.

432
Apex Reference Guide PostAuthorizationRequest Class

Signature
global PostAuthApiPaymentMethodRequest()

PostAuthApiPaymentMethodRequest Properties
Lists the properties for PostAuthApiPaymentMethodRequest.
The following are properties for PostAuthApiPaymentMethodRequest.

IN THIS SECTION:
cardPaymentMethod
The card payment method object used in a postauthorizaiton payment method request.
alternativePaymentMethod
The alternative payment method object used in a postauthorizaiton payment method request.

cardPaymentMethod
The card payment method object used in a postauthorizaiton payment method request.

Signature
global commercepayments.CardPaymentMethodRequest cardPaymentMethod {get; set;}

Property Value
Type: commercepayments.CardPaymentMethodRequest on page 385

alternativePaymentMethod
The alternative payment method object used in a postauthorizaiton payment method request.

Signature
global commercepayments.AlternativePaymentMethodRequest PaymentMethod {get; set;}

Property Value
Type: commercepayments.alternativePaymentMethodRequest

PostAuthorizationRequest Class
Sends information about a postauthorization request to a gateway adapter during a service call.

Namespace
CommercePayments

433
Apex Reference Guide PostAuthorizationRequest Class

Usage
This class extends BaseRequest and contains information about a transaction postauthorization request. The gateway adapter reads
fields from this class to validate the client-side transaction with the payment gateway. An object of this class is available by calling
getPaymentRequest() in the PaymentGatewayContext Class).

((commercepayments.PostAuthorizationRequest)gatewayContext.getPaymentRequest());

IN THIS SECTION:
PostAuthorizationRequest Constructors
Lists the constructors for postauthorization requests.
PostAuthorizationRequest Properties
Lists properties for a postauthorizaiton request.

PostAuthorizationRequest Constructors
Lists the constructors for postauthorization requests.
The following are constructors for PostAuthorizationRequest.

IN THIS SECTION:
PostAuthorizationRequest(amount)
Constructor for building the amount in a postauthorization request. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.

PostAuthorizationRequest(amount)
Constructor for building the amount in a postauthorization request. This constructor is intended for test usage and throws an exception
if used outside of the Apex test context.

Signature
global PostAuthorizationRequest(Double amount)

Parameters
amount
Type: Double
The amount of the authorization.

PostAuthorizationRequest Properties
Lists properties for a postauthorizaiton request.
The following are properties for a PostAuthorizationRequest.

434
Apex Reference Guide PostAuthorizationRequest Class

IN THIS SECTION:
accountId
The customer account that is settled when the postauthorization is performed.
amount
The total amount of the postauthorization request.
comments
Comments about the postauthorization. Users can enter comments to provide additional information.
currencyIsoCode
The ISO currency code for the postauthorization request.
paymentMethod
The payment method used to process the postauthorization request.

accountId
The customer account that is settled when the postauthorization is performed.

Signature
global String accountId {get; set;}

Property Value
Type: String

amount
The total amount of the postauthorization request.

Signature
global Double amount {get; set;}

Property Value
Type: Double

comments
Comments about the postauthorization. Users can enter comments to provide additional information.

Signature
global String comments {get; set;}

Property Value
Type: String

435
Apex Reference Guide PostAuthorizationResponse Class

currencyIsoCode
The ISO currency code for the postauthorization request.

Signature
global String currencyIsoCode {get; set;}

Property Value
Type: String

paymentMethod
The payment method used to process the postauthorization request.

Signature
global PostAuthApiPaymentMethodRequest paymentMethod {get; set;}

Property Value
Type: AuthApiPaymentMethodRequest on page 340

PostAuthorizationResponse Class
Response sent by the payment gateway adapter for a postauthorization service.

Namespace
CommercePayments

Usage
This class extends AbstractTransactionResponse. The constructor of this class takes no arguments. For example:
CommercePayments.PostAuthorizationResponse authr = new
CommercePayments.PostAuthorizationResponse();
Contains information about the payment gateway’s response following an authorization transaction. The gateway adapter uses the
payment gateway’s response to populate the PostAuthorizationResponse fields. The payments platform uses the information
from this class to settle the transaction.

IN THIS SECTION:
PostAuthorizationResponse Methods
Lists the methods for the PostAuthorizationResponse.

PostAuthorizationResponse Methods
Lists the methods for the PostAuthorizationResponse.

436
Apex Reference Guide PostAuthorizationResponse Class

The following are methods for PostAuthorizationResponse.

IN THIS SECTION:
setPaymentMethodDetailsResponse(PaymentMethodDetailsResponsepaymentMethodDetails)
Sets details from the gateway about the authorized payment method.
setCardPaymentMethodResponse(CardPaymentMethodResponsecardPaymentMethod)
Sets details from the gateway about the authorized card payment method.
setAlternativePaymentMethodResponse(AlternativePaymentMethodResponsealternativePaymentMethod)
Sets details from the gateway about the authorized alternative payment method.
setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse)
Sets information from the gateway about the tokenized payment method.
setGatewayAuthCode(gatewayAuthCode)
Sets the authorization code that the gateway returned. Maximum length of 64 characters.
setAuthorizationExpirationDate(authExpDate)
Sets the expiration date of the authorization request.
setAsync(async)
Sets whether the payment capture or authorization is asynchronous (True) or synchronous (False). If True, then the payment
or payment authorization record created has a status of Pending.

setPaymentMethodDetailsResponse(PaymentMethodDetailsResponsepaymentMethodDetails)
Sets details from the gateway about the authorized payment method.

Signature
global void setPaymentMethodDetailsResponse(commercepayments.PaymentMethodDetailsResponse
paymentMethodDetailsResponse)

Parameters
paymentMethodDetailsResponse
Gateway response sent by payment gateway adapters for the payment method details request.

Return Value
Type: void

setCardPaymentMethodResponse(CardPaymentMethodResponsecardPaymentMethod)
Sets details from the gateway about the authorized card payment method.

Signature
global void setCardPaymentMethodResponse(commercepaymentsCardPaymentMethodResponse
cardpaymentMethodResponse)

437
Apex Reference Guide PostAuthorizationResponse Class

Parameters
cardPaymentMethodResponse
Gateway response sent by payment gateway adapter for the card payment method request.

Return Value
Type: void

setAlternativePaymentMethodResponse(AlternativePaymentMethodResponsealternativePaymentMethod)
Sets details from the gateway about the authorized alternative payment method.

Signature
global void
setAlternativePaymentMethodResponse(commercepayments.AlternativePaymentMethodResponse
paymentMethodResponse)

Parameters
alternativePaymentMethodResponse
Gateway response sent by payment gateway adapter for the alternative payment method request.

Return Value
Type: void

setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse)
Sets information from the gateway about the tokenized payment method.

Signature
global void
setPaymentMethodTokenizationResponse(commercepayments.PaymentMethodTokenizationResponse
paymentMethodTokenizationResponse)

Parameters
paymentMethodTokenizationResponse
PaymentMethodTokenizationResponse on page 423
Gateway response sent by payment gateway adapters for the payment method tokenization request.

Return Value
Type: void

setGatewayAuthCode(gatewayAuthCode)
Sets the authorization code that the gateway returned. Maximum length of 64 characters.

438
Apex Reference Guide PostAuthorizationResponse Class

Signature
global void setGatewayAuthCode(String gatewayAuthCode)

Parameters
gatewayAuthCode
Type: String
The authorization code returned by the gateway.

Return Value
Type: void

setAuthorizationExpirationDate(authExpDate)
Sets the expiration date of the authorization request.

Signature
global void setAuthorizationExpirationDate(Datetime authExpDate)

Parameters
authExpDate
Type: Datetime

Return Value
Type: void

setAsync(async)
Sets whether the payment capture or authorization is asynchronous (True) or synchronous (False). If True, then the payment or
payment authorization record created has a status of Pending.

Signature
global void setAsync(Boolean async)

Parameters
async
Type: Boolean

Return Value
Type: void

439
Apex Reference Guide ReferencedRefundNotification Class

ReferencedRefundNotification Class
When a payment gateway sends a notification for a refund transaction, the payment gateway adapter creates the
ReferencedRefundNotification object to store information about notification.

Namespace
CommercePayments on page 317

Usage
This class is used with asynchronous payments. When a payment gateway sends a notification for a refund transcation, the gateway
adapter creates an object of type ReferencedRefundNotification to populate the respective values.
The constructor of this class takes no arguments. For example:
CommercePayments.ReferencedRefundNotification rrn = new
CommercePayments.ReferencedRefundNotification();

Example
commercepayments.NotificationStatus notificationStatus = null;
if (success) {
notificationStatus = commercepayments.NotificationStatus.Success;
} else {
notificationStatus = commercepayments.NotificationStatus.Failed;
}
commercepayments.BaseNotification notification = null;
if ('CAPTURE'.equals(eventCode)) {
notification = new commercepayments.CaptureNotification();
} else if ('REFUND'.equals(eventCode)) {
notification = new commercepayments.ReferencedRefundNotification();
}

IN THIS SECTION:
ReferencedRefundNotification Methods

ReferencedRefundNotification Methods
The following are methods for ReferencedRefundNotification.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount. Can be positive, negative, or zero.
setGatewayDate(gatewayDate)
Sets the date that communication for the refund notification occurred with the payment gateway.
setGatewayMessage(gatewayMessage)
Sets information or messages that the gateway returned.

440
Apex Reference Guide ReferencedRefundNotification Class

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.
setGatewayResultCode(gatewayResultCode)
Sets the payment gateway’s result code.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets the payment gateway’s result code description.
setId(id)
Sets the ID of a notification sent by the payment gateway.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets Salesforce result code information.
setStatus(status)
Sets the notification status value on the notification object.

setAmount(amount)
Sets the transaction amount. Can be positive, negative, or zero.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount to be debited or captured.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that communication for the refund notification occurred with the payment gateway.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime
The date that communication happened with the gateway.

441
Apex Reference Guide ReferencedRefundNotification Class

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets information or messages that the gateway returned.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String
Provides information about the gateway communication.

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String

442
Apex Reference Guide ReferencedRefundNotification Class

Unique transaction ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets the payment gateway’s result code.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
The gateway result code. You must map this to a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets the payment gateway’s result code description.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the gateway result code. Provides additional context about the result code .

Return Value
Type: void

setId(id)
Sets the ID of a notification sent by the payment gateway.

Signature
global void setId(String id)

443
Apex Reference Guide ReferencedRefundRequest

Parameters
id
Type: String

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets Salesforce result code information.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: SalesforceResultCodeInfo on page 465
Description of the Salesforce result code value.

Return Value
Type: void

setStatus(status)
Sets the notification status value on the notification object.

Signature
global void setStatus(commercepayments.NotificationStatus status)

Parameters
status
Type: NotificationStatus on page 408
Indicates whether the payments platform successfully received the notification from the payment gateway.

Return Value
Type: void

ReferencedRefundRequest
Access information about the referenced refund requests. Extends the RefundRequest class.

444
Apex Reference Guide ReferencedRefundRequest

Namespace
CommercePayments on page 317

Example
global commercepayments.GatewayResponse processRequest(commercepayments.PaymentGatewayContext
gatewayContext) {
commercepayments.RequestType requestType = gatewayContext.getPaymentRequestType();
if (requestType == commercepayments.RequestType.ReferencedRefund) {
commercepayments.*ReferencedRefundRequest* refundRequest =
(commercepayments.*ReferencedRefundRequest*) gatewayContext.getPaymentRequest();
}
}

IN THIS SECTION:
ReferencedRefundRequest Constructors
ReferencedRefundRequest Properties
ReferencedRefundRequest Methods

ReferencedRefundRequest Constructors
The following are constructors for ReferencedRefundRequest.

IN THIS SECTION:
ReferencedRefundRequest(amount, paymentId)
This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

ReferencedRefundRequest(amount, paymentId)
This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Parameters
amount
Type: Double
The amount to be debited or captured.
paymentId
Type: String
The payment record.

ReferencedRefundRequest Properties
The following are properties for ReferencedRefundRequest.

445
Apex Reference Guide ReferencedRefundResponse Class

IN THIS SECTION:
PaymentId
References a payment object.
accountId
References an account.
amount
References an amount.

PaymentId
References a payment object.

Property Value
Type: String

accountId
References an account.

Property Value
Type: String

amount
References an amount.

Property Value
Type: Double

ReferencedRefundRequest Methods
The following are methods for ReferencedRefundRequest.

ReferencedRefundResponse Class
The payment gateway adapter sends this response for the ReferencedRefund request type.

Namespace
CommercePayments on page 317

Usage
The constructor of this class takes no arguments. For example:

446
Apex Reference Guide ReferencedRefundResponse Class

CommercePayments.ReferencedRefundResponse refr = new


CommercePayments.ReferencedRefundResponse();

IN THIS SECTION:
ReferencedRefundResponse Methods

ReferencedRefundResponse Methods
The following are methods for ReferencedRefundResponse.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount. The value must be a postive number.
setGatewayAvsCode(gatewayAvsCode)
Sets the payment gateway’s address verification system (AVS) code.
setGatewayDate(gatewayDate)
Sets the payment gateway’s date.
setGatewayMessage(gatewayMessage)
Sets information or messages that the gateway returned.
setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.
setGatewayResultCode(gatewayResultCode)
Sets the payment gateway’s result code.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets the payment gateway’s result code description.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Set the Salesforce result code info.

setAmount(amount)
Sets the transaction amount. The value must be a postive number.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount to be debited or captured.

447
Apex Reference Guide ReferencedRefundResponse Class

Return Value
Type: void

setGatewayAvsCode(gatewayAvsCode)
Sets the payment gateway’s address verification system (AVS) code.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String
Code sent by gateways that use an address verification system.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the payment gateway’s date.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime
Date and time of the gateway communication.

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets information or messages that the gateway returned.

Signature
global void setGatewayMessage(String gatewayMessage)

448
Apex Reference Guide ReferencedRefundResponse Class

Parameters
gatewayMessage
Type: String
Information or error messages returned by the gateway.

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets the payment gateway’s reference details.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String
Information about the gateway communication.

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the payment gateway’s reference number.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String
Unique transaction ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets the payment gateway’s result code.

449
Apex Reference Guide ReferencedRefundResponse Class

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
The gateway result code. Must be mapped to a Salesforce result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets the payment gateway’s result code description.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the GatewayResultCode. Provides more information about the result code returned by the gateway.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Set the Salesforce result code info.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: commercepayments.SalesforceResultCodeInfo on page 465
Describes the Salesforce result code value.

Return Value
Type: void

450
Apex Reference Guide RefundRequest Class

RefundRequest Class
Sends data related to a refund to the payment gateway adapter.

Namespace
CommercePayments on page 451

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.RefundRequest rrq = new CommercePayments.RefundRequest();

Example
commercepayments.ReferencedRefundRequest refundRequest = new
commercepayments.ReferencedRefundRequest(80, pmt.id);

IN THIS SECTION:
RefundRequest Methods

RefundRequest Methods
The following are methods for RefundRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type RefundRequest by determining the equality of external objects in a list. This method is
dynamic and is based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type RefundRequest by determining the uniqueness of the external object records in a list.

equals(obj)
Maintains the integrity of lists of type RefundRequest by determining the equality of external objects in a list. This method is
dynamic and is based on the equals method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object

451
Apex Reference Guide RequestType Enum

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type RefundRequest by determining the uniqueness of the external object records in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

RequestType Enum
Defines the type of payment transaction request made to the payment gateway.

Enum Values
The following are the values of the commercepayments.RequestType enum.

Value Description
Authorize Payment authorization request

PostAuth Post authorization request

Capture Payment capture request

AuthorizationReversal Authorization Reversal request

ReferencedRefund Payment refund request

Sale Sale request


commercepayments.RequestType,
Sale

Tokenize Payment tokenize request


commercepayments.RequestType,
Tokenize

SaleApiPaymentMethodRequest Class
Sends data related to a card payment method to a gateway adapter during a sale service call.

452
Apex Reference Guide SaleApiPaymentMethodRequest Class

Namespace
CommercePayments on page 317

Usage
This class holds information about a payment method that was used for a Sale request. SaleApiPaymentMethodRequest
contains all the possible payment methods as fields, but only one value is populated for a given request. Gateway adapters use this class
when constructing a sale request. The object of this class is obtained through the paymentMethod field on the SaleRequest
object.

Example: This code sample retrieves the SaleApiPaymentMethodRequest object from the SaleRequest class.
commercepayments.SaleApiPaymentMethodRequest paymentMethod = saleRequest.paymentMethod;

IN THIS SECTION:
SaleApiPaymentMethodRequest Constructors
SaleApiPaymentMethodRequest Properties
SaleApiPaymentMethodRequest Methods

SaleApiPaymentMethodRequest Constructors
The following are constructors for SaleApiPaymentMethodRequest.

IN THIS SECTION:
SaleApiPaymentMethodRequest(cardPaymentMethodRequest)
Sends data related to a card payment method to a gateway adapter during a sale service call.
SaleApiPaymentMethodRequest()
Constructor for building a sale payment method request. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

SaleApiPaymentMethodRequest(cardPaymentMethodRequest)
Sends data related to a card payment method to a gateway adapter during a sale service call.

Signature
global SaleApiPaymentMethodRequest(commercepayments.CardPaymentMethodRequest
cardPaymentMethodRequest)

Parameters
cardPaymentMethodRequest
Type: CardPaymentMethodRequest on page 385

453
Apex Reference Guide SaleApiPaymentMethodRequest Class

SaleApiPaymentMethodRequest()
Constructor for building a sale payment method request. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

Signature
global SaleApiPaymentMethodRequest()

SaleApiPaymentMethodRequest Properties
The following are properties for SaleApiPaymentMethodRequest.

IN THIS SECTION:
cardPaymentMethod
Contains details of the card used in a payment method.

cardPaymentMethod
Contains details of the card used in a payment method.

Signature
global commercepayments.CardPaymentMethodRequest cardPaymentMethod {get; set;}

Property Value
Type: CardPaymentMethodRequest on page 385

SaleApiPaymentMethodRequest Methods
The following are methods for SaleApiPaymentMethodRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type SaleApiPaymentMethodRequest by determining the equality of external objects in
a list. This method is dynamic and is based on the equals method in Java.
hashCode()
Maintains the integrity of lists of type SaleApiPaymentMethodRequest by determining the uniqueness of the external
object records in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type SaleApiPaymentMethodRequest by determining the equality of external objects in a
list. This method is dynamic and is based on the equals method in Java.

454
Apex Reference Guide SaleRequest Class

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type SaleApiPaymentMethodRequest by determining the uniqueness of the external object
records in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

SaleRequest Class
Stores information about a sales request.

Namespace
CommercePayments on page 317

455
Apex Reference Guide SaleRequest Class

Usage
This class holds all the required details about a sale request. Gateway adapters read the fields of this class object while constructing a
sale JSON request thatis sent to the payment gateway. The object of this class is made available through
commercepayments.paymentGatewayContext by calling getPaymentRequest().

Example
This code sample retrieves the SaleRequest object from the PaymentGatewayContext class.
commercepayments.SaleRequest =
(commercepayments.SaleRequest)gatewayContext.getPaymentRequest()

IN THIS SECTION:
SaleRequest Constructors
SaleRequest Properties
SaleRequest Methods

SaleRequest Constructors
The following are constructors for SaleRequest.

IN THIS SECTION:
SaleRequest(amount)
Constructor for defining an amount for the sale request. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

SaleRequest(amount)
Constructor for defining an amount for the sale request. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

Signature
global SaleRequest(Double amount)

Parameters
amount
Type: Double
Amount of the sale request.

SaleRequest Properties
The following are properties for SaleRequest.

456
Apex Reference Guide SaleRequest Class

IN THIS SECTION:
accountId
Customer account ID for the sale request.
amount
Amount of the sale request. Can be positive only.
comments
Additional information about the sale request.
currencyIsoCode
Currency code for the sale request.
paymentMethod
Payment method used in the sale request.

accountId
Customer account ID for the sale request.

Signature
global String accountId {get; set;}

Property Value
Type: String

amount
Amount of the sale request. Can be positive only.

Signature
global Double amount {get; set;}

Property Value
Type: Double

comments
Additional information about the sale request.

Signature
global String comments {get; set;}

Property Value
Type: String

457
Apex Reference Guide SaleRequest Class

currencyIsoCode
Currency code for the sale request.

Signature
global String currencyIsoCode {get; set;}

Property Value
Type: String

paymentMethod
Payment method used in the sale request.

Signature
global commercepayments.SaleApiPaymentMethodRequest paymentMethod {get; set;}

Property Value
Type: SaleApiPaymentMethodRequest on page 452

SaleRequest Methods
The following are methods for SaleRequest.

IN THIS SECTION:
equals(obj)
Compares this object with the specified object and returns true if both objects are equal; otherwise, returns false.
hashCode()
Maintains the integrity of lists of type SaleRequest by determining the uniqueness of the external object records in a list.
toString()
Converts a date to a string.

equals(obj)
Compares this object with the specified object and returns true if both objects are equal; otherwise, returns false.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object

458
Apex Reference Guide SaleResponse Class

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type SaleRequest by determining the uniqueness of the external object records in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

SaleResponse Class
Response sent by payment gateway adapters for a sales service.

Namespace
CommercePayments on page 317

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.SaleResponse slr CommercePayments.SaleResponse();
This class contains details about a customer card that was used as a payment method for Authorization, Sale, or Tokenization request.
The gateway adapter reads the fields of this class while constructing a transaction JSON request, which it then sends to the payment
gateway. The object of this class is made available by the cardPaymentMethod field in SaleApiPaymentMethodRequest
on page 452 and AuthApiPaymentMethodRequest on page 340.

459
Apex Reference Guide SaleResponse Class

Example
This code sample builds a SaleResponse object.
commercepayments.SaleResponse saleResponse = new commercepayments.SaleResponse();
saleResponse.setGatewayReferenceDetails("refDetailString");
saleResponse.setGatewayResultCode("res_code");
saleResponse.setGatewayResultCodeDescription("");
saleResponse.setGatewayReferenceNumber("");
saleResponse.setSalesforceResultCodeInfo(getSalesforceResultCodeInfo(commercepayments.SalesforceResultCode.SUCCESS.name()));

IN THIS SECTION:
SaleResponse Methods

SaleResponse Methods
The following are methods for SaleResponse.

IN THIS SECTION:
setAmount(amount)
Sets the transaction amount. Must be a non-negative value.
setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.
setGatewayDate(gatewayDate)
Sets the date that the sale occurred. Some gateways don’t send this value.
setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the sale request. Maximum length of 255 characters.
setGatewayReferenceDetails(gatewayReferenceDetails)
Sets additional data that you can use for subsequent sales. You can use any data that isn’t normalized in financial entities. This field
has a maximum length of 1000 characters and can store data as JSON or XML.
setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.
setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code may be mapped to a Salesforce-specific result code. Maximum length of 64 characters.
setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.
setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse)
Sets information from the gateway about the tokenized payment method.
setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

460
Apex Reference Guide SaleResponse Class

setAmount(amount)
Sets the transaction amount. Must be a non-negative value.

Signature
global void setAmount(Double amount)

Parameters
amount
Type: Double
The amount of the transaction.

Return Value
Type: void

setGatewayAvsCode(gatewayAvsCode)
Sets the AVS (address verification system) result code information that the gateway returned. Maximum length of 64 characters.

Signature
global void setGatewayAvsCode(String gatewayAvsCode)

Parameters
gatewayAvsCode
Type: String
Used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment
gateway.

Return Value
Type: void

setGatewayDate(gatewayDate)
Sets the date that the sale occurred. Some gateways don’t send this value.

Signature
global void setGatewayDate(Datetime gatewayDate)

Parameters
gatewayDate
Type: Datetime

461
Apex Reference Guide SaleResponse Class

Return Value
Type: void

setGatewayMessage(gatewayMessage)
Sets error messages that the gateway returned for the sale request. Maximum length of 255 characters.

Signature
global void setGatewayMessage(String gatewayMessage)

Parameters
gatewayMessage
Type: String

Return Value
Type: void

setGatewayReferenceDetails(gatewayReferenceDetails)
Sets additional data that you can use for subsequent sales. You can use any data that isn’t normalized in financial entities. This field has
a maximum length of 1000 characters and can store data as JSON or XML.

Signature
global void setGatewayReferenceDetails(String gatewayReferenceDetails)

Parameters
gatewayReferenceDetails
Type: String

Return Value
Type: void

setGatewayReferenceNumber(gatewayReferenceNumber)
Sets the unique gateway reference number for the transaction that the gateway returned. Maximum length of 255 characters.

Signature
global void setGatewayReferenceNumber(String gatewayReferenceNumber)

Parameters
gatewayReferenceNumber
Type: String

462
Apex Reference Guide SaleResponse Class

Unique authorization ID created by the payment gateway.

Return Value
Type: void

setGatewayResultCode(gatewayResultCode)
Sets a gateway-specific result code. The code may be mapped to a Salesforce-specific result code. Maximum length of 64 characters.

Signature
global void setGatewayResultCode(String gatewayResultCode)

Parameters
gatewayResultCode
Type: String
Gateway-specific result code. Must be used to map a Salesforce-specific result code.

Return Value
Type: void

setGatewayResultCodeDescription(gatewayResultCodeDescription)
Sets a description of the gateway-specific result code that a payment gateway returned. Maximum length of 1000 characters.

Signature
global void setGatewayResultCodeDescription(String gatewayResultCodeDescription)

Parameters
gatewayResultCodeDescription
Type: String
Description of the gateway’s result code. Use this field to learn more about why the gateway returned a certain result code.

Return Value
Type: void

setPaymentMethodTokenizationResponse(paymentMethodTokenizationResponse)
Sets information from the gateway about the tokenized payment method.

463
Apex Reference Guide SalesforceResultCode Enum

Signature
global void
setPaymentMethodTokenizationResponse(commercepayments.PaymentMethodTokenizationResponse
paymentMethodTokenizationResponse)

Parameters
paymentMethodTokenizationResponse
Type: PaymentMethodTokenizationResponse on page 423
Gateway response sent by payment gateway adapters for the payment method tokenization request. The response includes the
payment method’s token ID value.

Return Value
Type: void

setSalesforceResultCodeInfo(salesforceResultCodeInfo)
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce uses
the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Signature
global void setSalesforceResultCodeInfo(commercepayments.SalesforceResultCodeInfo
salesforceResultCodeInfo)

Parameters
salesforceResultCodeInfo
Type: SalesforceResultCodeInfo on page 465
Sets the Salesforce-specific result code information. Payment gateways have many response codes for payment calls. Salesforce
uses the result code information to map payment gateway codes to a predefined set of standard Salesforce result codes.

Return Value
Type: void

SalesforceResultCode Enum
Defines the gateway call status values in Salesforce based on the call status values that the payment gateway returned.

Usage
Payment gateways can return many different responses. Salesforce maps these responses into one of seven possible Salesforce response
values.

464
Apex Reference Guide SalesforceResultCodeInfo

Enum Values
The following are the values of the commercepayments.SalesforceResultCode enum.

Value Description
Decline The gateway call failed, but it may still work if you try again. For example, the
customer had insufficient funds or briefly lost their connection to the internet. This
is also known as a “soft decline.”

Indeterminate The gateway didn't respond to the call and the user has to check the transaction
request’s status. Indeterminate responses often occur following server timeouts,
system failure, or any action that interrupts the gateway’s ability to process the
payment.

PermanentFail The customer’s bank recognized the payment account as closed, terminated, or
fraudulent. The gateway won’t further calls from the payment method associate
with the transaction. After a permanent fail response, the transaction changes its
gateway status to Permanent Fail.

RequiresReview The gateway call initially failed, but the payment method may still work after further
evaluation. This response often happens when the customer bank requires more
information about the payment request. In this case, the bank provides an
authorization code manually when the payment manager calls the processor.

Success The gateway processed the transaction successfully.

SystemError Salesforce ended the payment request call before receiving a gateway response.
System error responses often occur due to gateway server errors, invalid customer
credentials, or anytime the request times out before receiving a gateway response.
The failure occurs before the request reaches the gateway, so there’s no risk of an
unaccounted payment remaining in the gateway. You can continue with the
transaction by manually creating a payment.

ValidationError The gateway received incorrect customer payment information, such as misspelled
credit card names or a CVV with missing numbers.

SalesforceResultCodeInfo
Stores Salesforce result code information from payment gateway adapters.

Namespace
CommercePayments on page 317

Usage
The constructor of this class takes no arguments. For example:
CommercePayments.SalesforceResultCodeInfo srci = new
CommercePayments.SalesforceResultCodeInfo();
Gateways can return the transaction result as either CustomMetadata or SalesforceResultCode.

465
Apex Reference Guide CommerceTax Namespace

IN THIS SECTION:
SalesforceResultCodeInfo Constructors

SalesforceResultCodeInfo Constructors
The following are constructors for SalesforceResultCodeInfo.

IN THIS SECTION:
SalesforceResultCodeInfo(customMetadataTypeInfo)
Constructor for providing the customMetadataTypeInfo for the result of the transaction.
SalesforceResultCodeInfo(salesforceResultCode)
Constructor that provides the salesforceResultCode for the transaction result.

SalesforceResultCodeInfo(customMetadataTypeInfo)
Constructor for providing the customMetadataTypeInfo for the result of the transaction.

Signature
global SalesforceResultCodeInfo(commercepayments.CustomMetadataTypeInfo
customMetadataTypeInfo)

Parameters
customMetadataTypeInfo
Type: CustomMetadataTypeInfo on page 400
Information about the metadata type.

SalesforceResultCodeInfo(salesforceResultCode)
Constructor that provides the salesforceResultCode for the transaction result.

Signature
global SalesforceResultCodeInfo(commercepayments.SalesforceResultCode
salesforceResultCode)

Parameters
salesforceResultCode
Type: SalesforceResultCode on page 464
The enum value for the result code.

CommerceTax Namespace
Manage the communication between Salesforce and an external tax engine.

466
Apex Reference Guide CommerceTax Namespace

The CommerceTax namespace includes these classes.

IN THIS SECTION:
AbstractTransactionResponse Class
Abstract class that contains methods for setting tax fields based on the external tax provider's response. Response classes that extend
AbstractTransactionResponse inherit these methods.
AddressesResponse Class
Sets the tax address fields based on a response from the external tax engine. Contains setter methods for the Ship From, Ship To,
and Sold To addresses.
AddressResponse Class
Contains a location code sent from the external tax engine.
AmountDetailsResponse Class
Sets tax amount fields based on a response from the external tax engine.
CalculateTaxRequest Class
Represents a request to an external tax engine to calculate tax. Extends the TaxTransactionRequest class and is the top-level request
class.
CalculateTaxResponse Class
Sets the values of the tax transaction following a response from the external tax engine. Extends the AbstractTransactionResponse
class and is the top-level response class.
CalculateTaxType Enum
Shows whether a tax calculation request is for estimated or actual tax.
ErrorResponse Class
Use to respond with an error after receiving errors from the PaymentGatewayAdapter methods of the CommercePayments namespace,
such as request-forbidden responses, custom validation errors, or expired API tokens.
HeaderTaxAddressesRequest Class
Captures the address values that are applicable for the quote or order transaction.
ImpositionResponse Class
Stores details of tax impositions from the external tax engine.
JurisdictionResponse Class
Stores details from the external tax engine about the tax jurisdiction used in the tax calculation process. A tax jurisdiction represents
a government entity that collects tax.
LineItemResponse Class
Response class that stores details of a list of one or more line items on which the tax engine has calculated tax.
LineTaxAddressesRequest Class
Stores details of the addresses applied per line item in a tax calculation request.
RequestType Enum
Shows the type of tax request made to the tax engine.
ResultCode Enum
Code that represents the results of a tax request made to the tax engine.
RuleDetailsResponse Class
Contains details about the tax rules used for tax calculation.

467
Apex Reference Guide AbstractTransactionResponse Class

TaxAddressesRequest Class
Contains methods to get and set tax address values.
TaxAddressRequest Class
Contains address details used for tax calculation.
TaxApiException Class
Contains details about any exceptions during the tax calculation process. Extends the ApexBaseException class.
TaxCustomerDetailsRequest Class
Contains customer details used in tax calculation.
TaxDetailsResponse Class
Stores details of the tax values that an external tax engine calculates in response to a tax calculation request.
TaxEngineAdapter Interface
Retrieves information from the tax engine and evaluates the information to define tax details.
TaxEngineContext Class
Wrapper class that stores details about the type of a tax calculation request.
TaxLineItemRequest Class
Contains line item details of a tax request.
TaxSellerDetailsRequest Class
Contains tax code details used in the tax calculation request.
TaxTransactionRequest Class
Abstract class for storing customer details used in tax calculation and estimation requests.
TaxTransactionStatus Enum
Shows whether the tax transaction has been committed or uncommitted.
TaxTransactionType Enum
Shows whether the tax transaction is for a credit or debit transaction.

AbstractTransactionResponse Class
Abstract class that contains methods for setting tax fields based on the external tax provider's response. Response classes that extend
AbstractTransactionResponse inherit these methods.

Namespace
CommerceTax

IN THIS SECTION:
AbstractTransactionResponse Methods
Learn more about the methods for AbstractTransactionResponse class.

AbstractTransactionResponse Methods
Learn more about the methods for AbstractTransactionResponse class.
The AbstractTransactionResponse class includes these methods.

468
Apex Reference Guide AbstractTransactionResponse Class

IN THIS SECTION:
setAddresses(addresses)
Uses an instance of AddressesResponse to set the values of tax address fields.
setAmountDetails(amountDetails)
Uses an instance of AmountDetailsResponse to set tax amount fields such as exemption amount and tax amount.
setCurrencyIsoCode(currencyIsoCode)
Sets the currencyIsoCode field.
setDescription(dscptn)
Sets the Description field.
setDocumentCode(documentCode)
Sets the DocumentCode field. Document codes are often used to reference tax documents that the external tax engine uses in the
tax calculation process. Document code acts as a unique link to chain-related transactions, such as amendment or refunds.
setEffectiveDate(effectiveDate)
Sets the EffectiveDate field. Effective Date fields are optional fields that store the date that a transaction takes effect. We provide
these fields only for recordkeeping purposes – for example, if you must report an effective date to an external general ledger system.
Salesforce doesn't use them to calculate any tax or payment values.
setLineItems(lineItems)
Uses an instance of the LineItemResponse class to set a list of line items. Each line item represents an item sent to an external
tax engine for tax calculation.
setReferenceDocumentCode(referenceDocumentCode)
Sets the ReferenceDocumentCode field. Use this field to store the code of an additional document used in the tax calculation process.
For example, use this field in case of a refund for a previously taxed purchase.
setReferenceEntityId(referenceEntityId)
Sets the ID of a reference entity. In Commerce Tax, a reference entity represents a record related to the items sent to the external
tax engine for tax calculation. For example, if you sent order items for tax calculation, you could define the parent order as the
reference entity.
setTaxTransactionId(taxTrxnId)
Sets the TaxTransactionId field using the ID of a tax transaction record. In Commerce Tax, a tax transaction record stores information
about a specific tax calculation process.
setTransactionDate(transactionDate)
Sets the TransactionDate field.

setAddresses(addresses)
Uses an instance of AddressesResponse to set the values of tax address fields.

Signature
global void setAddresses(commercetax.AddressesResponse addresses)

Parameters
addresses
Type: AddressesResponse

469
Apex Reference Guide AbstractTransactionResponse Class

Class that contains methods to set the Ship To, Ship From, and Sold To address information.

Return Value
Type: void

setAmountDetails(amountDetails)
Uses an instance of AmountDetailsResponse to set tax amount fields such as exemption amount and tax amount.

Signature
global void setAmountDetails(commercetax.AmountDetailsResponse amountDetails)

Parameters
amountDetails
Type: AmountDetailsResponse
Class that contains methods to set the tax exemption amount, tax amount, total amount, and total amount with tax.

Return Value
Type: void

setCurrencyIsoCode(currencyIsoCode)
Sets the currencyIsoCode field.

Signature
global void setCurrencyIsoCode(String currencyIsoCode)

Parameters
currencyIsoCode
Type: String
Three-letter ISO 4217 currency code associated with a tax object.

Return Value
Type: void

setDescription(dscptn)
Sets the Description field.

Signature
global void setDescription(String dscptn)

470
Apex Reference Guide AbstractTransactionResponse Class

Parameters
dscptn
Type: String
Optional field for providing additional information about a record.

Return Value
Type: void

setDocumentCode(documentCode)
Sets the DocumentCode field. Document codes are often used to reference tax documents that the external tax engine uses in the tax
calculation process. Document code acts as a unique link to chain-related transactions, such as amendment or refunds.

Signature
global void setDocumentCode(String documentCode)

Parameters
documentCode
Type: String
Code for a tax document used in the tax calculation process.

Return Value
Type: void

setEffectiveDate(effectiveDate)
Sets the EffectiveDate field. Effective Date fields are optional fields that store the date that a transaction takes effect. We provide these
fields only for recordkeeping purposes – for example, if you must report an effective date to an external general ledger system. Salesforce
doesn't use them to calculate any tax or payment values.

Signature
global void setEffectiveDate(Datetime effectiveDate)

Parameters
effectiveDate
Type: Datetime
Optional field that stores the date that a transaction takes effect.

Return Value
Type: void

471
Apex Reference Guide AbstractTransactionResponse Class

setLineItems(lineItems)
Uses an instance of the LineItemResponse class to set a list of line items. Each line item represents an item sent to an external
tax engine for tax calculation.

Signature
global void setLineItems(List<commercetax.LineItemResponse> lineItems)

Parameters
lineItems
Type: List<LineItemResponse>
A list of line items sent to an external tax engine for tax calculation.

Return Value
Type: void

setReferenceDocumentCode(referenceDocumentCode)
Sets the ReferenceDocumentCode field. Use this field to store the code of an additional document used in the tax calculation process.
For example, use this field in case of a refund for a previously taxed purchase.

Signature
global void setReferenceDocumentCode(String referenceDocumentCode)

Parameters
referenceDocumentCode
Type: String
The code for a document used in the tax calculation process.

Return Value
Type: void

setReferenceEntityId(referenceEntityId)
Sets the ID of a reference entity. In Commerce Tax, a reference entity represents a record related to the items sent to the external tax
engine for tax calculation. For example, if you sent order items for tax calculation, you could define the parent order as the reference
entity.

Signature
global void setReferenceEntityId(String referenceEntityId)

472
Apex Reference Guide AbstractTransactionResponse Class

Parameters
referenceEntityId
Type: String
ID of a record related to the items sent for tax calculation.

Return Value
Type: void

setTaxTransactionId(taxTrxnId)
Sets the TaxTransactionId field using the ID of a tax transaction record. In Commerce Tax, a tax transaction record stores information
about a specific tax calculation process.

Signature
global void setTaxTransactionId(String taxTrxnId)

Parameters
taxTrxnId
Type: String
The ID of a tax transaction record in Commerce Tax.

Return Value
Type: void

setTransactionDate(transactionDate)
Sets the TransactionDate field.

Signature
global void setTransactionDate(Datetime transactionDate)

Parameters
transactionDate
Type: Datetime
Date that a tax transaction occurred.

Return Value
Type: void

473
Apex Reference Guide AddressesResponse Class

AddressesResponse Class
Sets the tax address fields based on a response from the external tax engine. Contains setter methods for the Ship From, Ship To, and
Sold To addresses.

Namespace
CommerceTax

Usage
Because AddressesResponse contains multiple addresses, we recommend using multiple instances of AddressResponse
to set unique values for each address.

Example
This code sample represents a portion of the code used in a mock tax adapter. In this example, you create three AddressResponse
classes, set their location codes, and pass them to the Ship To, Ship From, and Sold To setter methods in
AddressesResponse. In an actual implementation, your AddressResponse classes already have a location code based on
the response from the external tax engine.
commercetax.AddressesResponse addressesRes = new commercetax.AddressesResponse();

//AddressResponse containing ShipTo information


commercetax.AddressResponse shipToAddress = new commercetax.AddressResponse();
shipToAddress.setLocationCode('1234567');

//AddressResponse containing ShipFrom information


commercetax.AddressResponse shipFromAddress = new commercetax.AddressResponse();
shipFromAddress.setLocationCode('84720385');

//AddressResponse containing Sold To information


commercetax.AddressResponse soldToAddress = new commercetax.AddressResponse();
soldToAddress.setLocationCode('92381749');

//set values of addressesRes


addressesRes.setShipFrom(shipFromAddress);
addressesRes.setShipTo(shipToAddress);
addressesRes.setSoldTo(soldToAddress);

IN THIS SECTION:
AddressesResponse Methods
Learn more about the methods for AddressesResponse class.

AddressesResponse Methods
Learn more about the methods for AddressesResponse class.
The AddressesResponse class includes these methods.

474
Apex Reference Guide AddressesResponse Class

IN THIS SECTION:
setShipFrom(shipFrom)
Sets the value of a ShipFrom address field.
setShipTo(shipTo)
Sets the value of a ShipTo address field.
setSoldTo(soldTo)
Sets the value of a SoldTo address field.

setShipFrom(shipFrom)
Sets the value of a ShipFrom address field.

Signature
global void setShipFrom(commercetax.AddressResponse shipFrom)

Parameters
shipFrom
Type: AddressResponse
A single address. Use this generic address parameter to store any type of address, such as Ship From, Ship To, and Sold To details.
Users set the specific address in an AddressResponse instance and then pass that instance to the AddressesResponse’s
setShipTo(), setShipFrom(), and setSoldTo() methods as needed.

Return Value
Type: void

setShipTo(shipTo)
Sets the value of a ShipTo address field.

Signature
global void setShipTo(commercetax.AddressResponse shipTo)

Parameters
shipTo
Type: AddressResponse
Stores a single address. This is a generic address parameter and can be used to store any type of address, such as Ship From, Ship
To, and Sold To details. Users set the specific address in an AddressResponse instance and then pass that instance to the
AddressesResponse’s setShipTo(), setShipFrom(), and setSoldTo() methods as needed.

Return Value
Type: void

475
Apex Reference Guide AddressResponse Class

setSoldTo(soldTo)
Sets the value of a SoldTo address field.

Signature
global void setSoldTo(commercetax.AddressResponse soldTo)

Parameters
soldTo
Type: AddressResponse
Stores a single address. This is a generic address parameter and can be used to store any type of address, such as Ship From, Ship
To, Sold To details. Users set the specific address in an AddressResponse instance and then pass that instance to the
AddressesResponse’s setShipTo(), setShipFrom(), and setSoldTo() methods as needed.

Return Value
Type: void

AddressResponse Class
Contains a location code sent from the external tax engine.

Namespace
CommerceTax

Usage
Use the AddressResponse class to set unique values for each address.
commercetax.AddressesResponse addressesRes = new commercetax.AddressesResponse();

//AddressResponse containing ShipTo information


commercetax.AddressResponse shipToAddress = new commercetax.AddressResponse();
shipToAddress.setLocationCode('1234567');

//AddressResponse containing ShipFrom information


commercetax.AddressResponse shipFromAddress = new commercetax.AddressResponse();
shipFromAddress.setLocationCode('84720385');

//AddressResponse containing Sold To information


commercetax.AddressResponse soldToAddress = new commercetax.AddressResponse();
soldToAddress.setLocationCode('92381749');

//set values of addressesRes


addressesRes.setShipFrom(shipFromAddress);
addressesRes.setShipTo(shipToAddress);
addressesRes.setSoldTo(soldToAddress);

476
Apex Reference Guide AmountDetailsResponse Class

IN THIS SECTION:
AddressResponse Methods
Learn more about the available methods with the AddressResponse class.

AddressResponse Methods
Learn more about the available methods with the AddressResponse class.
The AddressResponse class includes these methods.

IN THIS SECTION:
setLocationCode(locationCode)
Sets the value of a LocationCode field.

setLocationCode(locationCode)
Sets the value of a LocationCode field.

Signature
global void setLocationCode(String locationCode)

Parameters
locationCode
Type: String
A code that contains address information. This value can be passed to a method that sets the value of an address field.

Return Value
Type: void

AmountDetailsResponse Class
Sets tax amount fields based on a response from the external tax engine.

Namespace
CommerceTax

Example
In this example, an instance of AmountDetailsResponse class in a mock adapter calculates several tax amount fields. The
totalTax and totalAmount parameters were defined in an instance of LineItemResponse class. The adapter then assigns
the instance to lineItemResponse.
commercetax.AmountDetailsResponse amountResponse = new commercetax.AmountDetailsResponse();
amountResponse.setTotalAmountWithTax(totalTax+totalAmount);

477
Apex Reference Guide AmountDetailsResponse Class

amountResponse.setExemptAmount(0);
amountResponse.setTotalAmount(totalAmount);
amountResponse.setTaxAmount(totalTax);
lineItemResponse.setAmountDetails(amountResponse);

IN THIS SECTION:
AmountDetailsResponse Methods
Learn more about the methods available from the AmountDetailsResponse class.

AmountDetailsResponse Methods
Learn more about the methods available from the AmountDetailsResponse class.
The following are methods for AmountDetailsResponse.

IN THIS SECTION:
setExemptAmount(exemptAmount)
Sets the value of the ExemptAmount field.
setTaxAmount(taxAmount)
Sets the value of the TaxAmount field.
setTotalAmount(totalAmount)
Sets the value of the TotalAmount field.
setTotalAmountWithTax(totalAmtWithTax)
Sets the value of the TotalAmountWithTax field.

setExemptAmount(exemptAmount)
Sets the value of the ExemptAmount field.

Signature
global void setExemptAmount(Double exemptAmount)

Parameters
exemptAmount
Type: Double
The amount of a line item's total amount that's exempt from tax calculation.

Return Value
Type: void

setTaxAmount(taxAmount)
Sets the value of the TaxAmount field.

478
Apex Reference Guide AmountDetailsResponse Class

Signature
global void setTaxAmount(Double taxAmount)

Parameters
taxAmount
Type: Double
The calculated amount of tax for a line item.

Return Value
Type: void

setTotalAmount(totalAmount)
Sets the value of the TotalAmount field.

Signature
global void setTotalAmount(Double totalAmount)

Parameters
totalAmount
Type: Double
The total amount of a line item, excluding tax.

Return Value
Type: void

setTotalAmountWithTax(totalAmtWithTax)
Sets the value of the TotalAmountWithTax field.

Signature
global void setTotalAmountWithTax(Double totalAmtWithTax)

Parameters
totalAmtWithTax
Type: Double
The total amount of a line item combined with the calculated tax for that line item.

Return Value
Type: void

479
Apex Reference Guide CalculateTaxRequest Class

CalculateTaxRequest Class
Represents a request to an external tax engine to calculate tax. Extends the TaxTransactionRequest class and is the top-level request
class.

Namespace
CommerceTax

Example
See TaxEngineAdapter Example Implementation for more details on how to access information from the CalculateTaxRequest
class.

IN THIS SECTION:
CalculateTaxRequest Constructors
Learn more about the constructors that are available with the CalculateTaxRequest class. This constructor is intended for
test usage and throws an exception if used outside of the Apex test context.
CalculateTaxRequest Properties
Learn more about the available properties with the CalculateTaxRequest class.
CalculateTaxRequest Methods
Learn more about the available methods with the CalculateTaxRequest class.

CalculateTaxRequest Constructors
Learn more about the constructors that are available with the CalculateTaxRequest class. This constructor is intended for test
usage and throws an exception if used outside of the Apex test context.
The CalculateTaxRequest class includes these constructors.

IN THIS SECTION:
CalculateTaxRequest(taxType)
This constructor is intended for test usage only and throws an exception if used outside of the Apex test context.

CalculateTaxRequest(taxType)
This constructor is intended for test usage only and throws an exception if used outside of the Apex test context.

Signature
global CalculateTaxRequest(commercetax.CalculateTaxType taxType)

Parameters
taxType
Type: CalculateTaxType
Indicates whether the tax calculation is for estimated tax or actual tax.

480
Apex Reference Guide CalculateTaxRequest Class

CalculateTaxRequest Properties
Learn more about the available properties with the CalculateTaxRequest class.
The CalculateTaxRequest class includes these properties.

IN THIS SECTION:
isCommit
Indicates whether the tax calculation has to be committed or reported to government authorities.
taxTransactionType
Shows whether the tax transaction is for a credit or debit transaction.
taxType
Shows whether the tax calculation is for estimated or actual tax wherein only actual tax can be submitted.

isCommit
Indicates whether the tax calculation has to be committed or reported to government authorities.

Signature
global Boolean isCommit {get; set;}

Property Value
Type: Boolean

taxTransactionType
Shows whether the tax transaction is for a credit or debit transaction.

Signature
global commercetax.TaxTransactionType taxTransactionType {get; set;}

Property Value
Type: TaxTransactionType

taxType
Shows whether the tax calculation is for estimated or actual tax wherein only actual tax can be submitted.

Signature
global commercetax.CalculateTaxType taxType {get; set;}

Property Value
Type: CalculateTaxType

481
Apex Reference Guide CalculateTaxRequest Class

CalculateTaxRequest Methods
Learn more about the available methods with the CalculateTaxRequest class.
The CalculateTaxRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type CalculateTaxRequest by determining the equality of external objects in a list. This
method is dynamic and is based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type CalculateTaxRequest by determining the uniqueness of the external object records
in a list.
toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type CalculateTaxRequest by determining the equality of external objects in a list. This method
is dynamic and is based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type CalculateTaxRequest by determining the uniqueness of the external object records in a
list.

Signature
global Integer hashCode()

Return Value
Type: Integer

482
Apex Reference Guide CalculateTaxResponse Class

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

CalculateTaxResponse Class
Sets the values of the tax transaction following a response from the external tax engine. Extends the AbstractTransactionResponse class
and is the top-level response class.

Namespace
CommerceTax

Example
if(requestType == commercetax.RequestType.CalculateTax){
commercetax.calculatetaxtype type = request.taxtype;
String docCode='';
if(request.DocumentCode == 'simulateEmptyDocumentCode')
docCode = '';
else if(request.DocumentCode != null)
docCode =request.DocumentCode;
else if(request.ReferenceEntityId != null) docCode = request.ReferenceEntityId;

else docCode = String.valueOf(getRandomInteger(0,2147483647));


commercetax.CalculateTaxResponse response = new
commercetax.CalculateTaxResponse();
if(request.isCommit == true) {
response.setStatus(commercetax.TaxTransactionStatus.Committed);
} else {
response.setStatus(commercetax.TaxTransactionStatus.Uncommitted);
}
response.setDocumentCode(docCode);
response.setReferenceDocumentCode(request.referenceDocumentCode);
response.setTaxType(type);
response.setStatusDescription('statusDescription');
if(request.sellerDetails.code == 'testSellerCode') {
response.setDescription('SellerCode fetched from TaxEngine entity');
}
else {
response.setDescription('description');
}
response.setEffectiveDate(system.now());
if(request.transactionDate == null) {

483
Apex Reference Guide CalculateTaxResponse Class

response.setTransactionDate(system.now());
} else {
response.setTransactionDate(request.transactionDate);
}
if(request.taxTransactionType == null) {
response.setTaxTransactionType(commercetax.TaxTransactionType.Debit);
} else {
response.setTaxTransactionType(request.taxTransactionType);
}
if(request.currencyIsoCode == null || request.currencyIsoCode == '') {
response.setCurrencyIsoCode('USD');
} else {
response.setCurrencyIsoCode(request.currencyIsoCode);
}
response.setReferenceEntityId(request.ReferenceEntityId);
}

IN THIS SECTION:
CalculateTaxResponse Methods
Learn more about the available methods with the CalculateTaxResponse class.

CalculateTaxResponse Methods
Learn more about the available methods with the CalculateTaxResponse class.
The CalculateTaxResponse class includes these methods.

IN THIS SECTION:
setAddresses(addresses)
Sets the value of the Addresses field using the addresses contained in an instance of the AddressesResponse class.
setAmountDetails(amountDetails)
Sets the value of the AmountDetails field using an instance of AmountDetailsResponse.
setCurrencyIsoCode(currencyIsoCode)
Sets the value of the CurrencyIsoCode field of the CalculateTaxResponse object.
setDescription(dscptn)
Sets the value of the Description field of the CalculateTaxResponse object.
setDocumentCode(documentCode)
Sets the value of the DocumentCode field of the CalculateTaxResponse object.
setEffectiveDate(effectiveDate)
Sets the value of the EffectiveDate field of the CalculateTaxResponse object.
setLineItems(lineItems)
Sets the value of the LineItems field of the CalculateTaxResponse object.
setReferenceDocumentCode(referenceDocumentCode)
Sets the value of the ReferenceDocumentCode field of the CalculateTaxResponse object.

484
Apex Reference Guide CalculateTaxResponse Class

setReferenceEntityId(referenceEntityId)
Sets the value of the ReferenceEntityId field of the CalculateTaxResponse object.
setStatus(status)
Sets the value of the Status field of the CalculateTaxResponse object.
setStatusDescription(statusDescription)
Sets the value of the StatusDescription field of the CalculateTaxResponse object.
setTaxTransactionId(taxTrxnId)
Sets the value of the TaxTransactionId field of the CalculateTaxResponse object.
setTaxTransactionType(taxTransactionType)
Sets the value of the TaxTransactionType field of the CalculateTaxResponse object.
setTaxType(taxType)
Sets the value of the TaxType field of the CalculateTaxResponse object.
setTransactionDate(transactionDate)
Sets the value of the TransactionDate field of the CalculateTaxResponse object.

setAddresses(addresses)
Sets the value of the Addresses field using the addresses contained in an instance of the AddressesResponse class.

Signature
global void setAddresses(commercetax.AddressesResponse addresses)

Parameters
addresses
Type: AddressesResponse
Contains Ship To, Ship From, and Sold To addresses.

Return Value
Type: void

setAmountDetails(amountDetails)
Sets the value of the AmountDetails field using an instance of AmountDetailsResponse.

Signature
global void setAmountDetails(commercetax.AmountDetailsResponse amountDetails)

Parameters
amountDetails
Type: AmountDetailsResponse
The tax amount details for a line item on which tax was calculated.

485
Apex Reference Guide CalculateTaxResponse Class

Return Value
Type: void

setCurrencyIsoCode(currencyIsoCode)
Sets the value of the CurrencyIsoCode field of the CalculateTaxResponse object.

Signature
global void setCurrencyIsoCode(String currencyIsoCode)

Parameters
currencyIsoCode
Type: String
Three-letter ISO 4217 currency code associated with a tax object.

Return Value
Type: void

setDescription(dscptn)
Sets the value of the Description field of the CalculateTaxResponse object.

Signature
global void setDescription(String dscptn)

Parameters
dscptn
Type: String
Optional description for providing more information about the calculate tax response.

Return Value
Type: void

setDocumentCode(documentCode)
Sets the value of the DocumentCode field of the CalculateTaxResponse object.

Signature
global void setDocumentCode(String documentCode)

486
Apex Reference Guide CalculateTaxResponse Class

Parameters
documentCode
Type: String
Code for a tax document that’s created by the tax engine for the calculation process.

Return Value
Type: void

setEffectiveDate(effectiveDate)
Sets the value of the EffectiveDate field of the CalculateTaxResponse object.

Signature
global void setEffectiveDate(Datetime effectiveDate)

Parameters
effectiveDate
Type: Datetime
The date a tax calculation action takes effect. This parameter is optional and is provided only for recordkeeping purpose. Additionally,
this parameter is used to determine the tax rates or rules and overrides the transaction date. For example, if the tax calculation
request is placed on January 3 and the transaction date is January 1, you can set the effective date as January 1.

Return Value
Type: void

setLineItems(lineItems)
Sets the value of the LineItems field of the CalculateTaxResponse object.

Signature
global void setLineItems(List<commercetax.LineItemResponse> lineItems)

Parameters
lineItems
Type: List<LineItemResponse>
Response object that the tax adapter populates from the response of the external tax engine.

Return Value
Type: void

487
Apex Reference Guide CalculateTaxResponse Class

setReferenceDocumentCode(referenceDocumentCode)
Sets the value of the ReferenceDocumentCode field of the CalculateTaxResponse object.

Signature
global void setReferenceDocumentCode(String referenceDocumentCode)

Parameters
referenceDocumentCode
Type: String
Code for a reference document used in the tax calculation process.

Return Value
Type: void

setReferenceEntityId(referenceEntityId)
Sets the value of the ReferenceEntityId field of the CalculateTaxResponse object.

Signature
global void setReferenceEntityId(String referenceEntityId)

Parameters
referenceEntityId
Type: String
ID of an entity related to the line items submitted for tax calculation. For example, if order items were sent for tax calculation, you
could use the ID of their parent order.

Return Value
Type: void

setStatus(status)
Sets the value of the Status field of the CalculateTaxResponse object.

Signature
global void setStatus(commercetax.TaxTransactionStatus status)

Parameters
status
Type: TaxTransactionStatus
Indicates whether a tax transaction has been committed.

488
Apex Reference Guide CalculateTaxResponse Class

Return Value
Type: void

setStatusDescription(statusDescription)
Sets the value of the StatusDescription field of the CalculateTaxResponse object.

Signature
global void setStatusDescription(String statusDescription)

Parameters
statusDescription
Type: String
Optional value for providing more information about a tax transaction's status.

Return Value
Type: void

setTaxTransactionId(taxTrxnId)
Sets the value of the TaxTransactionId field of the CalculateTaxResponse object.

Signature
public void setTaxTransactionId(String taxTrxnId)

Parameters
taxTrxnId
Type: String
The ID of the Salesforce tax transaction entity that stores information about the tax calculation transaction.

Return Value
Type: void

setTaxTransactionType(taxTransactionType)
Sets the value of the TaxTransactionType field of the CalculateTaxResponse object.

Signature
global void setTaxTransactionType(commercetax.TaxTransactionType taxTransactionType)

489
Apex Reference Guide CalculateTaxType Enum

Parameters
taxTransactionType
Type: TaxTransactionType
Whether the tax transaction was for a credit or debit transacation.

Return Value
Type: void

setTaxType(taxType)
Sets the value of the TaxType field of the CalculateTaxResponse object.

Signature
global void setTaxType(commercetax.CalculateTaxType taxType)

Parameters
taxType
Type: CalculateTaxType
Indicates whether a tax calculation request is for estimated or actual tax.

Return Value
Type: void

setTransactionDate(transactionDate)
Sets the value of the TransactionDate field of the CalculateTaxResponse object.

Signature
global void setTransactionDate(Datetime transactionDate)

Parameters
transactionDate
Type: Datetime
The date that the tax transaction occurred.

Return Value
Type: void

CalculateTaxType Enum
Shows whether a tax calculation request is for estimated or actual tax.

490
Apex Reference Guide ErrorResponse Class

Usage
Used by the CalculateTaxRequest and CalculateTaxResponse class methods.

Enum Values
The commercetax.CalculateTaxType enum includes these values.

Value Description
Actual Specifies that the tax calculation service should calculate the finalized (actual) tax
for the requested line items.

Estimated Specifies that the tax calculation service should estimate the tax for the requested
line items.

ErrorResponse Class
Use to respond with an error after receiving errors from the PaymentGatewayAdapter methods of the CommercePayments namespace,
such as request-forbidden responses, custom validation errors, or expired API tokens.

Namespace
CommerceTax

Example
This example snippet of a mock tax adapter shows a hypothetical scenario to demo an error response. The adapter receives request
information from TaxEngineContext and stores it in an instance of CalculateTaxRequest. If the request's documentCode
property is null or indicates an error, the adapter returns an error response with information about the error.

global virtual class MockAdapter implements commercetax.TaxEngineAdapter {

global commercetax.TaxEngineResponse processRequest(commercetax.TaxEngineContext


taxEngineContext) {
commercetax.RequestType requestType = taxEngineContext.getRequestType();
commercetax.CalculateTaxRequest request =
(commercetax.CalculateTaxRequest)taxEngineContext.getRequest();

if(request.documentCode == null) {
return new commercetax.ErrorResponse(commercetax.resultcode.TaxEngineError,
'404', 'documentCode is mandatory');
}
if(request.documentCode == 'TaxEngineError') {
return new commercetax.ErrorResponse(commercetax.resultcode.TaxEngineError,
'504', 'documentCode - not supported');
}
if(request.documentCode == 'simulateValidationFailureInAdapter') {
return new commercetax.ErrorResponse(commercetax.resultcode.TaxEngineError,
'400', 'validations for documentCode failed in adapter');

491
Apex Reference Guide ErrorResponse Class

}
if(request.documentCode == 'simulateMalformedErrorInAdapter') {
return new
commercetax.ErrorResponse(commercetax.resultcode.TaxEngineError, null, 'malformed adapter
error response');
}
if(request.documentCode == 'simulateTaxEngineProcessFailure') {
return new commercetax.ErrorResponse(commercetax.resultcode.TaxEngineError,
'500', 'Tax Engine couldnt process your request');
}

IN THIS SECTION:
ErrorResponse Constructors
Learn more about the available constructors with the ErrorResponse class.

ErrorResponse Constructors
Learn more about the available constructors with the ErrorResponse class.
The ErrorResponse class includes these constructors.

IN THIS SECTION:
ErrorResponse(resultCode, errorCode, errorMessage)
Constructor to initialize an ErrorResponse object from the result code, error code, and error message sent from the tax engine.

ErrorResponse(resultCode, errorCode, errorMessage)


Constructor to initialize an ErrorResponse object from the result code, error code, and error message sent from the tax engine.

Signature
global ErrorResponse(commercetax.ResultCode resultCode, String errorCode, String
errorMessage)

Parameters
resultCode
Type: ResultCode
Code for the type of result sent by the tax engine.
errorCode
Type: String
Code for the type of error sent by the tax engine.
Codes must match the HTTP status codes to be returned to the user. Here are a few examples:
• If the status code is for a bad request, set errorCode to 400.
• If the status code is for a forbidden request, set errorCode to 403.
• If errorCode isn't a valid HTTP status code, a 500 internal server error is returned.

492
Apex Reference Guide HeaderTaxAddressesRequest Class

errorMessage
Type: String
The error message sent by the tax engine.

HeaderTaxAddressesRequest Class
Captures the address values that are applicable for the quote or order transaction.

Namespace
CommerceTax

IN THIS SECTION:
HeaderTaxAddressesRequest Constructors
Learn more about the constructors available with the HeaderTaxAddressesRequest class.
HeaderTaxAddressesRequest Properties
Learn more about the available properties with the HeaderTaxAddressesRequest class.
HeaderTaxAddressesRequest Methods
Learn more about the available methods with the HeaderTaxAddressesRequest class.

HeaderTaxAddressesRequest Constructors
Learn more about the constructors available with the HeaderTaxAddressesRequest class.
The HeaderTaxAddressesRequest class includes these constructors.

IN THIS SECTION:
HeaderTaxAddressesRequest(shipFrom, shipTo, soldTo, billTo, taxEngineAddress)
Constructor for initializing the required addresses of the tax addresses request such as the ship from, ship to, sold to, and bill to
addresses. This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

HeaderTaxAddressesRequest(shipFrom, shipTo, soldTo, billTo, taxEngineAddress)


Constructor for initializing the required addresses of the tax addresses request such as the ship from, ship to, sold to, and bill to addresses.
This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Signature
global HeaderTaxAddressesRequest(commercetax.TaxAddressRequest shipFrom,
commercetax.TaxAddressRequest shipTo, commercetax.TaxAddressRequest soldTo,
commercetax.TaxAddressRequest billTo, commercetax.TaxAddressRequest taxEngineAddress)

Parameters
shipFrom
Type: TaxAddressRequest

493
Apex Reference Guide HeaderTaxAddressesRequest Class

Address where a line item was shipped from.


shipTo
Type: TaxAddressRequest
Address where a line item was shipped to.
soldTo
Type: TaxAddressRequest
Address of the line item's buyer.
billTo
Type: TaxAddressRequest
Person or group who was billed for the line item.
taxEngineAddress
Type: TaxAddressRequest
Address that the tax engine uses to calculate tax.

HeaderTaxAddressesRequest Properties
Learn more about the available properties with the HeaderTaxAddressesRequest class.
The HeaderTaxAddressesRequest class includes these properties.

IN THIS SECTION:
billTo
Specifies the billTo address for a line item on which tax was calculated.
shipFrom
Specifies the shipFrom address for a line item on which tax was calculated.
shipTo
Specifies the shipTo address for a line item on which tax was calculated.
soldTo
Specifies the soldTo address for a line item on which tax was calculated.
taxEngineAddress
Address used by the tax engine when calculating tax for a line item.

billTo
Specifies the billTo address for a line item on which tax was calculated.

Signature
global commercetax.TaxAddressRequest billTo {get; set;}

Property Value
Type: TaxAddressRequest

494
Apex Reference Guide HeaderTaxAddressesRequest Class

shipFrom
Specifies the shipFrom address for a line item on which tax was calculated.

Signature
global commercetax.TaxAddressRequest shipFrom {get; set;}

Property Value
Type: TaxAddressRequest

shipTo
Specifies the shipTo address for a line item on which tax was calculated.

Signature
global commercetax.TaxAddressRequest shipTo {get; set;}

Property Value
Type: TaxAddressRequest

soldTo
Specifies the soldTo address for a line item on which tax was calculated.

Signature
global commercetax.TaxAddressRequest soldTo {get; set;}

Property Value
Type: TaxAddressRequest

taxEngineAddress
Address used by the tax engine when calculating tax for a line item.

Signature
global commercetax.TaxAddressRequest taxEngineAddress {get; set;}

Property Value
Type: TaxAddressRequest

HeaderTaxAddressesRequest Methods
Learn more about the available methods with the HeaderTaxAddressesRequest class.

495
Apex Reference Guide HeaderTaxAddressesRequest Class

The HeaderTaxAddressesRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type HeaderTaxAddressesRequest by determining the equality of external objects in a
list. This method is dynamic and is based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxAddressesRequest by determining the uniqueness of the external objects in a list.
toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type HeaderTaxAddressesRequest by determining the equality of external objects in a list.
This method is dynamic and is based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type TaxAddressesRequest by determining the uniqueness of the external objects in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a value to a string.

496
Apex Reference Guide ImpositionResponse Class

Signature
global String toString()

Return Value
Type: String

ImpositionResponse Class
Stores details of tax impositions from the external tax engine.

Namespace
CommerceTax

Example
In this mock adapter example, the adapter sets the TaxDetailsResponse.setImposition() method parameter to null if
the request's document code indicates that the tax calculation didn't require any exceptions. Otherwise, it creates an instance of
ImpositionResponse and sets its SubType and Type values, and then assigns it to TaxDetailsResponse.

if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
taxDetailsResponse.setImposition(null);
}else{
commercetax.ImpositionResponse imposition = new
commercetax.ImpositionResponse();
imposition.setSubType('subtype');
imposition.setType('type');
taxDetailsResponse.setImposition(imposition);
}

IN THIS SECTION:
ImpositionResponse Methods
Learn more about the available methods with the ImpositionResponse class.

ImpositionResponse Methods
Learn more about the available methods with the ImpositionResponse class.
The ImpositionResponse class includes these methods.

IN THIS SECTION:
setId(id)
Sets the ID field of the ImpositionResponse class.
setName(name)
Sets the Name field of the ImpositionResponse class.

497
Apex Reference Guide ImpositionResponse Class

setSubType(subType)
Sets the SubType field of the ImpositionResponse class.
setType(type)
Sets the Type field of the ImpositionResponse class.

setId(id)
Sets the ID field of the ImpositionResponse class.

Signature
global void setId(String id)

Parameters
id
Type: String
User-defined ID value used for referencing the tax imposition.

Return Value
Type: void

setName(name)
Sets the Name field of the ImpositionResponse class.

Signature
global void setName(String name)

Parameters
name
Type: String
Optional user-defined name for the tax imposition response.

Return Value
Type: void

setSubType(subType)
Sets the SubType field of the ImpositionResponse class.

Signature
global void setSubType(String subType)

498
Apex Reference Guide JurisdictionResponse Class

Parameters
subType
Type: String
Many tax calculation organizations use types and subtypes to categorize their tax imposition procedures. If the tax engine you use
follows this process, set the subtype with this parameter.

Return Value
Type: void

setType(type)
Sets the Type field of the ImpositionResponse class.

Signature
public void setType(String type)

Parameters
type
Type: String
Many tax calculation organizations use types and subtypes to categorize their tax imposition procedures. If the tax engine you use
follows this process, set the type with this parameter.

Return Value
Type: void

JurisdictionResponse Class
Stores details from the external tax engine about the tax jurisdiction used in the tax calculation process. A tax jurisdiction represents a
government entity that collects tax.

Namespace
CommerceTax

Example
In this mock adapter example, the adapter sets the TaxDetailsResponse.setJurisdiction() method parameter to null
if the request's document code indicates that the tax calculation didn't require any exceptions. Otherwise, it creates an instance of
JurisdictionResponse and sets its address values. Because this code represents a mock adapter, the example defines the
address parameters directly. In a standard implementation, the jurisdiction's setters receive values passed from the eternal tax engine.
if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
taxDetailsResponse.setJurisdiction(null);
}else{
commercetax.JurisdictionResponse jurisdiction = new

499
Apex Reference Guide JurisdictionResponse Class

commercetax.JurisdictionResponse();
jurisdiction.setCountry('country');
jurisdiction.setRegion('region');
jurisdiction.setName('name');
jurisdiction.setStateAssignedNumber('stateAssignedNo');
jurisdiction.setId('id');
jurisdiction.setLevel('level');
taxDetailsResponse.setJurisdiction(jurisdiction);

IN THIS SECTION:
JurisdictionResponse Methods
Learn more about the available methods with the JurisdictionResponse class.

JurisdictionResponse Methods
Learn more about the available methods with the JurisdictionResponse class.
The JurisdictionResponse class includes these methods.

IN THIS SECTION:
setCountry(country)
Sets the Country field of the JurisdictionResponse class.
setId(id)
Sets the ID field of the JurisdictionResponse class.
setLevel(level)
Sets the Level field of the JurisdictionResponse class.
setName(name)
Sets the Name field of the JurisdictionResponse class.
setRegion(region)
Sets the Region value of the JurisdictionResponse class.
setStateAssignedNumber(stateAssignedNo)
Sets the StateAssignedNumber field of the JurisdictionResponse class.

setCountry(country)
Sets the Country field of the JurisdictionResponse class.

Signature
global void setCountry(String country)

500
Apex Reference Guide JurisdictionResponse Class

Parameters
country
Type: String
The country of the tax jurisdiction entity's address.

Return Value
Type: void

setId(id)
Sets the ID field of the JurisdictionResponse class.

Signature
global void setId(String id)

Parameters
id
Type: String
User-defined Id value used to reference the jurisdiction response.

Return Value
Type: void

setLevel(level)
Sets the Level field of the JurisdictionResponse class.

Signature
global void setLevel(String level)

Parameters
level
Type: String
Level value used in the jurisdiction entity's address.

Return Value
Type: void

setName(name)
Sets the Name field of the JurisdictionResponse class.

501
Apex Reference Guide JurisdictionResponse Class

Signature
global void setName(String name)

Parameters
name
Type: String
Optional user-defined name field for referencing the jurisdiction response.

Return Value
Type: void

setRegion(region)
Sets the Region value of the JurisdictionResponse class.

Signature
global void setRegion(String region)

Parameters
region
Type: String
Region value used in the tax jurisdiction entity's address.

Return Value
Type: void

setStateAssignedNumber(stateAssignedNo)
Sets the StateAssignedNumber field of the JurisdictionResponse class.

Signature
global void setStateAssignedNumber(String stateAssignedNo)

Parameters
stateAssignedNo
Type: String
State assigned number value of the tax jurisdiction entity's address.

Return Value
Type: void

502
Apex Reference Guide LineItemResponse Class

LineItemResponse Class
Response class that stores details of a list of one or more line items on which the tax engine has calculated tax.

Namespace
CommerceTax

Example
This example uses a LineItemResponse list to store information about each line item that was processed as part of the request.
For simplicity, the sample code uses a static value of 1 for the tax rate. However, most integrations typically have a more complex process
for determining a tax rate. Most integrations also build a TaxDetailsResponse list to store the actual tax value information that
they assign to each line item in the LineItemResponse list.
Double totalTax = 0.0;
Double totalAmount = 0.0;
List<commercetax.LineItemResponse> lineItemResponses = new
List<commercetax.LineItemResponse>();
for(Commercetax.TaxLineItemRequest lineItem : request.lineItems){
commercetax.AddressesResponse addressesRes = new
commercetax.AddressesResponse();
if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
addressesRes.setShipFrom(null);
addressesRes.setShipTO(null);
addressesRes.setSoldTo(null);
}else{
commercetax.AddressResponse addRes = new commercetax.AddressResponse();

addRes.setLocationCode('locationCode');
addressesRes.setShipFrom(addRes);
addressesRes.setShipTO(addRes);
addressesRes.setSoldTo(addRes);
}
commercetax.LineItemResponse lineItemResponse = new
commercetax.LineItemResponse();
Double totalLineTax = 0;
List<commercetax.TaxDetailsResponse> taxDetailsResponses = new
List<commercetax.TaxDetailsResponse>();
for(integer i =0;i<1;i++){
Integer rate = 1;
Double taxableAmount = lineItem.amount;
commercetax.TaxDetailsResponse taxDetailsResponse = new
commercetax.TaxDetailsResponse();
taxDetailsResponse.setRate(Double.valueOf(rate));
taxDetailsResponse.setTaxableAmount(taxableAmount);
Double tax = taxableAmount*rate;
totalLineTax+=tax;
taxDetailsResponse.setTax(taxableAmount*rate);
taxDetailsResponse.setExemptAmount(0);
taxDetailsResponse.setExemptReason('exemptReason');
taxDetailsResponse.setTaxRegionId('taxRegionId');

503
Apex Reference Guide LineItemResponse Class

taxDetailsResponse.setTaxId(String.valueOf(getRandomInteger(0,2323233)));
taxDetailsResponse.setSerCode('serCode');
taxDetailsResponse.setTaxAuthorityTypeId('taxAuthorityTypeId');
if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
taxDetailsResponse.setImposition(null);
}else{
commercetax.ImpositionResponse imposition = new
commercetax.ImpositionResponse();
imposition.setSubType('subtype');
imposition.setType('type');
taxDetailsResponse.setImposition(imposition);
}

if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
taxDetailsResponse.setJurisdiction(null);
}else{
commercetax.JurisdictionResponse jurisdiction = new
commercetax.JurisdictionResponse();
jurisdiction.setCountry('country');
jurisdiction.setRegion('region');
jurisdiction.setName('name');
jurisdiction.setStateAssignedNumber('stateAssignedNo');
jurisdiction.setId('id');
jurisdiction.setLevel('level');
taxDetailsResponse.setJurisdiction(jurisdiction);
}

taxDetailsResponses.add(taxDetailsResponse);
}
lineItemResponse.setTaxes(taxDetailsResponses);
totalTax +=totalLineTax;
totalAmount+=lineItem.amount;

IN THIS SECTION:
LineItemResponse Methods
Learn more about the available methods with the LineItemResponse class.

LineItemResponse Methods
Learn more about the available methods with the LineItemResponse class.
The LineItemResponse class includes these methods.

IN THIS SECTION:
setAddresses(addresses)
Sets the Addresses field on the LineItemResponse using an instance of AddressesResponse class.
setAmountDetails(amountDetails)
Sets the Amount Details field on the LineItemResponse using an instance of AmountDetails.

504
Apex Reference Guide LineItemResponse Class

setEffectiveDate(effectiveDate)
Sets the EffectiveDate field on the LineItemResponse class. Effective Date fields are optional fields that store the date that a
transaction takes effect. We provide these fields only for recordkeeping purposes – for example, if you must report an effective date
to an external general ledger system. Salesforce doesn't use them to calculate any tax or payment values.
setIsTaxable(isTaxable)
Sets the IsTaxable field on the LineItemResponse class.
setLineNumber(lineNumber)
Sets the LineNumber field on the LineItemResponse class.
setProductCode(productCode)
Sets the ProductCode field on the LineItemResponse class.
setQuantity(quantity)
Sets the Quantity field on the LineItemResponse class.
setTaxCode(taxCode)
Sets the TaxCode field on the LineItemResponse.
setTaxes(taxes)
Sets the Taxes field on a LineItemResponse.

setAddresses(addresses)
Sets the Addresses field on the LineItemResponse using an instance of AddressesResponse class.

Signature
global void setAddresses(commercetax.AddressesResponse addresses)

Parameters
addresses
Type: AddressesResponse
Class that contains methods to set the Ship To, Ship From, and Sold To address information.

Return Value
Type: void

setAmountDetails(amountDetails)
Sets the Amount Details field on the LineItemResponse using an instance of AmountDetails.

Signature
global void setAmountDetails(commercetax.AmountDetailsResponse amountDetails)

Parameters
amountDetails
Type: AmountDetailsResponse

505
Apex Reference Guide LineItemResponse Class

Class that contains methods to set the tax amount, total amount with tax, total amount, and exempt amount.

Return Value
Type: void

setEffectiveDate(effectiveDate)
Sets the EffectiveDate field on the LineItemResponse class. Effective Date fields are optional fields that store the date that a
transaction takes effect. We provide these fields only for recordkeeping purposes – for example, if you must report an effective date to
an external general ledger system. Salesforce doesn't use them to calculate any tax or payment values.

Signature
global void setEffectiveDate(Datetime effectiveDate)

Parameters
effectiveDate
Type: Datetime
Optional field that stores the date that a transaction takes effect.

Return Value
Type: void

setIsTaxable(isTaxable)
Sets the IsTaxable field on the LineItemResponse class.

Signature
global void setIsTaxable(Boolean isTaxable)

Parameters
isTaxable
Type: Boolean
Whether line items were taxed as part of the tax calculation request.

Return Value
Type: void

setLineNumber(lineNumber)
Sets the LineNumber field on the LineItemResponse class.

506
Apex Reference Guide LineItemResponse Class

Signature
global void setLineNumber(String lineNumber)

Parameters
lineNumber
Type: String
User-defined number used to identify a line item.

Return Value
Type: void

setProductCode(productCode)
Sets the ProductCode field on the LineItemResponse class.

Signature
global void setProductCode(String productCode)

Parameters
productCode
Type: String
Code for the product that a line item represents.

Return Value
Type: void

setQuantity(quantity)
Sets the Quantity field on the LineItemResponse class.

Signature
global void setQuantity(Double quantity)

Parameters
quantity
Type: Double
Quantity of a line item.

Return Value
Type: void

507
Apex Reference Guide LineTaxAddressesRequest Class

setTaxCode(taxCode)
Sets the TaxCode field on the LineItemResponse.

Signature
global void setTaxCode(String taxCode)

Parameters
taxCode
Type: String
Federal code that an individual or business uses to pay their taxes to a federal or state government. The tax engine uses this code
during the tax calculation process.

Return Value
Type: void

setTaxes(taxes)
Sets the Taxes field on a LineItemResponse.

Signature
global void setTaxes(List<commercetax.TaxDetailsResponse> taxes)

Parameters
taxes
Type: List<TaxDetailsResponse>
Tax values applied to a line item in the LineItemResponse list. This information is stored in a list of TaxDetailsResponses,
which contains values such as tax, taxable amount, and tax rate.

Return Value
Type: void

LineTaxAddressesRequest Class
Stores details of the addresses applied per line item in a tax calculation request.

Namespace
CommerceTax

IN THIS SECTION:
LineTaxAddressesRequest Constructors
Learn more about the constructors available with the LineTaxAddressesRequest class.

508
Apex Reference Guide LineTaxAddressesRequest Class

LineTaxAddressesRequest Properties
Learn more about the available properties with the LineTaxAddressesRequest class.
LineTaxAddressesRequest Methods
Learn more about the available methods with the LineTaxAddressesRequest class.

LineTaxAddressesRequest Constructors
Learn more about the constructors available with the LineTaxAddressesRequest class.
The LineTaxAddressesRequest class includes these constructors.

IN THIS SECTION:
LineTaxAddressesRequest(shipFrom, shipTo, soldTo, billTo, taxEngineAddress)
Constructor for initializing the required addresses for a line item of the tax addresses request such as the ship to, ship from, and bill
to addresses. This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

LineTaxAddressesRequest(shipFrom, shipTo, soldTo, billTo, taxEngineAddress)


Constructor for initializing the required addresses for a line item of the tax addresses request such as the ship to, ship from, and bill to
addresses. This constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Signature
global LineTaxAddressesRequest(commercetax.TaxAddressRequest shipFrom,
commercetax.TaxAddressRequest shipTo, commercetax.TaxAddressRequest soldTo,
commercetax.TaxAddressRequest billTo, commercetax.TaxAddressRequest taxEngineAddress)

Parameters
shipFrom
TaxAddressRequest
Address where a line item was shipped from.
shipTo
TaxAddressRequest
Address where a line item is shipped to.
soldTo
TaxAddressRequest
Address of the line item's buyer.
billTo
TaxAddressRequest
Person or group who was billed for the line item.
taxEngineAddress
TaxAddressRequest
Address that the tax engine uses to calculate tax.

509
Apex Reference Guide LineTaxAddressesRequest Class

LineTaxAddressesRequest Properties
Learn more about the available properties with the LineTaxAddressesRequest class.
The LineTaxAddressesRequest class includes these properties.

IN THIS SECTION:
billTo
The Bill To address for a line item.
shipFrom
The Ship From address for a line item.
shipTo
The Ship To address for a line item.
soldTo
The Sold To address for a line item.

billTo
The Bill To address for a line item.

Signature
global commercetax.TaxAddressRequest billTo {get; set;}

Property Value
Type: TaxAddressRequest

shipFrom
The Ship From address for a line item.

Signature
global commercetax.TaxAddressRequest shipFrom {get; set;}

Property Value
Type: TaxAddressRequest

shipTo
The Ship To address for a line item.

Signature
global commercetax.TaxAddressRequest shipTo {get; set;}

510
Apex Reference Guide LineTaxAddressesRequest Class

Property Value
Type: TaxAddressRequest

soldTo
The Sold To address for a line item.

Signature
global commercetax.TaxAddressRequest soldTo {get; set;}

Property Value
Type: TaxAddressRequest

LineTaxAddressesRequest Methods
Learn more about the available methods with the LineTaxAddressesRequest class.
The LineTaxAddressesRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type LineTaxAddressesRequest by determining the equality of external objects in a list.
This method is dynamic and is based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type LineTaxAddressesRequest by determining the uniquness of the external object
records in a list.
toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type LineTaxAddressesRequest by determining the equality of external objects in a list. This
method is dynamic and is based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

511
Apex Reference Guide RequestType Enum

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type LineTaxAddressesRequest by determining the uniquness of the external object records
in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

RequestType Enum
Shows the type of tax request made to the tax engine.

Usage
Used by the TaxEngineContext class method.

Enum Values
The commercetax.RequestType enum includes these values.

Value Description
CalculateTax Represents a request to calculate tax on a list of taxable line items.

ResultCode Enum
Code that represents the results of a tax request made to the tax engine.

512
Apex Reference Guide RuleDetailsResponse Class

Usage
Used by the ErrorResponse class method.

Enum Values
The commercetax.ResultCode enum includes these values.

Value Description
TaxEngineError Represents an error that occurred during the tax request process.

RuleDetailsResponse Class
Contains details about the tax rules used for tax calculation.

Namespace
CommerceTax

IN THIS SECTION:
RuleDetailsResponse Methods
Learn more about the available methods with the RuleDetailsResponse class.

RuleDetailsResponse Methods
Learn more about the available methods with the RuleDetailsResponse class.
The RuleDetailsResponse includes these methods.

IN THIS SECTION:
RuleDetailsResponse()
Contains information about the tax rules used when calculating tax for line items.
setNonTaxableRuleId(nonTaxableRuleId)
Sets the NonTaxableRuleId field of the RuleDetailsResponse.
setNonTaxableType(nonTaxableType)
Sets the NonTaxableType field of the RuleDetailsResponse.
setRateRuleId(rateRuleId)
Sets the RateRuleId field of the RuleDetailsResponse.
setRateSourceId(rateSourceId)
Sets the RateSourceId field on the RuleDetailsResponse.

RuleDetailsResponse()
Contains information about the tax rules used when calculating tax for line items.

513
Apex Reference Guide RuleDetailsResponse Class

Signature
global void RuleDetailsResponse()

Return Value
Type: void

setNonTaxableRuleId(nonTaxableRuleId)
Sets the NonTaxableRuleId field of the RuleDetailsResponse.

Signature
global void setNonTaxableRuleId(String nonTaxableRuleId)

Parameters
nonTaxableRuleId
Type: String
ID of the tax rule applied to non-taxable line items.

Return Value
Type: void

setNonTaxableType(nonTaxableType)
Sets the NonTaxableType field of the RuleDetailsResponse.

Signature
global void setNonTaxableType(String nonTaxableType)

Parameters
nonTaxableType
Type: String
Reason (from several possible types) that a line item is non-taxable.

Return Value
Type: void

setRateRuleId(rateRuleId)
Sets the RateRuleId field of the RuleDetailsResponse.

Signature
global void setRateRuleId(String rateRuleId)

514
Apex Reference Guide TaxAddressesRequest Class

Parameters
rateRuleId
Type: String
ID of the tax rule used to determine a tax rate.

Return Value
Type: void

setRateSourceId(rateSourceId)
Sets the RateSourceId field on the RuleDetailsResponse.

Signature
global void setRateSourceId(String rateSourceId)

Parameters
rateSourceId
Type: String
ID of the source object used for calculating tax rate.

Return Value
Type: void

TaxAddressesRequest Class
Contains methods to get and set tax address values.

Namespace
CommerceTax

IN THIS SECTION:
TaxAddressesRequest Constructors
Learn more about the available constructors with the TaxAddressesRequest class.
TaxAddressesRequest Properties
Learn more about the available properties with the TaxAddressesRequest class.
TaxAddressesRequest Methods
Learn more about the available methods with the TaxAddressesRequest class.

TaxAddressesRequest Constructors
Learn more about the available constructors with the TaxAddressesRequest class.

515
Apex Reference Guide TaxAddressesRequest Class

The TaxAddressesRequest class includes these constructors.

IN THIS SECTION:
TaxAddressesRequest(shipFrom, shipTo, soldTo, billTo, taxEngineAddress)
Constructor for defining addresses for the tax addresses request. This constructor is intended for test usage and throws an exception
if used outside of the Apex test context.

TaxAddressesRequest(shipFrom, shipTo, soldTo, billTo, taxEngineAddress)


Constructor for defining addresses for the tax addresses request. This constructor is intended for test usage and throws an exception if
used outside of the Apex test context.

Signature
global TaxAddressesRequest(commercetax.TaxAddressRequest shipFrom,
commercetax.TaxAddressRequest shipTo, commercetax.TaxAddressRequest soldTo,
commercetax.TaxAddressRequest billTo, commercetax.TaxAddressRequest taxEngineAddress)

Parameters
shipFrom
TaxAddressRequest
The address where a line item was shipped from.
shipTo
TaxAddressRequest
The address where a line item is shipped to.
soldTo
TaxAddressRequest
The address of the line item's buyer.
billTo
TaxAddressRequest
The person or group who was billed for the line item.
taxEngineAddress
TaxAddressRequest
The address that the tax engine uses to calculate tax.

TaxAddressesRequest Properties
Learn more about the available properties with the TaxAddressesRequest class.
The TaxAddressesRequest class includes these properties.

IN THIS SECTION:
billTo
The Bill To address for a line item.

516
Apex Reference Guide TaxAddressesRequest Class

shipFrom
The Ship From address for a line item.
shipTo
The Ship To address for a line item.
soldTo
The Sold To address for a line item.
taxEngineAddress
The Tax Engine Address for a line item.

billTo
The Bill To address for a line item.

Signature
global commercetax.TaxAddressRequest billTo {get; set;}

Property Value
TaxAddressRequest

shipFrom
The Ship From address for a line item.

Signature
global commercetax.TaxAddressRequest shipFrom {get; set;}

Property Value
TaxAddressRequest

shipTo
The Ship To address for a line item.

Signature
public commercetax.TaxAddressRequest shipTo {get; set;}

Property Value
TaxAddressRequest

soldTo
The Sold To address for a line item.

517
Apex Reference Guide TaxAddressesRequest Class

Signature
global commercetax.TaxAddressRequest soldTo {get; set;}

Property Value
TaxAddressRequest

taxEngineAddress
The Tax Engine Address for a line item.

Signature
global commercetax.TaxAddressRequest taxEngineAddress {get; set;}

Property Value
TaxAddressRequest

TaxAddressesRequest Methods
Learn more about the available methods with the TaxAddressesRequest class.
The TaxAddressesRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type TaxAddressesRequest by determining the equality of external objects in a list. This
method is dynamic and is based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxAddressesRequest by determining the uniqueness of the external object records
in a list.
toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type TaxAddressesRequest by determining the equality of external objects in a list. This method
is dynamic and is based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object

518
Apex Reference Guide TaxAddressRequest Class

External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type TaxAddressesRequest by determining the uniqueness of the external object records in a
list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

TaxAddressRequest Class
Contains address details used for tax calculation.

Namespace
CommerceTax

IN THIS SECTION:
TaxAddressRequest Constructors
Learn more about the available constructors with the TaxAddressRequest class.
TaxAddressRequest Properties
Learn more about the available properties with the TaxAddressRequest class.
TaxAddressRequest Methods
Learn more about the available methods with the TaxAddressRequest class.

519
Apex Reference Guide TaxAddressRequest Class

TaxAddressRequest Constructors
Learn more about the available constructors with the TaxAddressRequest class.
The TaxAddressRequest class includes these constructors.

IN THIS SECTION:
TaxAddressRequest(city, country, latitude, longitude, postalCode, state, street, locationCode)
Initializes the TaxAddressRequest object using address details. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.

TaxAddressRequest(city, country, latitude, longitude, postalCode, state,


street, locationCode)
Initializes the TaxAddressRequest object using address details. This constructor is intended for test usage and throws an exception
if used outside of the Apex test context.

Signature
global TaxAddressRequest(String city, String country, Double latitude, Double longitude,
String postalCode, String state, String street, String locationCode)

Parameters
city
Type: String
City used in an address required for tax calculation.
country
Type: String
Country used in an address required for tax calculation.
latitude
Type: Double
Latitude used in an address required for tax calculation.
longitude
Type: Double
Longitude used in an address required for tax calculation.
postalCode
Type: String
Postal code used in an address required for tax calculation.
state
Type: String
State used in an address required for tax calculation.
street
Type: String
Street used in an address required for tax calculation.

520
Apex Reference Guide TaxAddressRequest Class

locationCode
Type: String
Location code used in an address required for tax calculation.

TaxAddressRequest Properties
Learn more about the available properties with the TaxAddressRequest class.
The TaxAddressRequest class includes these properties.

IN THIS SECTION:
city
City used in an address required for tax calculation.
country
Country used in an address required for tax calculation.
latitude
Latitude used in an address required for tax calculation.
locationCode
Location code used in an address required for tax calculation.
longitude
Longitude used in an address required for tax calculation.
postalCode
Postal code used in an address required for tax calculation.
state
State used in an address required for tax calculation.
street
Street used in an address required for tax calculation.

city
City used in an address required for tax calculation.

Signature
global String city {get; set;}

Property Value
Type: String

country
Country used in an address required for tax calculation.

521
Apex Reference Guide TaxAddressRequest Class

Signature
global String country {get; set;}

Property Value
Type: String

latitude
Latitude used in an address required for tax calculation.

Signature
global Double latitude {get; set;}

Property Value
Type: Double

locationCode
Location code used in an address required for tax calculation.

Signature
global String locationCode {get; set;}

Property Value
Type: String

longitude
Longitude used in an address required for tax calculation.

Signature
global Double longitude {get; set;}

Property Value
Type: Double

postalCode
Postal code used in an address required for tax calculation.

Signature
global String postalCode {get; set;}

522
Apex Reference Guide TaxAddressRequest Class

Property Value
Type: String

state
State used in an address required for tax calculation.

Signature
global String state {get; set;}

Property Value
Type: String

street
Street used in an address required for tax calculation.

Signature
global String street {get; set;}

Property Value
Type: String

TaxAddressRequest Methods
Learn more about the available methods with the TaxAddressRequest class.
The TaxAddressRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type TaxAddressRequest by determining the equality of external objects in a list. This method is
dynamic and based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxAddressRequest by determining the uniqueness of the external object in a list.
toString()
Converts a date to a string.

equals(obj)
Maintains the integrity of lists of type TaxAddressRequest by determining the equality of external objects in a list. This method is dynamic
and based on the equals() method in Java.

523
Apex Reference Guide TaxApiException Class

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type TaxAddressRequest by determining the uniqueness of the external object in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a date to a string.

Signature
global String toString()

Return Value
Type: String

TaxApiException Class
Contains details about any exceptions during the tax calculation process. Extends the ApexBaseException class.

Namespace
CommerceTax

IN THIS SECTION:
TaxApiException Constructors
Learn more about the available constructors with the TaxApiException class.

524
Apex Reference Guide TaxApiException Class

TaxApiException Constructors
Learn more about the available constructors with the TaxApiException class.
The TaxApiException class includes these constructors.

IN THIS SECTION:
TaxApiException(var1, var2)
Initializes the TaxApiException class using an Exception and a string to provide more details about the exception. This
constructor is intended for test usage and throws an exception if used outside of the Apex test context.
TaxApiException(var1)
Initializes the TaxApiException class using an Exception. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.
TaxApiException()
Initializes the TaxApiException class without any initialized parameters. This constructor is intended for test usage and throws
an exception if used outside of the Apex test context.

TaxApiException(var1, var2)
Initializes the TaxApiException class using an Exception and a string to provide more details about the exception. This
constructor is intended for test usage and throws an exception if used outside of the Apex test context.

Signature
global TaxApiException(String var1, Exception var2)

Parameters
var1
Type: String
Text that provides more information about the returned exception.
var2
Type: Exception
An exception denotes an error that disrupts the normal flow of code execution. You can use Apex built-in exceptions or create
custom exceptions. All exceptions have common methods.

TaxApiException(var1)
Initializes the TaxApiException class using an Exception. This constructor is intended for test usage and throws an exception
if used outside of the Apex test context.

Signature
global TaxApiException(Exception var1)

525
Apex Reference Guide TaxCustomerDetailsRequest Class

Parameters
var1
Type: Exception
An exception denotes an error that disrupts the normal flow of code execution. You can use Apex built-in exceptions or create
custom exceptions. All exceptions have common methods.

TaxApiException()
Initializes the TaxApiException class without any initialized parameters. This constructor is intended for test usage and throws an
exception if used outside of the Apex test context.

Signature
global TaxApiException()

TaxCustomerDetailsRequest Class
Contains customer details used in tax calculation.

Namespace
CommerceTax

IN THIS SECTION:
TaxCustomerDetailsRequest Constructors
Learn more about the available constructors with the TaxCustomerDetailsRequest class.
TaxCustomerDetailsRequest Properties
Learn more about the available properties with the TaxCustomerDetailsRequest class.
TaxCustomerDetailsRequest Methods
Learn more about the available methods with the TaxCustomerDetailsRequest class.

TaxCustomerDetailsRequest Constructors
Learn more about the available constructors with the TaxCustomerDetailsRequest class.
The TaxCustomerDetailsRequest class includes these constructors.

IN THIS SECTION:
TaxCustomerDetailsRequest(accountId, code, exemptionNo, exemptionReason)
Initializes the TaxCustomerDetailsRequest object. This constructor is intended for test usage and throws an exception if
used outside of the Apex test context.

TaxCustomerDetailsRequest(accountId, code, exemptionNo, exemptionReason)


Initializes the TaxCustomerDetailsRequest object. This constructor is intended for test usage and throws an exception if used
outside of the Apex test context.

526
Apex Reference Guide TaxCustomerDetailsRequest Class

Signature
global TaxCustomerDetailsRequest(String accountId, String code, String exemptionNo,
String exemptionReason)

Parameters
accountId
Type: String
The customer account ID for the line items sent for tax calculation.
code
Type: String
The tax code used during tax calculation.
exemptionNo
Type: String
The exemption number applied to any tax exempt line items.
exemptionReason
Type: String
The reason that certain line items are tax exempt.

TaxCustomerDetailsRequest Properties
Learn more about the available properties with the TaxCustomerDetailsRequest class.
The TaxCustomerDetailsRequest class includes these properties.

IN THIS SECTION:
accountId
Customer account that contains the line items sent for tax calculation.
code
Tax code used during tax calculation.
exemptionNo
Number used to qualify a line item for tax exemption.
exemptionReason
Reason why a line item qualifies for tax exemption.
taxCertificateId
ID of a tax certificate used for tax calculation.

accountId
Customer account that contains the line items sent for tax calculation.

Signature
global String accountId {get; set;}

527
Apex Reference Guide TaxCustomerDetailsRequest Class

Property Value
Type: String

code
Tax code used during tax calculation.

Signature
global String code {get; set;}

Property Value
Type: String

exemptionNo
Number used to qualify a line item for tax exemption.

Signature
global String exemptionNo {get; set;}

Property Value
Type: String

exemptionReason
Reason why a line item qualifies for tax exemption.

Signature
global String exemptionReason {get; set;}

Property Value
Type: String

taxCertificateId
ID of a tax certificate used for tax calculation.

Signature
global String taxCertificateId {get; set;}

Property Value
Type: String

528
Apex Reference Guide TaxCustomerDetailsRequest Class

TaxCustomerDetailsRequest Methods
Learn more about the available methods with the TaxCustomerDetailsRequest class.
The TaxCustomerDetailsRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type TaxCustomerDetailsRequest by determining the equality of external objects in a
list. This method is dynamic and based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxCustomerDetailsRequest by determining the uniqueness of the external objects
in a list.
toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type TaxCustomerDetailsRequest by determining the equality of external objects in a list.
This method is dynamic and based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type TaxCustomerDetailsRequest by determining the uniqueness of the external objects in
a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

529
Apex Reference Guide TaxDetailsResponse Class

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

TaxDetailsResponse Class
Stores details of the tax values that an external tax engine calculates in response to a tax calculation request.

Namespace
CommerceTax

Usage
If your tax calculation request contains multiple line items, we recommend building your adapter using a list of TaxDetailsResponse
instances. Each instance represents the tax details calculated for a given line item.

Example
List<commercetax.TaxDetailsResponse> taxDetailsResponses = new
List<commercetax.TaxDetailsResponse>();
for(integer i =0;i<1;i++){
Integer rate = 1;
Double taxableAmount = lineItem.amount;
commercetax.TaxDetailsResponse taxDetailsResponse = new
commercetax.TaxDetailsResponse();
taxDetailsResponse.setRate(Double.valueOf(rate));
taxDetailsResponse.setTaxableAmount(taxableAmount);
Double tax = taxableAmount*rate;
totalLineTax+=tax;
taxDetailsResponse.setTax(taxableAmount*rate);
taxDetailsResponse.setExemptAmount(0);
taxDetailsResponse.setExemptReason('exemptReason');
taxDetailsResponse.setTaxRegionId('taxRegionId');

taxDetailsResponse.setTaxId(String.valueOf(getRandomInteger(0,2323233)));
taxDetailsResponse.setSerCode('serCode');
taxDetailsResponse.setTaxAuthorityTypeId('taxAuthorityTypeId');
if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
taxDetailsResponse.setImposition(null);
}else{
commercetax.ImpositionResponse imposition = new
commercetax.ImpositionResponse();

530
Apex Reference Guide TaxDetailsResponse Class

imposition.setSubType('subtype');
imposition.setType('type');
taxDetailsResponse.setImposition(imposition);
}

if(request.DocumentCode == 'SetsNullForResponseWithoutException'){
taxDetailsResponse.setJurisdiction(null);
}else{
commercetax.JurisdictionResponse jurisdiction = new
commercetax.JurisdictionResponse();
jurisdiction.setCountry('country');
jurisdiction.setRegion('region');
jurisdiction.setName('name');
jurisdiction.setStateAssignedNumber('stateAssignedNo');
jurisdiction.setId('id');
jurisdiction.setLevel('level');
taxDetailsResponse.setJurisdiction(jurisdiction);
}

taxDetailsResponses.add(taxDetailsResponse);
}
lineItemResponse.setTaxes(taxDetailsResponses);
totalTax +=totalLineTax;
totalAmount+=lineItem.amount;

IN THIS SECTION:
TaxDetailsResponse Methods
Learn more about the available methods with the TaxDetailsResponse class.

TaxDetailsResponse Methods
Learn more about the available methods with the TaxDetailsResponse class.
The TaxDetailsResponse class includes these methods.

IN THIS SECTION:
setExemptAmount(exemptAmount)
Sets the ExemptAmount field of the TaxDetailsResponse class.
setExemptReason(reason)
Sets the ExemptReason field of the TaxDetailsResponse class.
setImposition(imposition)
Sets the Imposition field of the TaxDetailsResponse class using an instance of the ImpositionResponse class.
setJurisdiction(jurisdiction)
Sets the Jurisdiction field of the TaxDetailsResponse using an instance of the JurisdictionResponse class.
setRate(rate)
Sets the Rate field of the TaxDetailsResponse class.
setSerCode(serCode)
Sets the Service Code field of the TaxDetailsResponse class.

531
Apex Reference Guide TaxDetailsResponse Class

setTax(tax)
Sets the Tax field of the TaxDetailsResponse class.
setTaxAuthorityTypeId(taxAuthorityTypeId)
Sets the TaxAuthorityTypeId field of the TaxDetailsResponse class.
setTaxId(taxId)
Sets the TaxId field of the TaxDetailsResponse class.
setTaxRegionId(taxRegionId)
Sets the TaxRegionId field on the TaxDetailsResponse class.
setTaxRuleDetails(taxRuleDetails)
Sets the TaxRuleDetails field of the TaxDetailsResponse class.
setTaxableAmount(taxableAmount)
Sets the TaxableAmount field of the TaxDetailsResponse class.

setExemptAmount(exemptAmount)
Sets the ExemptAmount field of the TaxDetailsResponse class.

Signature
global void setExemptAmount(Double exemptAmount)

Parameters
exemptAmount
Type: Double
Amount of tax on a line item that is exempt from tax calculation.

Return Value
Type: void

setExemptReason(reason)
Sets the ExemptReason field of the TaxDetailsResponse class.

Signature
global void setExemptReason(String reason)

Parameters
reason
Type: String
Optional user-defined information on why a tax exemption applies to a line item.

532
Apex Reference Guide TaxDetailsResponse Class

Return Value
Type: void

setImposition(imposition)
Sets the Imposition field of the TaxDetailsResponse class using an instance of the ImpositionResponse class.

Signature
global void setImposition(commercetax.ImpositionResponse imposition)

Parameters
imposition
Type: ImpositionResponse
Contains information about why tax was imposed on a line item.

Return Value
Type: void

setJurisdiction(jurisdiction)
Sets the Jurisdiction field of the TaxDetailsResponse using an instance of the JurisdictionResponse class.

Signature
global void setJurisdiction(commercetax.JurisdictionResponse jurisdiction)

Parameters
jurisdiction
Type: JurisdictionResponse
Contains address information about the tax jurisdiction used in the tax calculation process.

Return Value
Type: void

setRate(rate)
Sets the Rate field of the TaxDetailsResponse class.

Signature
global void setRate(Double rate)

533
Apex Reference Guide TaxDetailsResponse Class

Parameters
rate
Type: Double
Tax used during tax calculation. This value is often a decimal amount, such as 0.1 or 0.06, based on the applied tax percentage.

Return Value
Type: void

setSerCode(serCode)
Sets the Service Code field of the TaxDetailsResponse class.

Signature
global void setSerCode(String serCode)

Parameters
serCode
Type: String
Service code used in tax calculation.

Return Value
Type: void

setTax(tax)
Sets the Tax field of the TaxDetailsResponse class.

Signature
global void setTax(Double tax)

Parameters
tax
Type: Double
Amount of tax for a line item.

Return Value
Type: void

setTaxAuthorityTypeId(taxAuthorityTypeId)
Sets the TaxAuthorityTypeId field of the TaxDetailsResponse class.

534
Apex Reference Guide TaxDetailsResponse Class

Signature
global void setTaxAuthorityTypeId(String taxAuthorityTypeId)

Parameters
taxAuthorityTypeId
Type: String
ID of the organization that oversees tax collection.

Return Value
Type: void

setTaxId(taxId)
Sets the TaxId field of the TaxDetailsResponse class.

Signature
global void setTaxId(String taxId)

Parameters
taxId
Type: String
ID value used to determine the tax for an individual or business.

Return Value
Type: void

setTaxRegionId(taxRegionId)
Sets the TaxRegionId field on the TaxDetailsResponse class.

Signature
global void setTaxRegionId(String taxRegionId)

Parameters
taxRegionId
Type: String
ID of the tax region used in tax calculation. A tax region represents a geographical area where tax is applied.

Return Value
Type: void

535
Apex Reference Guide TaxEngineAdapter Interface

setTaxRuleDetails(taxRuleDetails)
Sets the TaxRuleDetails field of the TaxDetailsResponse class.

Signature
global void setTaxRuleDetails(commercetax.RuleDetailsResponse taxRuleDetails)

Parameters
taxRuleDetails
Type: RuleDetailsResponse
Information about the Salesforce tax rules used during tax calculation.

Return Value
Type: void

setTaxableAmount(taxableAmount)
Sets the TaxableAmount field of the TaxDetailsResponse class.

Signature
global void setTaxableAmount(Double taxableAmount)

Parameters
taxableAmount
Type: Double
Amount that can be taxed on a line item.

Return Value
Type: void

TaxEngineAdapter Interface
Retrieves information from the tax engine and evaluates the information to define tax details.

Namespace
CommerceTax

IN THIS SECTION:
TaxEngineAdapter Methods
Learn more about the available methods with the TaxEngineAdapter class.

536
Apex Reference Guide TaxEngineAdapter Interface

TaxEngineAdapter Example Implementation


Refer to the example implementation of the TaxEngineAdapter interface to accept information from a tax engine and evaluate
the information to define tax details.

TaxEngineAdapter Methods
Learn more about the available methods with the TaxEngineAdapter class.
The TaxEngineAdapter class includes these methods.

IN THIS SECTION:
processRequest(requestType)
The processRequest method takes an instance of TaxEngineContext class and returns a response with the calculated
tax details through the TaxDetailsResponse class or an error response through the ErrorResponse class.

processRequest(requestType)
The processRequest method takes an instance of TaxEngineContext class and returns a response with the calculated tax
details through the TaxDetailsResponse class or an error response through the ErrorResponse class.

Signature
global commercetax.TaxEngineResponse processRequest(commercetax.TaxEngineContext var1)

Parameters
var1
Type: TaxEngineContext
Wrapper class that stores information about the type of a tax calculation request.

Return Value
Type: TaxEngineResponse
Generic interface representing a response from a tax engine.

TaxEngineAdapter Example Implementation


Refer to the example implementation of the TaxEngineAdapter interface to accept information from a tax engine and evaluate
the information to define tax details.

Namespace
commercetax

537
Apex Reference Guide TaxEngineAdapter Interface

Usage
The TaxEngineAdapter interface accepts information from the tax engine through the TaxEngineContext class. The
interface evaluates the information to define tax in the response with details, such as tax amount and addresses. The response is used
to update and create entities in the Salesforce org.
Use these steps to build a sample tax adapter implementation. Each tax adapter implementation varies based on your implementation
requirements. Customize this example to suit your business requirements.

Example:
• The custom adapter class implements the TaxEngineAdapter interface. The processRequest method takes an
instance of TaxEngineContext class and returns a response with the calculated tax details through the
TaxDetailsResponse class or an error response through the ErrorResponse class.

global virtual class AvalaraAdapter implements commercetax.TaxEngineAdapter {


global commercetax.TaxEngineResponse processRequest(commercetax.TaxEngineContext
taxEngineContext) {
commercetax.RequestType requestType = taxEngineContext.getRequestType();
if(requestType == commercetax.RequestType.CalculateTax){
return CalculateTaxService.getTax(taxEngineContext);
}
else
return null;
}
}

• This example shows the CalculateTaxService class.


global class CalculateTaxService {
// ============================================================================

// CONSTANT
// ============================================================================

private static final String AVALARA_ENDPOINT_URL_SANDBOX =


'https://sandbox-rest.avatax.com/api/v2';
// Avalara Endpoint URL Production
private static final String AVALARA_ENDPOINT_URL_PRODUCTION =
'https://rest.avatax.com/api/v2';
private static final String TEST_REQUEST_BODY = '{ "id": -1, "code": "00000131",
"companyId": -1, "date": "2017-02-03T00:00:00", "taxDate": "2017-02-03T00:00:00",
"status": "Temporary", "type": "SalesOrder", "reconciled": false, "totalAmount":
4000, "totalExempt": 0, "totalTax": 290, "totalTaxable": 4000,
"totalTaxCalculated": 290, "adjustmentReason": "NotAdjusted", "locked": false,
"version": 1, "modifiedDate": "2017-02-03T12:18:18.7347388Z", "modifiedUserId":
53894, "lines": [ { "id": -1, "transactionId": -1, "lineNumber":
"80241000000jNDCAA2", "discountAmount": 0, "exemptAmount": 0,
"exemptCertId": 0, "isItemTaxable": true, "lineAmount": 1000,
"reportingDate": "2017-02-03T00:00:00", "tax": 72.5, "taxableAmount":
1000, "taxCalculated": 72.5, "taxCode": "P0000000", "taxDate":
"2017-02-03T00:00:00", "taxIncluded": false, "details": [ {
"id": -1, "transactionLineId": -1, "transactionId": -1,
"country": "US", "region": "CA", "exemptAmount": 0,
"jurisCode": "06", "jurisName": "CALIFORNIA", "stateAssignedNo":

538
Apex Reference Guide TaxEngineAdapter Interface

"", "jurisType": "STA", "nonTaxableAmount": 0, "rate":


0.06, "tax": 60, "taxableAmount": 1000, "taxType":
"Sales", "taxName": "CA STATE TAX", "taxAuthorityTypeId": 45,
"taxCalculated": 60, "rateType": "General" }, {
"id": -1, "transactionLineId": -1, "transactionId": -1,
"country": "US", "region": "CA", "exemptAmount": 0,
"jurisCode": "075", "jurisName": "SAN FRANCISCO",
"stateAssignedNo": "", "jurisType": "CTY", "nonTaxableAmount": 0,
"rate": 0.0025, "tax": 2.5, "taxableAmount": 1000,
"taxType": "Sales", "taxName": "CA COUNTY TAX",
"taxAuthorityTypeId": 45, "taxCalculated": 2.5, "rateType":
"General" }, { "id": -1, "transactionLineId": -1,
"transactionId": -1, "country": "US", "region": "CA",
"exemptAmount": 0, "jurisCode": "EMTV0", "jurisName": "SAN
FRANCISCO CO LOCAL TAX SL", "stateAssignedNo": "38", "jurisType":
"STJ", "nonTaxableAmount": 0, "rate": 0.01, "tax": 10,
"taxableAmount": 1000, "taxType": "Sales", "taxName":
"CA SPECIAL TAX", "taxAuthorityTypeId": 45, "taxCalculated": 10,
"rateType": "General" } ] } ]}';

private static String getTestResponseString(){

List<String> jsonResponse = new List<String> {


'"id": 0',
'"code": "testDocCode1231245984"',
'"companyId": 468039',
'"date": "2020-07-15"',
'"paymentDate": "2020-07-15"',
'"status": "Temporary"',
'"type": "SalesOrder"',
'"customerVendorCode": "testDocCode1234"',
'"customerCode": "testDocCode1234"',
'"reconciled": false',
'"totalAmount": 232',
'"totalExempt": 0',
'"totalDiscount": 0',
'"totalTax": 23.43',
'"totalTaxable": 232',
'"totalTaxCalculated": 23.43',
'"adjustmentReason": "NotAdjusted"',
'"locked": false',
'"version": 1',
'"exchangeRateEffectiveDate": "2020-07-15"',
'"exchangeRate": 1',
'"modifiedDate": "2020-08-13T11:19:20.4836636Z"',

'"modifiedUserId": 53894',
'"taxDate": "2020-07-15T00:00:00"',
'"lines": [{"id": 0,"transactionId":
0,"lineNumber": "1","discountAmount": 0,"exemptAmount": 0,"exemptCertId":
0,"isItemTaxable": true,"itemCode": "","lineAmount": 232,"quantity":
1,"reportingDate": "2020-07-15","tax": 23.43,"taxableAmount": 232,"taxCalculated":
23.43,"taxCode": "P0000000","taxCodeId": 8087,"taxDate":
"2020-07-15","taxOverrideType": "None","taxOverrideAmount": 0,"taxIncluded":

539
Apex Reference Guide TaxEngineAdapter Interface

false,"details": [{"id": 0,"transactionLineId": 0,"transactionId": 0,"country":


"US","region": "WA","exemptAmount": 0,"jurisCode": "53","jurisName":
"WASHINGTON","stateAssignedNo": "","jurisType": "STA","jurisdictionType":
"State","nonTaxableAmount": 0,"rate": 0.065,"tax": 15.08,"taxableAmount":
232,"taxType": "Sales","taxSubTypeId": "S","taxName": "WA STATE
TAX","taxAuthorityTypeId": 45,"taxCalculated": 15.08,"rateType":
"General","rateTypeCode": "G","unitOfBasis": "PerCurrencyUnit","isNonPassThru":
false,"isFee": false},{"id": 0,"transactionLineId": 0,"transactionId": 0,"country":
"US","region": "WA","exemptAmount": 0,"jurisCode": "033","jurisName":
"KING","stateAssignedNo": "1700","jurisType": "CTY","jurisdictionType":
"County","nonTaxableAmount": 0,"rate": 0,"tax": 0,"taxableAmount": 232,"taxType":
"Sales","taxSubTypeId": "S","taxName": "WA COUNTY TAX","taxAuthorityTypeId":
45,"taxCalculated": 0,"rateType": "General","rateTypeCode": "G","unitOfBasis":
"PerCurrencyUnit","isNonPassThru": false,"isFee": false}],"nonPassthroughDetails":
[],"hsCode": "","costInsuranceFreight": 0,"vatCode": "","vatNumberTypeId": 0}]',
'"addresses": [{"id": 0,"transactionId":
0,"boundaryLevel": "Address","line1": "255 S. King Street","line2": "","line3":
"","city": "Seattle","region": "WA","postalCode": "98104","country":
"US","taxRegionId": 2109700,"latitude": "47.59821","longitude": "-122.33108"}]',
'"summary": [{"country": "US","region":
"WA","jurisType": "State","jurisCode": "53","jurisName":
"WASHINGTON","taxAuthorityType": 45,"stateAssignedNo": "","taxType":
"Sales","taxSubType": "S","taxName": "WA STATE TAX","rateType": "General","taxable":
232,"rate": 0.065,"tax": 15.08,"taxCalculated": 15.08,"nonTaxable": 0,"exemption":
0},{"country": "US","region": "WA","jurisType": "County","jurisCode":
"033","jurisName": "KING","taxAuthorityType": 45,"stateAssignedNo": "1700","taxType":
"Sales","taxSubType": "S","taxName": "WA COUNTY TAX","rateType": "General","taxable":
232,"rate": 0,"tax": 0,"taxCalculated": 0,"nonTaxable": 0,"exemption": 0}]'
};
return '{' + String.join(jsonResponse, ',') + '}';
}

public static commercetax.TaxEngineResponse getTax(commercetax.TaxEngineContext


taxEngineContext)
{
commercetax.CalculateTaxRequest request =
(commercetax.CalculateTaxRequest)taxEngineContext.getRequest();
commercetax.calculatetaxtype requestType = request.taxtype;
string referenceEntity = request.ReferenceEntityId;
try{
List<commercetax.TaxLineItemRequest> listOfLines = request.lineItems;
if(!listOfLines.isEmpty()){
HttpService sendHttpRequest = new HttpService();
sendHttpRequest.addHeader('Content-type', 'application/json');
String requestBody =
AvalaraJSONBuilder.getInstance().frameJsonForGetTaxOrderItem(request);
sendHttpRequest.post('/transactions/create',requestBody);
//system.debug('Request '+requestBody);
String responseString = '';
if(Test.isRunningTest()){
responseString = getTestResponseString();
} else{
responseString = sendHttpRequest.getResponse().getBody();
}

540
Apex Reference Guide TaxEngineAdapter Interface

//system.debug(sendHttpRequest.getResponse());
//system.debug('response'+responseString);
//responseString = TEST_REQUEST_BODY;
system.debug('Heap size used ' +Limits.getHeapSize());

if(!responseString.contains('error'))
{
commercetax.CalculateTaxResponse response = new
commercetax.CalculateTaxResponse();
JsonSuccessParser jsonSuccessParserClass =
JsonSuccessParser.parse(responseString);
response.setTaxTransactionType(request.taxTransactionType);
response.setDocumentCode(jsonSuccessParserClass.code);

response.setReferenceDocumentCode(jsonSuccessParserClass.referenceCode);
if(jsonSuccessParserClass.status == 'Temporary') {

response.setStatus(commercetax.TaxTransactionStatus.Uncommitted);
}
if(jsonSuccessParserClass.status == 'Committed') {

response.setStatus(commercetax.TaxTransactionStatus.Committed);
}
response.setTaxType(requestType);
commercetax.AmountDetailsResponse headerAmountResponse = new
commercetax.AmountDetailsResponse();

headerAmountResponse.setTotalAmountWithTax(jsonSuccessParserClass.totalAmount +
jsonSuccessParserClass.totaltax);

headerAmountResponse.setExemptAmount(jsonSuccessParserClass.totalExempt);

headerAmountResponse.setTotalAmount(jsonSuccessParserClass.totalAmount);

headerAmountResponse.setTaxAmount(jsonSuccessParserClass.totalTax);
response.setAmountDetails(headerAmountResponse);

response.setStatusDescription(jsonSuccessParserClass.adjustmentReason);

response.setEffectiveDate(date.valueof(jsonSuccessParserClass.taxDate));

response.setTransactionDate(date.valueof(jsonSuccessParserClass.transactionDate));
response.setReferenceEntityId(referenceEntity);
response.setTaxTransactionId(jsonSuccessParserClass.id);
response.setCurrencyIsoCode(request.currencyIsoCode);
List<commercetax.LineItemResponse> lineItemResponses = new
List<commercetax.LineItemResponse>();
for(JsonSuccessParser.Lines linesToProcess:
jsonSuccessParserClass.lines)
{
commercetax.LineItemResponse lineItemResponse = new
commercetax.LineItemResponse();
Double rateCalculated = 0.0;
List<commercetax.TaxDetailsResponse> taxDetailsResponses =

541
Apex Reference Guide TaxEngineAdapter Interface

new List<commercetax.TaxDetailsResponse>();
for(JsonSuccessParser.details linesDetails :
linesToProcess.details)
{
commercetax.TaxDetailsResponse taxDetailsResponse = new
commercetax.TaxDetailsResponse();
if(linesDetails.exemptAmount != 0){

taxDetailsResponse.setExemptAmount(linesDetails.exemptAmount);
taxDetailsResponse.setExemptReason('Some reason we
dont know');
}
commercetax.ImpositionResponse imposition = new
commercetax.ImpositionResponse();
imposition.setSubType(linesDetails.taxName);
imposition.setType(linesDetails.ratetype);
imposition.setSubType(linesDetails.taxName);
taxDetailsResponse.setImposition(imposition);
commercetax.JurisdictionResponse jurisdiction = new
commercetax.JurisdictionResponse();
jurisdiction.setCountry(linesDetails.country);
jurisdiction.setRegion(linesDetails.region);
jurisdiction.setName(linesDetails.jurisName);

jurisdiction.setStateAssignedNumber(linesDetails.stateAssignedNo);
jurisdiction.setId(linesDetails.jurisCode);
jurisdiction.setLevel(linesDetails.jurisType);
taxDetailsResponse.setJurisdiction(jurisdiction);

rateCalculated += linesDetails.rate;
taxDetailsResponse.setRate(rateCalculated);
taxDetailsResponse.setTax(linesDetails.taxCalculated);

taxDetailsResponse.setTaxableAmount(linesDetails.taxableAmount);

taxDetailsResponse.setTaxAuthorityTypeId(String.valueOf(linesDetails.taxAuthorityTypeId));

taxDetailsResponse.setTaxId(linesDetails.id);

taxDetailsResponse.setTaxRegionId(linesDetails.region);
taxDetailsResponses.add(taxDetailsResponse);

}
lineItemResponse.setTaxes(taxDetailsResponses);

lineItemResponse.setEffectiveDate(date.valueof(linesToProcess.taxDate));
lineItemResponse.setIsTaxable(true);
commercetax.AmountDetailsResponse amountResponse =
new commercetax.AmountDetailsResponse();

amountResponse.setTaxAmount(linesToProcess.taxCalculated);

amountResponse.setTotalAmount(linesToProcess.lineAmount);

542
Apex Reference Guide TaxEngineAdapter Interface

amountResponse.setTotalAmountWithTax(linesToProcess.lineAmount+linesToProcess.taxCalculated);

amountResponse.setExemptAmount(linesToProcess.exemptAmount);
lineItemResponse.setAmountDetails(amountResponse);

lineItemResponse.setIsTaxable(linesToProcess.isItemTaxable);
lineItemResponse.setProductCode(linesToProcess.itemCode);

lineItemResponse.setTaxCode(linesToProcess.taxCode);
lineItemResponse.setLineNumber(linesToProcess.lineNumber);

lineItemResponse.setQuantity(linesToProcess.quantity);
lineItemResponses.add(lineItemResponse);
}
response.setLineItems(lineItemResponses);
return response;
}
else
{
JsonErrorParser jsonErrorParserClass =
JsonErrorParser.parse(responseString);
String message = null;
if(String.isNotBlank(jsonErrorParserClass.error.message))
{
message=jsonErrorParserClass.error.message;
}else{
String errorMessage = '';
for(JsonErrorParser.cls_details messageString :
jsonErrorParserClass.error.details)
{
if(String.isNotBlank(messageString.message) )
{
errorMessage = messageString.message;
}
}
message = errorMessage;
}
return new
commercetax.ErrorResponse(commercetax.resultcode.TaxEngineError, '501', message);

}
}else return null;
}
catch (Exception e)
{
throw e;
}
}
}

543
Apex Reference Guide TaxEngineAdapter Interface

• In the HttpService class, replace the test value in the endpoint variable with the name of the
TaxTypedNamedCredential record. This class contains the credentials that are required to access your Avalara account
through Salesforce.

public with sharing class HttpService


{
// Attribute to implement singleton pattern for Order Product Service class
private static HttpService httpServiceInstance;

// VARIABLES

private HttpResponse httpResponse;


private Map<String,String> mapOfHeaderParameter = new Map<String,String>();
private enum Method {GET, POST}

/**
* @name getInstance
* @description get an Instance of Service class
* @params NA
* @return Http Service Class Instance
*/
public static HttpService getInstance()
{
if (NULL == httpServiceInstance)
{
httpServiceInstance = new HttpService();
}
return httpServiceInstance;
}

/**
* @name get
* @description Get Method to get a HTTP request
*/
public void get(String endPoint)
{
send(newRequest(Method.GET, endPoint));
}

/**
* @name post
* @description Post Method to Post a HTTP request
*/
public void post(String path, String requestBody)
{
String endPoint = 'callout:commerce.tax.TaxTypedNamedCredential:test'+path;
send(newRequest(Method.POST, endPoint, requestBody));
}

/**
* @name addHeader
* @description addHeader Methods to add all the defualt Header's required fo
rthe request

544
Apex Reference Guide TaxEngineAdapter Interface

*/
public void addHeader(String name, String value)
{
mapOfHeaderParameter.put(name, value);
}

/**
* @name setHeader
* @description setHeader Methods to set setHeader for the request
*/
private void setHeader(HttpRequest request)
{
for(String headerValue : mapOfHeaderParameter.keySet())
{
request.setHeader(headerValue, mapOfHeaderParameter.get(headerValue));
}
}
/**
* @name newRequest
* @description newRequest Methods to make a new request
*/
private HttpRequest newRequest(Method method, String endPoint)
{
return newRequest(method, endPoint, NULL);
}

/**
* @name newRequest
* @description newRequest Methods to make a new request
*/
private HttpRequest newRequest(Method method, String endPoint, String requestBody)

{
HttpRequest request = new HttpRequest();
request.setMethod(Method.name());
setHeader(request);
request.setEndpoint(endPoint);
if (String.isNotBlank(requestBody))
{
request.setBody(requestBody);
}
request.setTimeout(120000);
return request;
}

/**
* @name send
* @description send Methods to send a request
*/
private void send(HttpRequest request)
{
try
{
Http http = new Http();

545
Apex Reference Guide TaxEngineAdapter Interface

httpResponse = http.send(request);
}
catch(System.CalloutException e)
{
system.debug('callout exception happened' + e.getMessage());
}
catch(Exception e)
{
system.debug('callout did not happen' + e.getMessage());
}
}

/**
* @name getResponse
* @description getResponse Method to get the Response
*/
public HttpResponse getResponse()
{
return httpResponse;
}

/**
* @name getResponseToString
* @description getResponse Method to get the Responses
*/
public String getResponseToString()
{
return getResponse().toString();
}
}

• Parse the JsonSuccessParser response object by using the AvalaraJSONBuilder class to build the response
for your adapter.
This example shows the JsonSuccessParser class.
global with sharing class JsonSuccessParser
{
public static void consumeObject(JSONParser parser)
{
Integer depth = 0;
do {
JSONToken curr = parser.getCurrentToken();
if (curr == JSONToken.START_OBJECT ||
curr == JSONToken.START_ARRAY) {
depth++;
} else if (curr == JSONToken.END_OBJECT ||
curr == JSONToken.END_ARRAY) {
depth--;
}
} while (depth > 0 && parser.nextToken() != null);
}

public class Addresses {


public String id {get;set;}

546
Apex Reference Guide TaxEngineAdapter Interface

public String transactionId {get;set;}


public String boundaryLevel {get;set;}
public String line1 {get;set;}
public String city {get;set;}
public String region {get;set;}
public String postalCode {get;set;}
public String country {get;set;}
public Integer taxRegionId {get;set;}

public Addresses(JSONParser parser) {


while (parser.nextToken() != JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String text = parser.getText();
if (parser.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'id') {
id = parser.getText();
} else if (text == 'transactionId') {
transactionId = parser.getText();
} else if (text == 'boundaryLevel') {
boundaryLevel = parser.getText();
} else if (text == 'line1') {
line1 = parser.getText();
} else if (text == 'city') {
city = parser.getText();
} else if (text == 'region') {
region = parser.getText();
} else if (text == 'postalCode') {
postalCode = parser.getText();
} else if (text == 'country') {
country = parser.getText();
} else if (text == 'taxRegionId') {
taxRegionId = parser.getIntegerValue();
} else {
consumeObject(parser);
}
}
}
}
}
}

public class Details {


public String id {get;set;}
public String transactionLineId {get;set;}
public String transactionId {get;set;}
public String country {get;set;}
public String region {get;set;}
public Integer exemptAmount {get;set;}
public String jurisCode {get;set;}
public String jurisName {get;set;}
public String stateAssignedNo {get;set;}
public String jurisType {get;set;}
public Integer nonTaxableAmount {get;set;}
public Double rate {get;set;}

547
Apex Reference Guide TaxEngineAdapter Interface

public Double tax {get;set;}


public Integer taxableAmount {get;set;}
public String taxType {get;set;}
public String taxName {get;set;}
public Integer taxAuthorityTypeId {get;set;}
public Double taxCalculated {get;set;}
public String rateType {get;set;}

public Details(JSONParser parser) {


while (parser.nextToken() != JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String text = parser.getText();
if (parser.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'id') {
id = parser.getText();
} else if (text == 'transactionLineId') {
transactionLineId = parser.getText();
} else if (text == 'transactionId') {
transactionId = parser.getText();
} else if (text == 'country') {
country = parser.getText();
} else if (text == 'region') {
region = parser.getText();
} else if (text == 'exemptAmount') {
exemptAmount = parser.getIntegerValue();
} else if (text == 'jurisCode') {
jurisCode = parser.getText();
} else if (text == 'jurisName') {
jurisName = parser.getText();
} else if (text == 'stateAssignedNo') {
stateAssignedNo = parser.getText();
} else if (text == 'jurisType') {
jurisType = parser.getText();
} else if (text == 'nonTaxableAmount') {
nonTaxableAmount = parser.getIntegerValue();
} else if (text == 'rate') {
rate = parser.getDoubleValue();
} else if (text == 'tax') {
tax = parser.getDoubleValue();
} else if (text == 'taxableAmount') {
taxableAmount = parser.getIntegerValue();
} else if (text == 'taxType') {
taxType = parser.getText();
} else if (text == 'taxName') {
taxName = parser.getText();
} else if (text == 'taxAuthorityTypeId') {
taxAuthorityTypeId = parser.getIntegerValue();
} else if (text == 'taxCalculated') {
taxCalculated = parser.getDoubleValue();
} else if (text == 'rateType') {
rateType = parser.getText();
} else {
consumeObject(parser);
}

548
Apex Reference Guide TaxEngineAdapter Interface

}
}
}
}
}

public class Messages {


public String summary {get;set;}
public String details {get;set;}
public String refersTo {get;set;}
public String severity {get;set;}
public String source {get;set;}

public Messages(JSONParser parser) {


while (parser.nextToken() != JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String text = parser.getText();
if (parser.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'summary') {
summary = parser.getText();
} else if (text == 'details') {
details = parser.getText();
} else if (text == 'refersTo') {
refersTo = parser.getText();
} else if (text == 'severity') {
severity = parser.getText();
} else if (text == 'source') {
source = parser.getText();
} else {
consumeObject(parser);
}
}
}
}
}
}

public String id {get;set;}


public String code {get;set;}
public String referenceCode {get;set;}
public Integer companyId {get;set;}
public String taxDate {get;set;}
public String transactionDate {get;set;}
public String status {get;set;}
public String type_Z {get;set;} // in json: type
public Boolean reconciled {get;set;}
public Integer totalAmount {get;set;}
public Integer totalExempt {get;set;}
public Double totalTax {get;set;}
public Integer totalTaxable {get;set;}
public Double totalTaxCalculated {get;set;}
public String adjustmentReason {get;set;}
public Boolean locked {get;set;}
public Integer version {get;set;}

549
Apex Reference Guide TaxEngineAdapter Interface

public String modifiedDate {get;set;}


public Integer modifiedUserId {get;set;}
public List<Lines> lines {get;set;}
public List<Addresses> addresses {get;set;}
public List<Summary> summary {get;set;}
public List<Messages> messages {get;set;}

public JsonSuccessParser(JSONParser parser) {


while (parser.nextToken() != JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String text = parser.getText();
if (parser.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'id') {
id = parser.getText();
} else if (text == 'code') {
code = parser.getText();
} else if (text == 'referenceCode'){
referenceCode = parser.getText();
} else if (text == 'companyId') {
companyId = parser.getIntegerValue();
} else if (text == 'taxDate') {
taxDate = parser.getText();
} else if (text == 'date') {
transactionDate = parser.getText();
} else if (text == 'status') {
status = parser.getText();
} else if (text == 'type') {
type_Z = parser.getText();
} else if (text == 'reconciled') {
reconciled = parser.getBooleanValue();
} else if (text == 'totalAmount') {
totalAmount = parser.getIntegerValue();
} else if (text == 'totalExempt') {
totalExempt = parser.getIntegerValue();
} else if (text == 'totalTax') {
totalTax = parser.getDoubleValue();
} else if (text == 'totalTaxable') {
totalTaxable = parser.getIntegerValue();
} else if (text == 'totalTaxCalculated') {
totalTaxCalculated = parser.getDoubleValue();
} else if (text == 'adjustmentReason') {
adjustmentReason = parser.getText();
} else if (text == 'locked') {
locked = parser.getBooleanValue();
} else if (text == 'version') {
version = parser.getIntegerValue();
} else if (text == 'modifiedDate') {
modifiedDate = parser.getText();
} else if (text == 'modifiedUserId') {
modifiedUserId = parser.getIntegerValue();
} else if (text == 'lines') {
lines = new List<Lines>();
while (parser.nextToken() != JSONToken.END_ARRAY) {
lines.add(new Lines(parser));

550
Apex Reference Guide TaxEngineAdapter Interface

}
} else if (text == 'addresses') {
addresses = new List<Addresses>();
while (parser.nextToken() != JSONToken.END_ARRAY) {
addresses.add(new Addresses(parser));
}
} else if (text == 'summary') {
summary = new List<Summary>();
while (parser.nextToken() != JSONToken.END_ARRAY) {
summary.add(new Summary(parser));
}
} else if (text == 'messages') {
messages = new List<Messages>();
while (parser.nextToken() != JSONToken.END_ARRAY) {
messages.add(new Messages(parser));
}
} else {
consumeObject(parser);
}
}
}
}
}

public class Summary {


public String country {get;set;}
public String region {get;set;}
public String jurisType {get;set;}
public String jurisCode {get;set;}
public String jurisName {get;set;}
public Integer taxAuthorityType {get;set;}
public String stateAssignedNo {get;set;}
public String taxType {get;set;}
public String taxName {get;set;}
public String taxGroup {get;set;}
public String rateType {get;set;}
public Integer taxable {get;set;}
public Double rate {get;set;}
public Double tax {get;set;}
public Double taxCalculated {get;set;}
public Integer nonTaxable {get;set;}
public Integer exemption {get;set;}

public Summary(JSONParser parser) {


while (parser.nextToken() != JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String text = parser.getText();
if (parser.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'country') {
country = parser.getText();
} else if (text == 'region') {
region = parser.getText();
} else if (text == 'jurisType') {
jurisType = parser.getText();

551
Apex Reference Guide TaxEngineAdapter Interface

} else if (text == 'jurisCode') {


jurisCode = parser.getText();
} else if (text == 'jurisName') {
jurisName = parser.getText();
} else if (text == 'taxAuthorityType') {
taxAuthorityType = parser.getIntegerValue();
} else if (text == 'stateAssignedNo') {
stateAssignedNo = parser.getText();
} else if (text == 'taxType') {
taxType = parser.getText();
} else if (text == 'taxName') {
taxName = parser.getText();
} else if (text == 'taxGroup') {
taxGroup = parser.getText();
} else if (text == 'rateType') {
rateType = parser.getText();
} else if (text == 'taxable') {
taxable = parser.getIntegerValue();
} else if (text == 'rate') {
rate = parser.getDoubleValue();
} else if (text == 'tax') {
tax = parser.getDoubleValue();
} else if (text == 'taxCalculated') {
taxCalculated = parser.getDoubleValue();
} else if (text == 'nonTaxable') {
nonTaxable = parser.getIntegerValue();
} else if (text == 'exemption') {
exemption = parser.getIntegerValue();
} else {
consumeObject(parser);
}
}
}
}
}
}

public class Lines {


public String id {get;set;}
public String transactionId {get;set;}
public String lineNumber {get;set;}
public Integer discountAmount {get;set;}
public Integer exemptAmount {get;set;}
public Integer exemptCertId {get;set;}
public Boolean isItemTaxable {get;set;}
public Integer lineAmount {get;set;}
public Double quantity {get;set;}
public String reportingDate {get;set;}
public Double tax {get;set;}
public Integer taxableAmount {get;set;}
public Double taxCalculated {get;set;}
public String taxCode {get;set;}
public String taxDate {get;set;}
public Boolean taxIncluded {get;set;}

552
Apex Reference Guide TaxEngineAdapter Interface

public List<Details> details {get;set;}


public String itemCode {get;set;}
public Lines(JSONParser parser) {
while (parser.nextToken() != JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String text = parser.getText();
if (parser.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'id') {
id = parser.getText();
} else if (text == 'transactionId') {
transactionId = parser.getText();
}else if (text == 'itemCode') {
itemCode = parser.getText();
}else if (text == 'lineNumber') {
lineNumber = parser.getText();
} else if (text == 'discountAmount') {
discountAmount = parser.getIntegerValue();
} else if (text == 'exemptAmount') {
exemptAmount = parser.getIntegerValue();
} else if (text == 'exemptCertId') {
exemptCertId = parser.getIntegerValue();
} else if (text == 'isItemTaxable') {
isItemTaxable = parser.getBooleanValue();
} else if (text == 'lineAmount') {
lineAmount = parser.getIntegerValue();
} else if (text == 'quantity') {
quantity = parser.getDoubleValue();
} else if (text == 'reportingDate') {
reportingDate = parser.getText();
} else if (text == 'tax') {
tax = parser.getDoubleValue();
} else if (text == 'taxableAmount') {
taxableAmount = parser.getIntegerValue();
} else if (text == 'taxCalculated') {
taxCalculated = parser.getDoubleValue();
} else if (text == 'taxCode') {
taxCode = parser.getText();
} else if (text == 'taxDate') {
taxDate = parser.getText();
} else if (text == 'taxIncluded') {
taxIncluded = parser.getBooleanValue();
} else if (text == 'details') {
details = new List<Details>();
while (parser.nextToken() != JSONToken.END_ARRAY) {
details.add(new Details(parser));
}
} else {
consumeObject(parser);
}
}
}
}
}
}

553
Apex Reference Guide TaxEngineAdapter Interface

public static JsonSuccessParser parse(String json)


{
return new JsonSuccessParser(System.JSON.createParser(json));
}
}

Prepare your JSON request to call the Avalara endpoint by using the AvalaraJSONBuilder class.
public with sharing class AvalaraJSONBuilder
{
private static AvalaraJSONBuilder avalaraJSONBuilderInstance;

public static AvalaraJSONBuilder getInstance()


{
if (NULL == avalaraJSONBuilderInstance)
{
avalaraJSONBuilderInstance = new AvalaraJSONBuilder();
}
return avalaraJSONBuilderInstance;
}

public String frameJsonForGetTaxOrderItem(commercetax.CalculateTaxRequest


calculateTaxRequest)
{
try
{
Id accountid = null;
if(calculateTaxRequest.CustomerDetails.AccountId != null &&
calculateTaxRequest.CustomerDetails.AccountId != '')
accountid = Id.valueof(calculateTaxRequest.CustomerDetails.AccountId);

JSONGenerator jsonGeneratorInstance = JSON.createGenerator(true);


jsonGeneratorInstance.writeStartObject();
String type = null;
if(calculateTaxRequest.taxtype == commercetax.CalculateTaxType.Actual)
type ='SalesInvoice';
else type = 'SalesOrder';
jsonGeneratorInstance.writeStringField('type', type);
if(calculateTaxRequest.SellerDetails != null)
jsonGeneratorInstance.writeStringField('companyCode',
calculateTaxRequest.SellerDetails.code);
else
jsonGeneratorInstance.writeStringField('companyCode', 'billing2');
if(calculateTaxRequest.isCommit != null) {
jsonGeneratorInstance.writeBooleanField('commit',
calculateTaxRequest.isCommit);
}
if(calculateTaxRequest.documentcode != null){
jsonGeneratorInstance.writeStringField('code',
calculateTaxRequest.documentcode);
}else if(calculateTaxRequest.referenceEntityId != null) {
jsonGeneratorInstance.writeStringField('code',
calculateTaxRequest.referenceEntityId);

554
Apex Reference Guide TaxEngineAdapter Interface

}
if(calculateTaxRequest.CustomerDetails.code == null && accountid !=null)
{
Account acc = [select id, name from account where id=:accountid];
jsonGeneratorInstance.writeStringField('customerCode', acc.name);
} else {
jsonGeneratorInstance.writeStringField('customerCode',
calculateTaxRequest.CustomerDetails.code);
}
if(calculateTaxRequest.EffectiveDate == null)
jsonGeneratorInstance.writeDateField('date', system.today());
else
jsonGeneratorInstance.writeDateTimeField('date',
calculateTaxRequest.EffectiveDate);

jsonGeneratorInstance.writeFieldName('lines');
jsonGeneratorInstance.writeStartArray();
for(integer i=0;i<1;i++){
for(Commercetax.TaxLineItemRequest lineItem :
calculateTaxRequest.LineItems)
{
jsonGeneratorInstance.writeStartObject();
if(lineItem.linenumber != null){
jsonGeneratorInstance.writeStringField('number',
lineItem.linenumber);
}
jsonGeneratorInstance.writeNumberField('quantity',
lineItem.Quantity);
jsonGeneratorInstance.writeNumberField('amount',
(lineItem.Amount));

jsonGeneratorInstance.writeStringField('taxCode',lineItem.taxCode);

jsonGeneratorInstance.writeFieldName('addresses');
jsonGeneratorInstance.writeStartObject();
jsonGeneratorInstance.writeFieldName('ShipFrom');
jsonGeneratorInstance.writeStartObject();
jsonGeneratorInstance.writeStringField('line1',
lineItem.addresses.shipfrom.street);
jsonGeneratorInstance.writeStringField('line2',
lineItem.addresses.shipfrom.street);
jsonGeneratorInstance.writeStringField('city',
lineItem.addresses.shipfrom.city);
jsonGeneratorInstance.writeStringField('region',
lineItem.addresses.shipfrom.state);
jsonGeneratorInstance.writeStringField('country',
lineItem.addresses.shipfrom.country);

jsonGeneratorInstance.writeStringField('postalCode',lineItem.addresses.shipfrom.postalcode);

jsonGeneratorInstance.writeEndObject();

jsonGeneratorInstance.writeFieldName('ShipTo');
jsonGeneratorInstance.writeStartObject();

555
Apex Reference Guide TaxEngineAdapter Interface

jsonGeneratorInstance.writeStringField('line1',
lineItem.addresses.shipto.street);
jsonGeneratorInstance.writeStringField('line2',
lineItem.addresses.shipto.street);
jsonGeneratorInstance.writeStringField('city',
lineItem.addresses.shipto.city);
jsonGeneratorInstance.writeStringField('region',
lineItem.addresses.shipto.state);
jsonGeneratorInstance.writeStringField('country',
lineItem.addresses.shipto.country);

jsonGeneratorInstance.writeStringField('postalCode',lineItem.addresses.shipto.postalcode);

jsonGeneratorInstance.writeEndObject();

jsonGeneratorInstance.writeFieldName('pointOfOrderOrigin');
jsonGeneratorInstance.writeStartObject();
jsonGeneratorInstance.writeStringField('line1',
lineItem.addresses.soldto.street);
jsonGeneratorInstance.writeStringField('line2',
lineItem.addresses.soldto.street);
jsonGeneratorInstance.writeStringField('city',
lineItem.addresses.soldto.city);
jsonGeneratorInstance.writeStringField('region',
lineItem.addresses.soldto.state);
jsonGeneratorInstance.writeStringField('country',
lineItem.addresses.soldto.country);

jsonGeneratorInstance.writeStringField('postalCode',lineItem.addresses.soldto.postalcode);

jsonGeneratorInstance.writeEndObject();

if(lineItem.effectiveDate != null)
{
jsonGeneratorInstance.writeFieldName('taxOverride');
jsonGeneratorInstance.writeStartObject();
jsonGeneratorInstance.writeDateTimeField('taxDate',
lineItem.effectiveDate);
jsonGeneratorInstance.writeEndObject();
}
jsonGeneratorInstance.writeEndObject();
jsonGeneratorInstance.writeEndObject();
}
}
jsonGeneratorInstance.writeEndArray();
jsonGeneratorInstance.writeEndObject();
return jsonGeneratorInstance.getAsString();
}
catch (Exception e)
{
throw e;
}

556
Apex Reference Guide TaxEngineContext Class

}
}

• Use the JsonErrorParser class to extract the error details, if any.


global with sharing class JsonErrorParser
{
public cls_error error;

public class cls_error


{
public String code;
public String message;
public String target;
public cls_details[] details;
}

public class cls_details


{
public String code;
public String message;
public String description;
public String faultCode;
public String helpLink;
public String severity;
}
public static JsonErrorParser parse(String json)
{
return (JsonErrorParser) System.JSON.deserialize(json, JsonErrorParser.class);

}
}

TaxEngineContext Class
Wrapper class that stores details about the type of a tax calculation request.

Namespace
CommerceTax

Example
At the beginning of a tax adapter, use TaxEngineContext class to pass the value of a request type to an instance of RequestType.
global virtual class MockAdapter implements commercetax.TaxEngineAdapter {

global commercetax.TaxEngineResponse processRequest(commercetax.TaxEngineContext


taxEngineContext) {
commercetax.RequestType requestType = taxEngineContext.getRequestType();
commercetax.CalculateTaxRequest request =
(commercetax.CalculateTaxRequest)taxEngineContext.getRequest();

557
Apex Reference Guide TaxEngineContext Class

Build the rest of your adapter based on the type of request that you got from TaxEngineContext class.
if(requestType == commercetax.RequestType.CalculateTax){
commercetax.calculatetaxtype type = request.taxtype;
String docCode='';
if(request.DocumentCode == 'simulateEmptyDocumentCode')
docCode = '';
else if(request.DocumentCode != null)
docCode =request.DocumentCode;
else if(request.ReferenceEntityId != null) docCode = request.ReferenceEntityId;

else docCode = String.valueOf(getRandomInteger(0,2147483647));


commercetax.CalculateTaxResponse response = new
commercetax.CalculateTaxResponse();
if(request.isCommit == true) {
response.setStatus(commercetax.TaxTransactionStatus.Committed);
} else {
response.setStatus(commercetax.TaxTransactionStatus.Uncommitted);
}
}

IN THIS SECTION:
TaxEngineContext Constructors
Learn more about the available constructors with the TaxEngineContext class.
TaxEngineContext Methods
Learn more about the available methods with the TaxEngineContext class.

TaxEngineContext Constructors
Learn more about the available constructors with the TaxEngineContext class.
The TaxEngineContext class includes these constructors.

IN THIS SECTION:
TaxEngineContext(request, requestType, namedUri)
Initializes the TaxEngineContext object. This constructor is intended for test usage and throws an exception if used outside
of the Apex test context.

TaxEngineContext(request, requestType, namedUri)


Initializes the TaxEngineContext object. This constructor is intended for test usage and throws an exception if used outside of
the Apex test context.

Signature
TaxEngineContext(commercetax.TaxEngineRequest request, commercetax.RequestType
requestType, String namedUri)

558
Apex Reference Guide TaxEngineContext Class

Parameters
request
Type: TaxEngineRequest
Information about the request.
requestType
Type: RequestType
Whether the tax request is to calculate or estimate tax.
namedUri
Type: String
URI that was called as part of the tax calculation request.

TaxEngineContext Methods
Learn more about the available methods with the TaxEngineContext class.
The TaxEngineContext class includes these methods.

IN THIS SECTION:
getNamedUri()
Retrieves the value of the NamedUri field of the TaxEngineContext class.
getRequest()
Gets the value of the TaxEngineContext's Request field.
getRequestType()
Gets the value of the RequestType field of the TaxEngineContext class.

getNamedUri()
Retrieves the value of the NamedUri field of the TaxEngineContext class.

Signature
global String getNamedUri()

Return Value
Type: String

getRequest()
Gets the value of the TaxEngineContext's Request field.

Signature
global commercetax.TaxEngineRequest getRequest()

559
Apex Reference Guide TaxLineItemRequest Class

Return Value
Type: TaxEngineRequest
An implemented instance of an external tax engine's interface for processing requests. We've provided the TaxEngineRequest
interface for you to test within mock adapters with classes that implement it, such as CalculateTaxRequest. However, don’t use it outside
of a testing context.

getRequestType()
Gets the value of the RequestType field of the TaxEngineContext class.

Signature
global commercetax.RequestType getRequestType()

Return Value
Type: RequestType
Indicates whether the calculation request was for actual or calculated tax.

TaxLineItemRequest Class
Contains line item details of a tax request.

Namespace
CommerceTax

IN THIS SECTION:
TaxLineItemRequest Constructors
Learn more about the constructors available with the TaxLineItemRequest class.
TaxLineItemRequest Properties
Learn more about the available properties with the TaxLineItemRequest class.
TaxLineItemRequest Methods
Learn more about the available methods with the TaxLineItemRequest class.

TaxLineItemRequest Constructors
Learn more about the constructors available with the TaxLineItemRequest class.
The TaxLineItemRequest class includes these constructors.

IN THIS SECTION:
TaxLineItemRequest(addresses, amount, description, productCode, productSKU, quantity, lineNumber, taxCode, effectiveDate)
Initializes the request for the tax line item. This constructor is intended for test usage and throws an exception if used outside of the
Apex test context.

560
Apex Reference Guide TaxLineItemRequest Class

TaxLineItemRequest(addresses, amount, description, productCode, productSKU,


quantity, lineNumber, taxCode, effectiveDate)
Initializes the request for the tax line item. This constructor is intended for test usage and throws an exception if used outside of the
Apex test context.

Signature
global TaxLineItemRequest(commercetax.LineTaxAddressesRequest addresses, Double amount,
String description, String productCode, String productSKU, Double quantity, String
lineNumber, String taxCode, Datetime effectiveDate)

commercetax.TaxLineItemRequest, newinstance, [commercetax.LineTaxAddressesRequest, Double,


String, String, String, Double, String, String, Datetime], commercetax.TaxLineItemRequest

Parameters
addresses
Type: LineTaxAddressesRequest
Information about the addresses applied to each line item in a tax calculation request.
amount
Type: Double
Total amount (in a given currency) represented by a line item sent for tax calculation.
description
Type: String
User-defined description for a tax line item.
productCode
Type: String
Catalog code for the product represented by the tax line item.
productSKU
Type: String
Unique identifier of a product that can be used to identify products that are exempted from tax.
quantity
Type: Double
Number of units of a given product that the tax line item represents.
lineNumber
Type: String
Unique number used to identify a tax line item.
taxCode
Type: String
Code used to identify how tax is calculated for a tax line item.
effectiveDate
Type: Datetime
This is a user-defined date used for reporting only.

561
Apex Reference Guide TaxLineItemRequest Class

TaxLineItemRequest Properties
Learn more about the available properties with the TaxLineItemRequest class.
The TaxLineItemRequest class includes these properties.

IN THIS SECTION:
addresses
Contains the list of addresses of a line item.
amount
Total amount (in a given currency) represented by a line item sent for tax calculation.
description
User-defined description for a tax line item.
effectiveDate
The date that a tax transaction takes effect on a line item. This is a user-defined date used for reporting only.
lineNumber
Unique number used to identify a tax line item.
productCode
Catalog code for the product represented by the tax line item.
productSKU
Unique identifier of a product that can be used to identify products that are exempted from tax.
quantity
Number of units of a given product that the tax line item represents.
taxCode
Code used to identify how tax is calculated for a tax line item.

addresses
Contains the list of addresses of a line item.

Signature
public commercetax.LineTaxAddressesRequest addresses {get; set;}

Property Value
Type: commercetax.LineTaxAddressesRequest

amount
Total amount (in a given currency) represented by a line item sent for tax calculation.

Signature
global Double amount {get; set;}

562
Apex Reference Guide TaxLineItemRequest Class

Property Value
Type: Double

description
User-defined description for a tax line item.

Signature
global String description {get; set;}

Property Value
Type: String

effectiveDate
The date that a tax transaction takes effect on a line item. This is a user-defined date used for reporting only.

Signature
global Datetime effectiveDate {get; set;}

Property Value
Type: Datetime

lineNumber
Unique number used to identify a tax line item.

Signature
global String lineNumber {get; set;}

Property Value
Type: String

productCode
Catalog code for the product represented by the tax line item.

Signature
global String productCode {get; set;}

Property Value
Type: String

563
Apex Reference Guide TaxLineItemRequest Class

productSKU
Unique identifier of a product that can be used to identify products that are exempted from tax.

Signature
global String productSKU {get; set;}

Property Value
Type: String

quantity
Number of units of a given product that the tax line item represents.

Signature
global Double quantity {get; set;}

Property Value
Type: Double

taxCode
Code used to identify how tax is calculated for a tax line item.

Signature
global String taxCode {get; set;}

Property Value
Type: String

TaxLineItemRequest Methods
Learn more about the available methods with the TaxLineItemRequest class.
The TaxLineItemRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type TaxLineItemRequest by determining the equality of external objects in a list. This
method is dynamic and is based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxLineItemRequest by determining the uniqueness of the external object records in
a list.

564
Apex Reference Guide TaxSellerDetailsRequest Class

toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type TaxLineItemRequest by determining the equality of external objects in a list. This method
is dynamic and is based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type TaxLineItemRequest by determining the uniqueness of the external object records in a
list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

TaxSellerDetailsRequest Class
Contains tax code details used in the tax calculation request.

565
Apex Reference Guide TaxSellerDetailsRequest Class

Namespace
CommerceTax

IN THIS SECTION:
TaxSellerDetailsRequest Constructors
Learn more about the available constructors with the TaxSellerDetailsRequest class.
TaxSellerDetailsRequest Properties
Learn more about the available properties with the TaxSellerDetailsRequest class.
TaxSellerDetailsRequest Methods
Learn more about the available methods with the TaxSellerDetailsRequest class.

TaxSellerDetailsRequest Constructors
Learn more about the available constructors with the TaxSellerDetailsRequest class.
The TaxSellerDetailsRequest class includes these constructors.

IN THIS SECTION:
TaxSellerDetailsRequest(code)
Initializes the request for the tax seller details. This constructor is intended for test usage and throws an exception if used outside of
the Apex test context

TaxSellerDetailsRequest(code)
Initializes the request for the tax seller details. This constructor is intended for test usage and throws an exception if used outside of the
Apex test context

Signature
global TaxSellerDetailsRequest(String code)

Parameters
code
Type: String
Tax code used for tax calculation.

TaxSellerDetailsRequest Properties
Learn more about the available properties with the TaxSellerDetailsRequest class.
The TaxSellerDetailsRequest class includes these properties.

IN THIS SECTION:
code
Tax code used for tax calculation.

566
Apex Reference Guide TaxSellerDetailsRequest Class

code
Tax code used for tax calculation.

Signature
global String code {get; set;}

Property Value
Type: String

TaxSellerDetailsRequest Methods
Learn more about the available methods with the TaxSellerDetailsRequest class.
The TaxSellerDetailsRequest class includes these methods.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type TaxSellerDetailsRequest by determining the equality of the external objects in a
list. This method is dynamic and based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxSellerDetailsRequest by determining the uniqueness of the external objects
in a list.
toString()
Converts a value to a string.

equals(obj)
Maintains the integrity of lists of type TaxSellerDetailsRequest by determining the equality of the external objects in a list.
This method is dynamic and based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object
External object whose key is to be validated.

Return Value
Type: Boolean

567
Apex Reference Guide TaxTransactionRequest Class

hashCode()
Maintains the integrity of lists of type TaxSellerDetailsRequest by determining the uniqueness of the external objects in a
list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

TaxTransactionRequest Class
Abstract class for storing customer details used in tax calculation and estimation requests.

Namespace
CommerceTax

Usage
Specify the CommerceTax namespace when creating an instance of this class. The constructor of this class takes no arguments. For
example, let's say you create an instance of CalculateTaxRequest class, which extends the TaxTransactionRequest
class.

IN THIS SECTION:
TaxTransactionRequest Constructors
Learn more about the available constructors with the TaxTransactionRequest class.
TaxTransactionRequest Properties
Learn more about the available properties with the TaxTransactionRequest class.
TaxTransactionRequest Methods

568
Apex Reference Guide TaxTransactionRequest Class

TaxTransactionRequest Constructors
Learn more about the available constructors with the TaxTransactionRequest class.
The TaxTransactionRequest class includes these constructors.

IN THIS SECTION:
TaxTransactionRequest(addresses, currencyIsoCode, customerDetails, description, documentCode, referenceDocumentCode,
transactionDate, effectiveDate, lineItems, referenceEntityId, sellerDetails)
Initializes the request for the tax transaction. This constructor is intended for test usage and throws an exception if used outside of
the Apex test context.

TaxTransactionRequest(addresses, currencyIsoCode, customerDetails,


description, documentCode, referenceDocumentCode, transactionDate,
effectiveDate, lineItems, referenceEntityId, sellerDetails)
Initializes the request for the tax transaction. This constructor is intended for test usage and throws an exception if used outside of the
Apex test context.

Signature
global TaxTransactionRequest(commercetax.HeaderTaxAddressesRequest addresses, String
currencyIsoCode, commercetax.TaxCustomerDetailsRequest customerDetails, String
description, String documentCode, String referenceDocumentCode, Datetime transactionDate,
Datetime effectiveDate, List<commercetax.TaxLineItemRequest> lineItems, String
referenceEntityId, commercetax.TaxSellerDetailsRequest sellerDetails)

Parameters
addresses
Type: HeaderTaxAddressesRequest
Tax addresses, such as Ship To and Bill From.
currencyIsoCode
Type: String
Three-letter ISO 4217 currency code associated with the TaxTransactionRequest.
customerDetails
Type: TaxCustomerDetailsRequest
Customer information used in tax calculation.
description
Type: String
Optional user-defined description for providing more information about the tax transaction request.
documentCode
Type: String
Code for documents that are used to provide more information in the tax calculation process.
referenceDocumentCode
Type: String

569
Apex Reference Guide TaxTransactionRequest Class

Code for additional documents that are used in the tax calculation process.
transactionDate
Type: Datetime
The date that the tax transaction occurred.
effectiveDate
Type: Datetime
The date that the tax transaction takes effect. User-defined and used only for reporting purposes.
lineItems
Type: List<TaxLineItemRequest>
A list of line items on which tax is calculated.
referenceEntityId
Type: String
ID of an object related to the line items sent for tax calculation.
sellerDetails
Type: TaxSellerDetailsRequest
Contains tax code information used in a tax calculation request.

TaxTransactionRequest Properties
Learn more about the available properties with the TaxTransactionRequest class.
The TaxTransactionRequest class includes these properties.

IN THIS SECTION:
addresses
A list of addresses (such as Ship To and Sold To) used as part of the tax transaction.
currencyIsoCode
Three-letter ISO 4217 currency code associated with the TaxTransactionRequest.
customerDetails
Customer information used in tax calculation.
description
Optional user-defined description for providing more information about the tax transaction request.
documentCode
Code for documents used to provide more information in the tax calculation process.
effectiveDate
The date that the tax transaction takes effect. User-defined and used only for reporting purposes.
lineItems
A list of line items on which tax will be calculated.
referenceDocumentCode
Code for documents used to provide more information in the tax calculation process.
referenceEntityId
ID of an object related to the line items sent for tax calculation.

570
Apex Reference Guide TaxTransactionRequest Class

sellerDetails
Contains tax code information used in a tax calculation request.
transactionDate
The date that the tax transaction occurred.

addresses
A list of addresses (such as Ship To and Sold To) used as part of the tax transaction.

Signature
global commercetax.HeaderTaxAddressesRequest addresses {get; set;}

Property Value
Type: HeaderTaxAddressesRequest

currencyIsoCode
Three-letter ISO 4217 currency code associated with the TaxTransactionRequest.

Signature
global String currencyIsoCode {get; set;}

Property Value
Type: String

customerDetails
Customer information used in tax calculation.

Signature
global CommerceTax.TaxCustomerDetailsRequest customerDetails {get; set;}

Property Value
Type: TaxCustomerDetailsRequest

description
Optional user-defined description for providing more information about the tax transaction request.

Signature
global String description {get; set;}

571
Apex Reference Guide TaxTransactionRequest Class

Property Value
Type: String

documentCode
Code for documents used to provide more information in the tax calculation process.

Signature
global String documentCode {get; set;}

Property Value
Type: String

effectiveDate
The date that the tax transaction takes effect. User-defined and used only for reporting purposes.

Signature
global Datetime effectiveDate {get; set;}

Property Value
Type: Datetime

lineItems
A list of line items on which tax will be calculated.

Signature
global List<CommerceTax.TaxLineItemRequest> lineItems {get; set;}

Property Value
Type: List<TaxLineItemRequest>

referenceDocumentCode
Code for documents used to provide more information in the tax calculation process.

Signature
global String referenceDocumentCode {get; set;}

Property Value
Type: String

572
Apex Reference Guide TaxTransactionRequest Class

referenceEntityId
ID of an object related to the line items sent for tax calculation.

Signature
global String referenceEntityId {get; set;}

Property Value
Type: String

sellerDetails
Contains tax code information used in a tax calculation request.

Signature
global commercetax.TaxSellerDetailsRequest sellerDetails {get; set;}

Property Value
Type: TaxSellerDetailsRequest

transactionDate
The date that the tax transaction occurred.

Signature
global Datetime transactionDate {get; set;}

Property Value
Type: Datetime

TaxTransactionRequest Methods
The following are methods for TaxTransactionRequest.

IN THIS SECTION:
equals(obj)
Maintains the integrity of lists of type TaxTransactionRequest by determining the equality of external objects in a list. This
method is dynamic and based on the equals() method in Java.
hashCode()
Maintains the integrity of lists of type TaxTransactionRequest by determining the uniqueness of the external object records
in a list.
toString()
Converts a value to a string.

573
Apex Reference Guide TaxTransactionStatus Enum

equals(obj)
Maintains the integrity of lists of type TaxTransactionRequest by determining the equality of external objects in a list. This
method is dynamic and based on the equals() method in Java.

Signature
global Boolean equals(Object obj)

Parameters
obj
Type: Object

Return Value
Type: Boolean

hashCode()
Maintains the integrity of lists of type TaxTransactionRequest by determining the uniqueness of the external object records
in a list.

Signature
global Integer hashCode()

Return Value
Type: Integer

toString()
Converts a value to a string.

Signature
global String toString()

Return Value
Type: String

TaxTransactionStatus Enum
Shows whether the tax transaction has been committed or uncommitted.

Usage
Used by the CalculateTaxResponse class method.

574
Apex Reference Guide TaxTransactionType Enum

Enum Values
The commercetax.TaxTransactionStatus enum includes these values.

Value Description
Committed Tax has been calculated and committed.

Uncommitted Tax has been calculated but hasn't been committed.

TaxTransactionType Enum
Shows whether the tax transaction is for a credit or debit transaction.

Usage
Used by the CalculateTaxResponse and CalculateTaxRequest class methods.

Enum Values
The commercetax.TaxTransactionType enum includes these values.

Value Description
Credit Represents a credit transaction.

Debit Represents a debit transaction.

ComplianceMgmt Namespace
The ComplianceMgmt namespace provides classes and methods to implement rule processors for compliance control.
The ComplianceMgmt namespace includes these classes.
• ComplianceEvaluation Interface
• ControlEvaluationInput Class
• ControlInput Class
• ComplianceEvaluationResponse Class
• EvaluationResult Class
• ComplianceControlLog Class

Compression Namespace
The Compression namespace provides classes and methods to create and extract zip files.
The following are the classes and enums in the Compression namespace.

575
Apex Reference Guide Level Enum

IN THIS SECTION:
Level Enum
Specifies the compression level for creating a zip file.
Method Enum
Specifies the compression method for the zip entries.
ZipEntry Class
Contains methods to get and set information about a zip file entry.
ZipReader Class
Contains methods to get information about zip entries and to extract content for specified zip entries from the zip file.
ZipWriter Class
Contains methods to add zip entries, generate a zipped archive, and return the result as an Apex blob.
Compression Exceptions
The Compression namespace contains exception classes.

Level Enum
Specifies the compression level for creating a zip file.

Usage
Use Level enum with the getLevel() and setLevel(value) methods in the ZipWriter class.

Enum Values
The following are the values of the Compression.Level enum.

Value Description
BEST_COMPRESSION Compression level for best compression.

BEST_SPEED Compression level for fastest compression.

DEFAULT_LEVEL Default compression level.

NO_COMPRESSION Compression level for no compression.

Method Enum
Specifies the compression method for the zip entries.

Usage
Use the Method enum with the getMethod() and setMethod(method) methods in the ZipEntry and ZipWriter
classes.

576
Apex Reference Guide ZipEntry Class

Enum Values
The following are the values of the Compression.Method enum.

Value Description
DEFLATED Deflated compression method for compressed entries.

STORED No compression method for zip entries.

ZipEntry Class
Contains methods to get and set information about a zip file entry.

Namespace
Compression

IN THIS SECTION:
ZipEntry Methods

ZipEntry Methods
The following are methods for ZipEntry.

IN THIS SECTION:
equals(obj)
Compares this object with the specified object and returns true if both objects are equal; otherwise, returns false.
hashcode()
Returns the hash code value for the zip entry.
getComment()
Gets the comment string for the zip entry.
getCompressedSize()
Gets the size in bytes of the compressed zip entry.
getContent()
Gets the content of the zip entry. This method doesn’t work with the ZipReader class.
getCrc()
Gets the cyclic redundancy check (CRC) value for the zip entry.
getLastModifiedTime()
Gets the last modification timestamp of the zip entry.
getMethod()
Gets the compression method of the zip entry.
getName()
Gets the name of the zip entry.

577
Apex Reference Guide ZipEntry Class

getUncompressedSize()
Gets the uncompressed size in bytes of the zip entry content.
setComment(comment)
Sets the comment string for the zip entry that’s written to the Zip archive. This method doesn’t work with the ZipReader class.
setContent(blob)
Sets the content of the zip entry that’s written to the Zip archive. This method doesn’t work with the ZipReader class.
setLastModifiedTime(modTime)
Sets the last modification time of the zip entry that’s written to the Zip archive. This method doesn’t work with the ZipReader
class.
setMethod(method)
Sets the compression method for the zip entry that’s written to the zip archive. This method doesn’t work with the ZipReader
class.
toString()
Returns a string representation of the zip entry.

equals(obj)
Compares this object with the specified object and returns true if both objects are equal; otherwise, returns false.

Signature
public Boolean equals(Object obj)

Parameters
obj
Type: Object

Return Value
Type: Boolean

hashcode()
Returns the hash code value for the zip entry.

Signature
public Integer hashcode()

Return Value
Type: Integer

getComment()
Gets the comment string for the zip entry.

578
Apex Reference Guide ZipEntry Class

Signature
public string getComment()

Return Value
Type: string

getCompressedSize()
Gets the size in bytes of the compressed zip entry.

Signature
public long getCompressedSize()

Return Value
Type: long

getContent()
Gets the content of the zip entry. This method doesn’t work with the ZipReader class.

Signature
public blob getContent()

Return Value
Type: blob

getCrc()
Gets the cyclic redundancy check (CRC) value for the zip entry.

Signature
public long getCrc()

Return Value
Type: long

getLastModifiedTime()
Gets the last modification timestamp of the zip entry.

Signature
public Datetime getLastModifiedTime()

579
Apex Reference Guide ZipEntry Class

Return Value
Type: Datetime

getMethod()
Gets the compression method of the zip entry.

Signature
public Compression.Method getMethod()

Return Value
Type: Compression.Method
Uses values from the Method enum and indicates whether the zip entry has DEFLATED or STORED method.

getName()
Gets the name of the zip entry.

Signature
public string getName()

Return Value
Type: string

getUncompressedSize()
Gets the uncompressed size in bytes of the zip entry content.

Signature
public long getUncompressedSize()

Return Value
Type: long

setComment(comment)
Sets the comment string for the zip entry that’s written to the Zip archive. This method doesn’t work with the ZipReader class.

Signature
public Compression.ZipEntry setComment(String comment)

580
Apex Reference Guide ZipEntry Class

Parameters
comment
Type: String

Return Value
Type: Compression.ZipEntry

setContent(blob)
Sets the content of the zip entry that’s written to the Zip archive. This method doesn’t work with the ZipReader class.

Signature
public Compression.ZipEntry setContent(Blob blob)

Parameters
blob
Type: Blob

Return Value
Type: Compression.ZipEntry

setLastModifiedTime(modTime)
Sets the last modification time of the zip entry that’s written to the Zip archive. This method doesn’t work with the ZipReader class.

Signature
public Compression.ZipEntry setLastModifiedTime(Datetime modTime)

Parameters
modTime
Type: Datetime

Return Value
Type: Compression.ZipEntry

setMethod(method)
Sets the compression method for the zip entry that’s written to the zip archive. This method doesn’t work with the ZipReader class.

Signature
public Compression.ZipEntry setMethod(Compression.Method method)

581
Apex Reference Guide ZipReader Class

Parameters
method
Type: Compression.Method
Uses the Method enum values and sets the compression method as DEFLATED or STORED.

Return Value
Type: Compression.ZipEntry

toString()
Returns a string representation of the zip entry.

Signature
public string toString()

Return Value
Type: string

ZipReader Class
Contains methods to get information about zip entries and to extract content for specified zip entries from the zip file.

Namespace
Compression

IN THIS SECTION:
ZipReader Constructors
ZipReader Methods

ZipReader Constructors
The following are constructors for ZipReader.

IN THIS SECTION:
ZipReader(data)
Creates a new instance of the ZipReader class using the specified blob data.

ZipReader(data)
Creates a new instance of the ZipReader class using the specified blob data.

582
Apex Reference Guide ZipReader Class

Signature
global ZipReader(Blob data)

Parameters
data
Type: Blob
Apex blob that contains the compressed content.

ZipReader Methods
The following are methods for ZipReader.

IN THIS SECTION:
extract(name)
Extracts the bytes for the specified zip entry name and decompresses the content.
extract(entry)
Extracts the bytes for the specified zip entry and decompresses the content.
getEntries()
Gets a list of all the entries from the zip file.
getEntriesMap()
Gets a map of names and the corresponding zip entries from the zip file.
getEntry(name)
Gets a zip entry for the specified name from the zip file.
getEntryNames()
Gets a list of all the zip entry names from the zip file.

extract(name)
Extracts the bytes for the specified zip entry name and decompresses the content.

Signature
public blob extract(string name)

Parameters
name
Type: string
Species the zip entry name to extract and decompress.

Return Value
Type: blob
Apex blob that contains the decompressed content.

583
Apex Reference Guide ZipReader Class

extract(entry)
Extracts the bytes for the specified zip entry and decompresses the content.

Signature
public blob extract(Compression.ZipEntry entry)

Parameters
entry
Type: Compression.ZipEntry
Species the zip entry to extract and decompress.

Return Value
Type: blob
Apex blob that contains the decompressed content.

getEntries()
Gets a list of all the entries from the zip file.

Signature
public List<compression.ZipEntry> getEntries()

Return Value
Type: List<Compression.ZipEntry>

getEntriesMap()
Gets a map of names and the corresponding zip entries from the zip file.

Signature
public Map<String,Compression.ZipEntry> getEntriesMap()

Return Value
Type: Map<string,Compression.ZipEntry>

getEntry(name)
Gets a zip entry for the specified name from the zip file.

Signature
public compression.ZipEntry getEntry(string name)

584
Apex Reference Guide ZipWriter Class

Parameters
name
Type: string
Name of the zip entry.

Return Value
Type: Compression.ZipEntry
Throws a ZipException if the specified name isn’t found.

getEntryNames()
Gets a list of all the zip entry names from the zip file.

Signature
public List<String> getEntryNames()

Return Value
Type: List<String>

ZipWriter Class
Contains methods to add zip entries, generate a zipped archive, and return the result as an Apex blob.

Namespace
Compression

Example
This sample code compresses email attachments into a single file.
Compression.ZipWriter writer = new Compression.ZipWriter();

List<id> contentDocumentIds = new List<id>();

// Add IDs of documents to be compressed to contentDocumentIds

for ( ContentVersion cv : [SELECT PathOnClient, Versiondata


FROM ContentVersion
WHERE ContentDocumentId IN :contentDocumentIds])
{
writer.addEntry(cv.PathOnClient, cv.versiondata);
}

blob zipAttachment = writer.getArchive();

Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

585
Apex Reference Guide ZipWriter Class

efa.setFileName('attachments.zip');
efa.setBody(zipAttachment);

List<Messaging.EmailFileAttachment> fileAttachments = new


List<Messaging.EmailFileAttachment>();
fileAttachments.add(efa);

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

// Set all the other email fields, such as addresses, subject, and body

email.setFileAttachments(fileAttachments);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

IN THIS SECTION:
ZipWriter Constructors
ZipWriter Methods

ZipWriter Constructors
The following are constructors for ZipWriter.

IN THIS SECTION:
ZipWriter()
Creates a new instance of the ZipWriter class.

ZipWriter()
Creates a new instance of the ZipWriter class.

Signature
global ZipWriter()

ZipWriter Methods
The following are methods for ZipWriter.

IN THIS SECTION:
addEntry(name, data)
Adds an entry to the zip file with the specified name and content.
addEntry(prototype)
Adds a copy of the specified prototype entry to the zip file and includes details such as the zip entry name, comment, last modification
time, and content.

586
Apex Reference Guide ZipWriter Class

addEntry(name, comment, modTime, method, data)


Adds an entry to the zip file with the specified name, comment, last modification time, compression method, and content.
getArchive()
Compresses the zip entries and generates a ZIP archive.
getEntries()
Gets a list of all the entries in the zip file.
getEntry(name)
Gets the entry with the specified name from the zip file.
getEntryNames()
Gets a set of all the zip entry names in the zip file.
getLevel()
Gets the compression level of the zip file.
getMethod()
Gets the compression method of the zip file.
removeEntry(name)
Removes the entry with the specified name from the zip file.
setLevel(level)
Sets the compression level of the zip file.
setMethod(method)
Sets the compression method for the zip file.

addEntry(name, data)
Adds an entry to the zip file with the specified name and content.

Signature
public Compression.ZipEntry addEntry(string name, blob data)

Parameters
name
Type: string
The name of the zip entry.
data
Type: blob
The content of the zip entry.

Return Value
Type: Compression.ZipEntry
Zip entry added to the zip file.

587
Apex Reference Guide ZipWriter Class

addEntry(prototype)
Adds a copy of the specified prototype entry to the zip file and includes details such as the zip entry name, comment, last modification
time, and content.

Signature
public Compression.ZipEntry addEntry(compression.ZipEntry prototype)

Parameters
prototype
Type: Compression.ZipEntry
Details of the entry to be added to the zip file.

Return Value
Type: Compression.ZipEntry

addEntry(name, comment, modTime, method, data)


Adds an entry to the zip file with the specified name, comment, last modification time, compression method, and content.

Signature
public Compression.ZipEntry addEntry(String name, String comment, Datetime modTime,
Compression.Method method, Blob data)

Parameters
name
Type: String
The name of the zip entry.
comment
Type: String
The comment about the zip entry.
modTime
Type: Datetime
The last modification timestamp of the zip entry.
method
Type: Compression.Method
The compression method of the zip entry, which is either DEFLATED or STORED.
data
Type: Blob
The content of the zip entry.

588
Apex Reference Guide ZipWriter Class

Return Value
Type: Compression.ZipEntry
Zip entry added to the zip file.

getArchive()
Compresses the zip entries and generates a ZIP archive.

Signature
public blob getArchive()

Return Value
Type: blob
Apex blob that contains the bytes of the compression operation.

getEntries()
Gets a list of all the entries in the zip file.

Signature
public List<Compression.ZipEntry> getEntries()

Return Value
Type: List<Compression.ZipEntry>

getEntry(name)
Gets the entry with the specified name from the zip file.

Signature
public compression.ZipEntry getEntry(string name)

Parameters
name
Type: string
Name of the zip entry to be retrieved.

Return Value
Type: Compression.ZipEntry

589
Apex Reference Guide ZipWriter Class

getEntryNames()
Gets a set of all the zip entry names in the zip file.

Signature
public Set<String> getEntryNames()

Return Value
Type: Set<String> on page 3926

getLevel()
Gets the compression level of the zip file.

Signature
public Compression.Level getLevel()

Return Value
Type: Compression.Level
Uses the Level enum values to indicate the compression level as BEST_COMPRESSION, BEST_SPEED, DEFAULT_LEVEL,
or NO_COMPRESSION.

getMethod()
Gets the compression method of the zip file.

Signature
public Compression.Method getMethod()

Return Value
Type: Compression.Method
Uses the Method enum values to indicate the compression method as DEFLATED or STORED.

removeEntry(name)
Removes the entry with the specified name from the zip file.

Signature
public Void removeEntry(string name)

Parameters
name
Type: string

590
Apex Reference Guide Compression Exceptions

Name of the zip entry to be removed. If an entry with this name isn’t found, the method throws a ZipException exception.

Return Value
Type: Void

setLevel(level)
Sets the compression level of the zip file.

Signature
public Compression.ZipWriter setLevel(compression.Level value)

Parameters
value
Type: Compression.Level
Uses the Level enum to set the compression level.

Return Value
Type: Compression.ZipWriter
Returns the zip file set with the specified compression level.

setMethod(method)
Sets the compression method for the zip file.

Signature
public Compression.ZipWriter setMethod(compression.Method value)

Parameters
value
Type: Compression.Method
Uses the Method enum to set the compression method.

Return Value
Type: Compression.ZipWriter
Returns the zip file set with the specified compression method.

Compression Exceptions
The Compression namespace contains exception classes.

591
Apex Reference Guide ConnectApi Namespace

All exception classes support built-in methods for returning the error message and exception type. See Exception Class and Built-In
Exceptions.
The Compression namespace contains this exception:

Exception Description
Compression.ZipException Any problem with the zip operations, such as a zip entry name isn’t found.

ConnectApi Namespace
The ConnectApi namespace (also called Connect in Apex) provides classes for accessing the same data available in Connect REST
API. Use Connect in Apex to create custom experiences in Salesforce.
For information about working with the ConnectApi classes, see Connect in Apex.

IN THIS SECTION:
ActionLinks Class
Create, delete, and get information about an action link group definition; get information about an action link group; get action link
diagnostic information.
Announcements Class
Access information about announcements and post announcements.
BotVersionActivation Class
Access and update activation information of a bot version.
CdpActivation Class
Get, create, update, and delete Data Cloud activations.
CdpActivationTarget Class
Get, create, and update Data Cloud activation targets.
CdpAudienceDMO Class
Get activation records from Data Cloud Audience Data Model Objects (DMOs).
CdpCalculatedInsight Class
Create, delete, get, run, and update Data Cloud calculated insights.
CdpConnection Class
Get database schemas for a Data Cloud connection.
CdpDataSpace Class
Get Data Cloud data spaces.
CdpDataStreams Class
Run Data Cloud data streams.
CdpIdentityResolution Class
Create, delete, get, run, and update Data Cloud identity resolution rulesets.
CdpMachineLearning Class
Make a machine-learning prediction with Data Cloud.

592
Apex Reference Guide ConnectApi Namespace

CdpQuery Class
Get Data Cloud metadata and query data.
CdpSegment Class
Create, delete, get, publish, and update Data Cloud segments.
Chatter Class
Access information about followers and subscriptions for records.
ChatterFavorites Class
Chatter favorites give you easy access to topics, list views, and feed searches.
ChatterFeeds Class
Get, post, and delete feed elements, likes, comments, and bookmarks. You can also search feed elements, share feed elements, and
vote on polls.
ChatterGroups Class
Information about groups, such as the group’s members, photo, and the groups the specified user is a member of. Add members
to a group, remove members, and change the group photo.
ChatterMessages Class
Get, send, search, and reply to private messages. You can also get and search private conversations, mark conversations as read, and
get a count of unread private messages.
ChatterUsers Class
Access information about users, such as activity, followers, subscriptions, files, and groups.
Clm Class
Create and update Contract Lifecycle Management (CLM) contracts using object ID.
CommerceBuyerExperience Class
Create, delete, or get commerce addresses. Get order delivery group, order item, order shipments, shipment items, and order
summaries. Get adjustments for order items and order summaries.
CommerceCart Class
Get, create, update, calculate, and delete carts. Get cart items, add items to carts, update and delete cart items.
CommerceCatalog Class
Get products, product categories, and product category paths.
CommerceCatalogManagement Class
Create or update a composite product. Create a variation product.
CommercePromotions Class
Evaluate promotions for Commerce orders. Get coupon code redemption usage.
CommerceSearch Class
Get sort rules for the live search index. Get product search suggestions. Search products.
CommerceSearchConnectFamily Class
Search products by search term or category in a webstore.
CommerceSearchSettings Class
Get indexes. Get index logs. Create an index of a product catalog.
CommerceStorePricing Class
Get product prices.

593
Apex Reference Guide ConnectApi Namespace

CommerceWishlist Class
Get, create, update, and delete wishlists. Add wishlists to carts. Get wishlist items, add items to wishlists, and delete wishlist items.
Communities Class
Get information about Experience Cloud sites in your org.
CommunityModeration Class
Get information about flagged feed items and comments in an Experience Cloud site. Add and remove flags from comments and
feed items.
ContentHub Class
Access Files Connect repositories and their files and folders.
ConversationApplicationDefinition Class
Access information about a conversation application definition.
Datacloud Class
Purchase Data.com contact or company records, and retrieve purchase information.
EinsteinLLM Class
Get a list of prompt templates and generate LLM responses for prompt templates.
EmailMergeFieldService Class
Extract a list of merge fields for an object. A merge field is a field you can put in an email template, mail merge template, custom
link, or formula to incorporate values from a record.
EmployeeProfiles Class
Get, set and crop, and delete employee banner photos and photos.
Exchanges Class
Preview and submit cart to exchange orders.
ExtendedCommerceDelivery Class
Access information about delivery estimation.
ExternalEmailServices Class
Access information about integration with external email services, such as sending email within Salesforce through an external email
account.
ExternalManagedAccount Class
Get externally managed accounts.
FieldService Class
Preview and create shifts from a pattern.
FulfillmentOrder Class
Fulfill orders in Order Management.
IBusinessObjectivesAndRecsFamily Class
Get and patch business objectives, or goals. Get, create, patch, and update recommended actions for business objectives.
Knowledge Class
Get information about trending articles in Experience Cloud sites.
LightningScheduler Class
Create and update service appointments.

594
Apex Reference Guide ConnectApi Namespace

ManagedContent Class
Clone managed content. Create and get managed content. Delete and replace variants. Get channels. Get a managed content space.
Get targets that managed content space folders can be shared with. Get and update targets that managed content space folders
are shared with. Publish and unpublish content.
ManagedContentChannels Class
Get managed content channels. Create, get, update, or delete a managed content channel.
ManagedContentDelivery Class
Get collection items. Get a managed content channel. Get managed content.
ManagedContentSpaces Class
Get channels in a managed content space. Add or remove channels from a managed content space.
ManagedTopics Class
Get managed topics in an Experience Cloud site. Create, delete, and reorder managed topics.
MarketingIntegration Class
Get, save, and submit a microsites marketing integration form for an Experience Cloud site.
Mentions Class
Access information about mentions. A mention is an “@” character followed by a user or group name. When a user or group is
mentioned, they receive a notification.
Missions Class
Export and purge mission activity for users. Get a user’s mission progress. Update mission activity counts for users.
NamedCredentials Class
Create, refresh, get, delete, replace, and update credentials. Create and get external credentials. Create and get named credentials.
Create, get, delete, and update external auth identity providers. Get the URL for the OAuth token flow for an external credential.
NavigationMenu Class
Get navigation menu items for an Experience Cloud site.
NextBestAction Class
Execute recommendation strategies, get recommendations, manage recommendation reactions.
OmnichannelInventoryService Class
Route orders to inventory locations in Order Management.
OMSAnalytics Class
Get products with return rates, get text classified into different classifications using text analysis, and capture the return reasons from
external sources based on the product ids.
Orchestration Class
Get orchestration instances.
OrderPaymentSummary Class
Work with payments in Order Management.
OrderSummary Class
Work with orders in Order Management.
OrderSummaryCreation Class
Create Order Summaries in Order Management.
Organization Class
Access information about an org.

595
Apex Reference Guide ConnectApi Namespace

PardotBusinessUnitContext Class
Get the Pardot business units the context user has access to.
Payments Class
Authorize a payment, capture an authorized payment, and refund an authorized payment.
Personalization Class
Get assigned personalization audiences that match the user context. Create, get, update, and delete an audience. Get personalization
targets that match the user context, based on the assigned audiences that include the user. Create and update targets. Get and
delete a target.
PickTicket Class
Create tickets to fulfill orders.
QuestionAndAnswers Class
Access question and answers suggestions.
Recommendations Class
Get and reject Chatter, custom, and static recommendations. Create, get, update, and delete custom recommendation audiences,
custom recommendation definitions, and scheduled custom recommendations.
RecordFilterCriteriaFamily Class
Filter records on recordset filter criteria.
Records Class
Access information about record motifs, which are small icons used to distinguish record types in the Salesforce UI.
RegisterGuestBuyer Class
Register a guest buyer for a webstore using an account ID, enabling a guest buyer to order on behalf of another buyer.
Repricing Class
Perform functions related to repricing orders in Order Management.
ReturnOrder Class
Process ReturnOrders in Order Management, limited to 2,000 requests per hour.
Routing Class
Route orders to inventory locations in Order Management.
SalesforceInbox Class
Access information about Automated Activity Capture, which is available in Einstein and Salesforce Inbox.
Search Class
Search objects using keywords or a natural language query.
Sites Class
Search an Experience Cloud site.
SmartDataDiscovery Class
Get predictions on Salesforce objects.
SocialEngagement Class
Manage information about social accounts or fan pages for social networks.
Surveys Class
Send survey invitations by email.
TaxPlatform Class
Apply or cancel tax.

596
Apex Reference Guide ActionLinks Class

Topics Class
Access information about topics, such as their descriptions, the number of people talking about them, related topics, and information
about groups contributing to the topic. Update a topic’s name or description, merge topics, and add and remove topics from records
and feed items.
UserProfiles Class
Access user profile data. The user profile data populates the profile page (also called the Chatter profile page). This data includes
user information (such as address, manager, and phone number), some user capabilities (permissions), and a set of subtab apps,
which are custom tabs on the profile page.
Zones Class
Access information about Chatter Answers zones in your organization. Zones organize questions into logical groups, with each zone
having its own focus and unique questions.
ConnectApi Input Classes
Some ConnectApi methods take arguments that are instances of ConnectApi input classes.
ConnectApi Output Classes
Most ConnectApi methods return instances of ConnectApi output classes.
ConnectApi Enums
Enums specific to the ConnectApi namespace.
ConnectApi Exceptions
The ConnectApi namespace contains exception classes.
ConnectApi Utilities
The ConnectApi namespace contains a utility class.
ConnectApi Release Notes
Use the Salesforce Release Notes to learn about the most recent updates and changes to the ConnectApi namespace in Apex.

ActionLinks Class
Create, delete, and get information about an action link group definition; get information about an action link group; get action link
diagnostic information.

Namespace
ConnectApi

Usage
An action link is a button on a feed element. Clicking an action link can take a user to a Web page, initiate a file download, or invoke an
API call to Salesforce or to an external server. An action link includes a URL and an HTTP method, and can include a request body and
header information, such as an OAuth token for authentication. Use action links to integrate Salesforce and third-party services into the
feed so that users can drive productivity and accelerate innovation.
There are two views of an action link and an action link group: the definition, and the context user’s view. The definition includes potentially
sensitive information, such as authentication information. The context user’s view is filtered by visibility options and the values reflect
the state of the context user.
Action link definition can be sensitive to a third party (for example, OAuth bearer token headers). For this reason, only calls made from
the Apex namespace that created the action link definition can read, modify, or delete the definition. In addition, the user making the

597
Apex Reference Guide ActionLinks Class

call must have created the definition or have View All Data permission. Use these methods to operate on action link group definitions
(which contain action link definitions).
• createActionLinkGroupDefinition(communityId, actionLinkGroup)
• deleteActionLinkGroupDefinition(communityId, actionLinkGroupId)
• getActionLinkGroupDefinition(communityId, actionLinkGroupId)
Use these methods to operate on a context user’s view of an action link or an action link group.
• getActionLink(communityId, actionLinkId)
• getActionLinkGroup(communityId, actionLinkGroupId)
• getActionLinkDiagnosticInfo(communityId, actionLinkId)
For information about how to use action links, see Working with Action Links.

ActionLinks Methods
These methods are for ActionLinks. All methods are static.

IN THIS SECTION:
createActionLinkGroupDefinition(communityId, actionLinkGroup)
Create an action link group definition. To associate an action link group with a feed element, first create an action link group definition.
Then post a feed element with an associated actions capability.
deleteActionLinkGroupDefinition(communityId, actionLinkGroupId)
Delete an action link group definition. Deleting an action link group definition removes all references to it from feed elements.
getActionLink(communityId, actionLinkId)
Get information about an action link, including state for the context user.
getActionLinkDiagnosticInfo(communityId, actionLinkId)
Get diagnostic information returned when an action link executes. Diagnostic information is given only for users who can access
the action link.
getActionLinkGroup(communityId, actionLinkGroupId)
Get information about an action link group including state for the context user.
getActionLinkGroupDefinition(communityId, actionLinkGroupId)
Get information about an action link group definition.

createActionLinkGroupDefinition(communityId, actionLinkGroup)
Create an action link group definition. To associate an action link group with a feed element, first create an action link group definition.
Then post a feed element with an associated actions capability.

API Version
33.0

Requires Chatter
No

598
Apex Reference Guide ActionLinks Class

Signature
public static ConnectApi.ActionLinkGroupDefinition createActionLinkGroupDefinition(String
communityId, ConnectApi.ActionLinkGroupDefinitionInput actionLinkGroup)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
actionLinkGroup
Type: ConnectApi.ActionLinkGroupDefinitionInput
A ConnectApi.ActionLinkGroupDefinitionInput object that defines the action link group.

Return Value
Type: ConnectApi.ActionLinkGroupDefinition

Usage
An action link is a button on a feed element. Clicking an action link can take a user to a Web page, initiate a file download, or invoke an
API call to Salesforce or to an external server. An action link includes a URL and an HTTP method, and can include a request body and
header information, such as an OAuth token for authentication. Use action links to integrate Salesforce and third-party services into the
feed so that users can drive productivity and accelerate innovation.
All action links must belong to a group. Action links in a group are mutually exclusive and share some properties. Define standalone
actions in their own action group.
Information in the action link group definition can be sensitive to a third party (for example, OAuth bearer token headers). For this reason,
only calls made from the Apex namespace that created the action link group definition can read, modify, or delete the definition. In
addition, the user making the call must have created the definition or have View All Data permission.

Note: Invoking ApiAsync action links from an app requires a call to set the status. However, there isn’t currently a way to set
the status of an action link using Apex. To set the status, use Connect REST API. See the Action Link resource in the Connect REST
API Developer Guidefor more information.

Example for Defining an Action Link and Posting with a Feed Element
For more information about this example, see Define an Action Link and Post with a Feed Element.
ConnectApi.ActionLinkGroupDefinitionInput actionLinkGroupDefinitionInput = new
ConnectApi.ActionLinkGroupDefinitionInput();
ConnectApi.ActionLinkDefinitionInput actionLinkDefinitionInput = new
ConnectApi.ActionLinkDefinitionInput();
ConnectApi.RequestHeaderInput requestHeaderInput1 = new ConnectApi.RequestHeaderInput();
ConnectApi.RequestHeaderInput requestHeaderInput2 = new ConnectApi.RequestHeaderInput();

// Create the action link group definition.


actionLinkGroupDefinitionInput.actionLinks = New
List<ConnectApi.ActionLinkDefinitionInput>();
actionLinkGroupDefinitionInput.executionsAllowed =
ConnectApi.ActionLinkExecutionsAllowed.OncePerUser;
actionLinkGroupDefinitionInput.category = ConnectApi.PlatformActionGroupCategory.Primary;

599
Apex Reference Guide ActionLinks Class

// To Do: Verify that the date is in the future.


// Action link groups are removed from feed elements on the expiration date.
datetime myDate = datetime.newInstance(2016, 3, 1);
actionLinkGroupDefinitionInput.expirationDate = myDate;

// Create the action link definition.


actionLinkDefinitionInput.actionType = ConnectApi.ActionLinkType.Api;
actionLinkDefinitionInput.actionUrl = '/services/data/v33.0/chatter/feed-elements';
actionLinkDefinitionInput.headers = new List<ConnectApi.RequestHeaderInput>();
actionLinkDefinitionInput.labelKey = 'Post';
actionLinkDefinitionInput.method = ConnectApi.HttpRequestMethod.HttpPost;
actionLinkDefinitionInput.requestBody = '{\"subjectId\": \"me\",\"feedElementType\":
\"FeedItem\",\"body\": {\"messageSegments\": [{\"type\": \"Text\",\"text\": \"This is a
test post created via an API action link.\"}]}}';
actionLinkDefinitionInput.requiresConfirmation = true;

// To Do: Substitute an OAuth value for your Salesforce org.


requestHeaderInput1.name = 'Authorization';
requestHeaderInput1.value = 'OAuth
00DD00000007WNP!ARsAQCwoeV0zzAV847FTl4zF.85w.EwsPbUgXR4SAjsp';
actionLinkDefinitionInput.headers.add(requestHeaderInput1);

requestHeaderInput2.name = 'Content-Type';
requestHeaderInput2.value = 'application/json';
actionLinkDefinitionInput.headers.add(requestHeaderInput2);

// Add the action link definition to the action link group definition.
actionLinkGroupDefinitionInput.actionLinks.add(actionLinkDefinitionInput);

// Instantiate the action link group definition.


ConnectApi.ActionLinkGroupDefinition actionLinkGroupDefinition =
ConnectApi.ActionLinks.createActionLinkGroupDefinition(Network.getNetworkId(),
actionLinkGroupDefinitionInput);

ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();


ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new
ConnectApi.FeedElementCapabilitiesInput();
ConnectApi.AssociatedActionsCapabilityInput associatedActionsCapabilityInput = new
ConnectApi.AssociatedActionsCapabilityInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

// Set the properties of the feedItemInput object.


feedItemInput.body = messageBodyInput;
feedItemInput.capabilities = feedElementCapabilitiesInput;
feedItemInput.subjectId = 'me';

// Create the text for the post.


messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
textSegmentInput.text = 'Click to post a feed item.';
messageBodyInput.messageSegments.add(textSegmentInput);

// The feedElementCapabilitiesInput object holds the capabilities of the feed item.

600
Apex Reference Guide ActionLinks Class

// Define an associated actions capability to hold the action link group.


// The action link group ID is returned from the call to create the action link group
definition.
feedElementCapabilitiesInput.associatedActions = associatedActionsCapabilityInput;
associatedActionsCapabilityInput.actionLinkGroupIds = new List<String>();
associatedActionsCapabilityInput.actionLinkGroupIds.add(actionLinkGroupDefinition.id);

// Post the feed item.


ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);

Example for Defining an Action Link in a Template and Posting with a Feed Element
For more information about this example, see Define an Action Link in a Template and Post with a Feed Element.
// Get the action link group template Id.
ActionLinkGroupTemplate template = [SELECT Id FROM ActionLinkGroupTemplate WHERE
DeveloperName='Doc_Example'];

// Add binding name-value pairs to a map.


// The names are defined in the action link template(s) associated with the action link
group template.
// Get them from Setup UI or SOQL.
Map<String, String> bindingMap = new Map<String, String>();
bindingMap.put('ApiVersion', 'v33.0');
bindingMap.put('Text', 'This post was created by an API action link.');
bindingMap.put('SubjectId', 'me');

// Create ActionLinkTemplateBindingInput objects from the map elements.


List<ConnectApi.ActionLinkTemplateBindingInput> bindingInputs = new
List<ConnectApi.ActionLinkTemplateBindingInput>();

for (String key : bindingMap.keySet()) {


ConnectApi.ActionLinkTemplateBindingInput bindingInput = new
ConnectApi.ActionLinkTemplateBindingInput();
bindingInput.key = key;
bindingInput.value = bindingMap.get(key);
bindingInputs.add(bindingInput);
}

// Set the template Id and template binding values in the action link group definition.
ConnectApi.ActionLinkGroupDefinitionInput actionLinkGroupDefinitionInput = new
ConnectApi.ActionLinkGroupDefinitionInput();
actionLinkGroupDefinitionInput.templateId = template.id;
actionLinkGroupDefinitionInput.templateBindings = bindingInputs;

// Instantiate the action link group definition.


ConnectApi.ActionLinkGroupDefinition actionLinkGroupDefinition =
ConnectApi.ActionLinks.createActionLinkGroupDefinition(Network.getNetworkId(),
actionLinkGroupDefinitionInput);

ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();


ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new
ConnectApi.FeedElementCapabilitiesInput();

601
Apex Reference Guide ActionLinks Class

ConnectApi.AssociatedActionsCapabilityInput associatedActionsCapabilityInput = new


ConnectApi.AssociatedActionsCapabilityInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

// Define the FeedItemInput object to pass to postFeedElement


feedItemInput.body = messageBodyInput;
feedItemInput.capabilities = feedElementCapabilitiesInput;
feedItemInput.subjectId = 'me';

// The MessageBodyInput object holds the text in the post


messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

textSegmentInput.text = 'Click to post a feed item.';


messageBodyInput.messageSegments.add(textSegmentInput);

// The FeedElementCapabilitiesInput object holds the capabilities of the feed item.


// For this feed item, we define an associated actions capability to hold the action link
group.
// The action link group ID is returned from the call to create the action link group
definition.
feedElementCapabilitiesInput.associatedActions = associatedActionsCapabilityInput;
associatedActionsCapabilityInput.actionLinkGroupIds = new List<String>();
associatedActionsCapabilityInput.actionLinkGroupIds.add(actionLinkGroupDefinition.id);

// Post the feed item.


ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);

deleteActionLinkGroupDefinition(communityId, actionLinkGroupId)
Delete an action link group definition. Deleting an action link group definition removes all references to it from feed elements.

API Version
33.0

Requires Chatter
No

Signature
public static void deleteActionLinkGroupDefinition(String communityId, String
actionLinkGroupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

602
Apex Reference Guide ActionLinks Class

actionLinkGroupId
Type: String
The ID of the action link group.

Return Value
Type: Void

Usage
Information in the action link group definition can be sensitive to a third party (for example, OAuth bearer token headers). For this reason,
only calls made from the Apex namespace that created the action link group definition can read, modify, or delete the definition. In
addition, the user making the call must have created the definition or have View All Data permission.

getActionLink(communityId, actionLinkId)
Get information about an action link, including state for the context user.

API Version
33.0

Requires Chatter
No

Signature
public static ConnectApi.PlatformAction getActionLink(String communityId, String
actionLinkId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
actionLinkId
Type: String
The ID of the action link.

Return Value
Type: ConnectApi.PlatformAction

getActionLinkDiagnosticInfo(communityId, actionLinkId)
Get diagnostic information returned when an action link executes. Diagnostic information is given only for users who can access the
action link.

603
Apex Reference Guide ActionLinks Class

API Version
33.0

Requires Chatter
No

Signature
public static ConnectApi.ActionLinkDiagnosticInfo getActionLinkDiagnosticInfo(String
communityId, String actionLinkId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
actionLinkId
Type: String
The ID of the action link.

Return Value
Type: ConnectApi.ActionLinkDiagnosticInfo

getActionLinkGroup(communityId, actionLinkGroupId)
Get information about an action link group including state for the context user.

API Version
33.0

Requires Chatter
No

Signature
public static ConnectApi.PlatformActionGroup getActionLinkGroup(String communityId,
String actionLinkGroupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

604
Apex Reference Guide ActionLinks Class

actionLinkGroupId
Type: String
The ID of the action link group.

Return Value
Type: ConnectApi.PlatformActionGroup

Usage
All action links must belong to a group. Action links in a group are mutually exclusive and share some properties. Action link groups are
accessible by clients, unlike action link group definitions.

getActionLinkGroupDefinition(communityId, actionLinkGroupId)
Get information about an action link group definition.

API Version
33.0

Requires Chatter
No

Signature
public static ConnectApi.ActionLinkGroupDefinition getActionLinkGroupDefinition(String
communityId, String actionLinkGroupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
actionLinkGroupId
Type: String
The ID of the action link group.

Return Value
Type: ConnectApi.ActionLinkGroupDefinition

Usage
Information in the action link group definition can be sensitive to a third party (for example, OAuth bearer token headers). For this reason,
only calls made from the Apex namespace that created the action link group definition can read, modify, or delete the definition. In
addition, the user making the call must have created the definition or have View All Data permission.

605
Apex Reference Guide Announcements Class

Announcements Class
Access information about announcements and post announcements.

Namespace
ConnectApi

Usage
Use the ConnectApi.Announcements class to get, create, update, and delete announcements. Use an announcement to
highlight information. Users can discuss, like, and post comments on announcements. Deleting the feed post deletes the announcement.
This image shows an announcement displayed in a group. Creating an announcement also creates a feed item with the announcement
text.

An announcement displays in a designated location in the Salesforce UI until 11:59 p.m. on its expiration date, unless it’s deleted or
replaced by another announcement.

Announcements Methods
These methods are for Announcements. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

IN THIS SECTION:
deleteAnnouncement(communityId, announcementId)
Delete an announcement.
getAnnouncement(communityId, announcementId)
Get an announcement.

606
Apex Reference Guide Announcements Class

getAnnouncements(communityId, parentId)
Get the first page of announcements.
getAnnouncements(communityId, parentId, pageParam, pageSize)
Get a page of announcements.
postAnnouncement(communityId, announcement)
Post an announcement.
updateAnnouncement(communityId, announcementId, expirationDate)
Update the expiration date of an announcement.

deleteAnnouncement(communityId, announcementId)
Delete an announcement.

API Version
31.0

Requires Chatter
Yes

Signature
public static void deleteAnnouncement(String communityId, String announcementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
announcementId
Type: String
An announcement ID, which has a prefix of 0BT.

Return Value
Type: Void

Usage
To get a list of announcements in a group, call getAnnouncements(communityId, parentId) or
getAnnouncements(communityId, parentId, pageParam, pageSize).
To post an announcement to a group, call postAnnouncement(communityId, announcement) .

getAnnouncement(communityId, announcementId)
Get an announcement.

607
Apex Reference Guide Announcements Class

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.Announcement getAnnouncement(String communityId, String
announcementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
announcementId
Type: String
An announcement ID, which has a prefix of 0BT.

Return Value
Type: ConnectApi.Announcement

Usage
To get a list of announcements in a group, call getAnnouncements(communityId, parentId) or
getAnnouncements(communityId, parentId, pageParam, pageSize).
To post an announcement to a group, call postAnnouncement(communityId, announcement) .

getAnnouncements(communityId, parentId)
Get the first page of announcements.

API Version
36.0

Available to Guest Users


38.0

Requires Chatter
Yes

608
Apex Reference Guide Announcements Class

Signature
public static ConnectApi.AnnouncementPage getAnnouncements(String communityId, String
parentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
parentId
Type: String
ID of the parent entity for the announcement, that is, a group ID when the announcement appears in a group.

Return Value
Type: ConnectApi.AnnouncementPage

getAnnouncements(communityId, parentId, pageParam, pageSize)


Get a page of announcements.

API Version
36.0

Available to Guest Users


38.0

Requires Chatter
Yes

Signature
public static ConnectApi.AnnouncementPage getAnnouncements(String communityId, String
parentId, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
parentId
Type: String
ID of the parent entity for the announcement, that is, a group ID when the announcement appears in a group.
pageParam
Type: Integer

609
Apex Reference Guide Announcements Class

Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of announcements per page.

Return Value
Type: ConnectApi.AnnouncementPage

postAnnouncement(communityId, announcement)
Post an announcement.

API Version
36.0

Requires Chatter
Yes

Signature
public static ConnectApi.Announcement postAnnouncement(String communityId,
ConnectApi.AnnouncementInput announcement)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
announcement
Type: ConnectApi.AnnouncementInput
A ConnectApi.AnnouncementInput object.

Return Value
Type: ConnectApi.Announcement

updateAnnouncement(communityId, announcementId, expirationDate)


Update the expiration date of an announcement.

API Version
31.0

610
Apex Reference Guide BotVersionActivation Class

Requires Chatter
Yes

Signature
public static ConnectApi.Announcement updateAnnouncement(String communityId, String
announcementId, Datetime expirationDate)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
announcementId
Type: String
An announcement ID, which has a prefix of 0BT.
expirationDate
Type: Datetime
The Salesforce UI displays an announcement until 11:59 p.m. on this date unless another announcement is posted first. The Salesforce
UI ignores the time value in the expirationDate. However, you can use the time value to create your own display logic in your
own UI.

Return Value
Type: ConnectApi.Announcement

Usage
To get a list of announcements in a group, call getAnnouncements(communityId, parentId) or
getAnnouncements(communityId, parentId, pageParam, pageSize).
To post an announcement to a group, call postAnnouncement(communityId, announcement) .

BotVersionActivation Class
Access and update activation information of a bot version.

Namespace
ConnectApi

BotVersionActivation Methods
These methods are for BotVersionActivation. All methods are static.

611
Apex Reference Guide BotVersionActivation Class

IN THIS SECTION:
getVersionActivationInfo(botVersionId)
Get the active or inactive status of the bot version.
updateVersionStatus(botVersionId, status, postBody)
Update the status of the specified bot version.

getVersionActivationInfo(botVersionId)
Get the active or inactive status of the bot version.

API Version
50.0

Requires Chatter
No

Signature
public static ConnectApi.BotVersionActivationInfo getVersionActivationInfo(String
botVersionId)

Parameters
botVersionId
Type: String
ID of the bot version.

Return Value
Type: ConnectApi.BotVersionActivationInfo

Usage
To access this method, enable the bot feature, and the user must be an admin or have the Manage Bots or Manage Bots Training Data
user permissions.

updateVersionStatus(botVersionId, status, postBody)


Update the status of the specified bot version.

API Version
50.0

Requires Chatter
No

612
Apex Reference Guide CdpActivation Class

Signature
public static ConnectApi.BotVersionActivationInfo updateVersionStatus(String
botVersionId, ConnectApi.BotVersionActivationStatus status,
ConnectApi.BotVersionActivationInput postBody)

Parameters
botVersionId
Type: String
ID of the bot version.
status
Type: ConnectApi.BotVersionActivationStatus
Activation status of the bot version. Values are:
• Active
• Inactive
Activation status must be specified in the status or postBody parameter.
postBody
Type: ConnectApi.BotVersionActivationInput
Parameters to update for the bot version. Activation status must be specified in the status or postBody parameter.

Return Value
Type: ConnectApi.BotVersionActivationInfo

Usage
To access this method, enable the bot feature, and the user must be an admin or have the Manage Bots or Manage Bots Training Data
user permissions.

CdpActivation Class
Get, create, update, and delete Data Cloud activations.

Namespace
ConnectApi

CdpActivation Methods
These methods are for CdpActivation. All methods are static.

IN THIS SECTION:
getActivations()
Get activations.

613
Apex Reference Guide CdpActivation Class

getActivationsPaginated(batchSize, offset, orderBy, filters)


Get a paginated list of activations.
createActivation(input)
Create an activation.
deleteActivation(activationId)
Delete an activation.
getActivation(activationId)
Get an activation by ID.
updateActivation(activationId, input)
Update an activation by ID.

getActivations()
Get activations.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.ActivationCollection getActivations()

Return Value
Type: ConnectApi.ActivationCollection

getActivationsPaginated(batchSize, offset, orderBy, filters)


Get a paginated list of activations.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.ActivationCollection getActivationsPaginated(Integer batchSize,
Integer offset, String orderBy, String filters)

614
Apex Reference Guide CdpActivation Class

Parameters
batchSize
Type: Integer
Number of results to return. Values are from 1 through 200. If unspecified, the default value is 20.
offset
Type: Integer
Number of rows to skip before returning results. Must be greater than or equal to 0. If unspecified, no rows are skipped.
orderBy
Type: String
Specify createdDate to sort results by creation date. If unspecified, items are returned by ID in ascending order.
filters
Type: String
Filter the result set to a more narrow scope or specific type. These filters are supported:
• name (field name: name; description: name of the activation)
• marketSegmentId (field name: segmentId; description: segment ID of the activation)
• activationTargetId (field name: activationTarget.id; description: activation target ID of the activation)
• activationRefreshType (field name: refreshType; description: refresh type of the activation; example: incremental)
• activationStatus (field name: status; description: status of the activation, which accepts only the values in the status response
field; example: active)

Return Value
Type: ConnectApi.ActivationCollection

createActivation(input)
Create an activation.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.Activation createActivation(ConnectApi.ActivationDefinitionInput
input)

Parameters
input
Type: ConnectApi.ActivationDefinitionInput
Input representation for an activation.

615
Apex Reference Guide CdpActivation Class

Return Value
Type: ConnectApi.Activation

deleteActivation(activationId)
Delete an activation.

Note: Before deleting an activation, ensure there are no downstream systems that expect data from it. After you delete an
activation, Data Cloud stops sending data to any downstream systems that are associated with the deleted activation. To identify
the downstream system (activation target) that's associated with the activation, use the getActivation(activationId) resource. It
provides the activation target details needed to evaluate the impact before deleting the activation.

API Version
60.0

Requires Chatter
No

Signature
public static Void deleteActivation(String activationId)

Parameters
activationId
Type: String
The unique identifier (ID) or developer name of a specific activation target.

Return Value
Type: Void

getActivation(activationId)
Get an activation by ID.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.Activation getActivation(String activationId)

616
Apex Reference Guide CdpActivationTarget Class

Parameters
activationId
Type: String
The unique identifier (ID) or developer name of a specific activation target.

Return Value
Type: ConnectApi.Activation

updateActivation(activationId, input)
Update an activation by ID.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.Activation updateActivation(String activationId,
ConnectApi.ActivationDefinitionInput input)

Parameters
activationId
Type: String
The unique identifier (ID) or developer name of a specific activation target.
input
Type: ConnectApi.ActivationDefinitionInput
Input representation for an activation.

Return Value
Type: ConnectApi.Activation

CdpActivationTarget Class
Get, create, and update Data Cloud activation targets.

Namespace
ConnectApi

617
Apex Reference Guide CdpActivationTarget Class

CdpActivationTarget Methods
These methods are for CdpActivationTarget. All methods are static.

IN THIS SECTION:
createActivationTarget(input)
Create an activation target.
getActivationTarget(activationTargetId)
Get an activation target by ID.
getActivationTargets()
Get a list of activation targets.
getActivationTargetsPaginated(batchSize, offset, orderBy, filters)
Get a paginated list of activation targets.
updateActivationTarget(activationTargetId, input)
Update an activation target.

createActivationTarget(input)
Create an activation target.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.ActivationTarget
createActivationTarget(ConnectApi.ActivationTargetInput input)

Parameters
input
Type: ConnectApi.ActivationTargetInput
Input details for the activation target.

Return Value
Type: ConnectApi.ActivationTarget

getActivationTarget(activationTargetId)
Get an activation target by ID.

618
Apex Reference Guide CdpActivationTarget Class

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.ActivationTarget getActivationTarget(String activationTargetId)

Parameters
activationTargetId
Type: String
ID of the activation target.

Return Value
Type: ConnectApi.ActivationTarget

getActivationTargets()
Get a list of activation targets.

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.ActivationTargetCollection getActivationTargets()

Return Value
Type: ConnectApi.ActivationTargetCollection

getActivationTargetsPaginated(batchSize, offset, orderBy, filters)


Get a paginated list of activation targets.

API Version
60.0

619
Apex Reference Guide CdpActivationTarget Class

Requires Chatter
No

Signature
public static ConnectApi.ActivationTargetCollection getActivationTargetsPaginated(Integer
batchSize, Integer offset, String orderBy, String filters)

Parameters
batchSize
Type: Integer
Number of results to return. Values are from 1 through 200. For example, specify 20 to return 20 results.
offset
Type: Integer
Number of rows to skip before returning results. Must be greater than or equal to 0. For example, specify 0 to skip no rows.
orderBy
Type: String
Sort order for the result set. Results are ordered by creation date. Specify createddate to order results in ascending order. Specify
createddate desc to order results in descending order.
filters
Type: String
Filter the result set to a more narrow scope or specific type. These filters are supported:
• masterLabel - Matches the field name, which is a string that identifies the name of the activation target.
• targetStatus - Matches the field status, which is an enum that indicates the status of the activation target. Values must
match those listed in the status response field.
• connectionType - Matches the field platformType, which is an enum that indicates the platform type of the activation
target. Values must match those listed in the platformType response field.
• platformName - Matches the field platformName, which is a string that indentifies the platform name of the activation
target.
These are examples of filter specifications:
• masterLabel in Target002
• targetStatus in active
• platformName in Customer Data Platform
• targetStatus in active AND platformName in Amazon S3

Return Value
Type: ConnectApi.ActivationTargetCollection

updateActivationTarget(activationTargetId, input)
Update an activation target.

620
Apex Reference Guide CdpAudienceDMO Class

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.ActivationTarget updateActivationTarget(String
activationTargetId, ConnectApi.ActivationTargetInput input)

Parameters
activationTargetId
Type: String
ID of the activation target.
input
Type: ConnectApi.ActivationTargetInput
Input details for the activation target.

Return Value
Type: ConnectApi.ActivationTarget

CdpAudienceDMO Class
Get activation records from Data Cloud Audience Data Model Objects (DMOs).

Namespace
ConnectApi

CdpAudienceDMO Methods
These methods are for CdpAudienceDMO. All methods are static.

IN THIS SECTION:
getActivationData(activationId)
Get a list of all activation records from Audience Data Model Objects (DMOs).

getActivationData(activationId)
Get a list of all activation records from Audience Data Model Objects (DMOs).

621
Apex Reference Guide CdpCalculatedInsight Class

API Version
60.0

Requires Chatter
No

Signature
public static ConnectApi.AudienceDMOCollection getActivationData(String activationId)

Parameters
activationId
Type: String
The unique identifier (ID) or developer name of a specific activation target.

Return Value
Type: ConnectApi.AudienceDMOCollection

CdpCalculatedInsight Class
Create, delete, get, run, and update Data Cloud calculated insights.

Namespace
ConnectApi

CdpCalculatedInsight Methods
These methods are for CdpCalculatedInsight. All methods are static.

IN THIS SECTION:
createCalculatedInsight(input)
Create a calculated insight.
deleteCalculatedInsight(apiName)
Delete a calculated insight.
getCalculatedInsight(apiName)
Get a calculated insight.
getCalculatedInsights(definitionType, batchSize, offset, orderby, dataspace)
Get calculated insights.
getCalculatedInsights(definitionType, batchSize, offset, orderby, dataspace, pageToken)
Get a page of calculated insights.

622
Apex Reference Guide CdpCalculatedInsight Class

runCalculatedInsight(apiName)
Run a calculated insight.
updateCalculatedInsight(apiName, input)
Update a calculated insight.

createCalculatedInsight(input)
Create a calculated insight.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpCalculatedInsightOutput
createCalculatedInsight(ConnectApi.CdpCalculatedInsightInput input)

Parameters
input
Type: ConnectApi.CdpCalculatedInsightInput
Input representation for a calculated insight.

Return Value
Type: ConnectApi.CdpCalculatedInsightOutput

deleteCalculatedInsight(apiName)
Delete a calculated insight.

API Version
57.0

Requires Chatter
No

Signature
public static Void deleteCalculatedInsight(String apiName)

623
Apex Reference Guide CdpCalculatedInsight Class

Parameters
apiName
Type: String
API name of the calculated insight to delete.

Return Value
Type: Void

getCalculatedInsight(apiName)
Get a calculated insight.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpCalculatedInsightOutput getCalculatedInsight(String apiName)

Parameters
apiName
Type: String
API name of the calculated insight to get.

Return Value
Type: ConnectApi.CdpCalculatedInsightOutput

getCalculatedInsights(definitionType, batchSize, offset, orderby, dataspace)


Get calculated insights.

API Version
56.0

Requires Chatter
No

624
Apex Reference Guide CdpCalculatedInsight Class

Signature
public static ConnectApi.CdpCalculatedInsightPage getCalculatedInsights(String
definitionType, Integer batchSize, Integer offset, String orderby, String dataspace)

Parameters
definitionType
Type: String
Definition type of the calculated insight. Values are:
• CALCULATED_METRIC
• CALCULATED_METRIC
• CALCULATED_METRIC
batchSize
Type: Integer
Number of items to return. Values are from 1–200. If unspecified, the default value is 25.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
dataspace
Type: String
Name of the data space.

Return Value
Type: ConnectApi.CdpCalculatedInsightPage

getCalculatedInsights(definitionType, batchSize, offset, orderby, dataspace,


pageToken)
Get a page of calculated insights.

API Version
57.0

Requires Chatter
No

625
Apex Reference Guide CdpCalculatedInsight Class

Signature
public static ConnectApi.CdpCalculatedInsightPage getCalculatedInsights(String
definitionType, Integer batchSize, Integer offset, String orderby, String dataspace,
String pageToken)

Parameters
definitionType
Type: String
Definition type of the calculated insight. Values are:
• CALCULATED_METRIC
• CALCULATED_METRIC
• CALCULATED_METRIC
batchSize
Type: Integer
Number of items to return. Values are from 1–200. If unspecified, the default value is 25.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
dataspace
Type: String
Name of the data space.
pageToken
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.

Return Value
Type: ConnectApi.CdpCalculatedInsightPage

runCalculatedInsight(apiName)
Run a calculated insight.

API Version
57.0

626
Apex Reference Guide CdpCalculatedInsight Class

Requires Chatter
No

Signature
public static ConnectApi.CdpCalculatedInsightStandardActionesponseRepresentation
runCalculatedInsight(String apiName)

Parameters
apiName
Type: String
API name of the calculated insight to run.

Return Value
Type: ConnectApi.CdpCalculatedInsightStandardActionResponseRepresentation

updateCalculatedInsight(apiName, input)
Update a calculated insight.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpCalculatedInsightOutput updateCalculatedInsight(String
apiName, ConnectApi.CdpCalculatedInsightInput input)

Parameters
apiName
Type: String
API name of the calculated insight to update.
input
Type: ConnectApi.CdpCalculatedInsightInput
Input representation for a calculated insight.

Return Value
Type: ConnectApi.CdpCalculatedInsightOutput

627
Apex Reference Guide CdpConnection Class

CdpConnection Class
Get database schemas for a Data Cloud connection.

Namespace
ConnectApi

CdpConnection Methods
These methods are for CdpConnection. All methods are static.

IN THIS SECTION:
getDatabaseSchemas(connectionId, getDatabaseSchemasInput)
Get a list of database schemas for a connection.

getDatabaseSchemas(connectionId, getDatabaseSchemasInput)
Get a list of database schemas for a connection.

API Version
63.0

Requires Chatter
No

Signature
public static ConnectApi.ConnectionDbSchemaCollection getDatabaseSchemas(String
connectionId, ConnectApi.ConnectionDbSchemaCollectionInputRepresentation
getDatabaseSchemasInput)

Parameters
connectionId
Type: String
ID for the connection.
getDatabaseSchemasInput
Type: ConnectApi.ConnectionDbSchemaCollectionInputRepresentation
Input representation for a database schema collection.

Return Value
Type: ConnectApi.ConnectionDbSchemaCollection

628
Apex Reference Guide CdpDataSpace Class

CdpDataSpace Class
Get Data Cloud data spaces.

Namespace
ConnectApi

CdpDataSpace Methods
These methods are for CdpDataSpace. All methods are static.

IN THIS SECTION:
getAllDataSpaces(batchSize, offset, orderBy)
Get a collection of all data spaces that a user is assigned to.
getDataSpace(idOrName)
Get a data space by ID or API name.

getAllDataSpaces(batchSize, offset, orderBy)


Get a collection of all data spaces that a user is assigned to.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.DataSpaceCollectionRepresentation getAllDataSpaces(Integer
batchSize, Integer offset, String orderBy)

Parameters
batchSize
Type: Integer
Number of results to return in each response. Values are from 1 through 4999. For example, specify 50 to return 50 results.
offset
Type: Integer
Number of rows to skip before returning results. Must be greater than or equal to 0. For example, specify 0 to skip no rows.
orderBy
Type: String
Sort order for the result set. Results are ordered by ID. Specify id to order results in ascending order. Specify id desc to order
results in descending order.

629
Apex Reference Guide CdpDataStreams Class

Return Value
Type: ConnectApi.DataSpaceCollectionRepresentation

getDataSpace(idOrName)
Get a data space by ID or API name.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.DataSpaceInfoRepresentation getDataSpace(String idOrName)

Parameters
idOrName
Type: String
ID or API name of the data space.

Return Value
Type: ConnectApi.DataSpaceInfoRepresentation

CdpDataStreams Class
Run Data Cloud data streams.

Namespace
ConnectApi

CdpDataStreams Methods
These methods are for CdpDataStreams. All methods are static.

IN THIS SECTION:
runDataStream(recordIdOrDeveloperName, interactive)
Start a data stream run to read from a source and update a data lake object.

runDataStream(recordIdOrDeveloperName, interactive)
Start a data stream run to read from a source and update a data lake object.

630
Apex Reference Guide CdpIdentityResolution Class

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.DataStreamActionResponse runDataStream(String
recordIdOrDeveloperName, Boolean interactive)

Parameters
recordIdOrDeveloperName
Type: String
Record ID or developer name of the data stream.
interactive
Type: Boolean
Indicates whether to perform fast format conversion for the data stream (true) or not (false).

Return Value
Type: ConnectApi.DataStreamActionResponseOutput

CdpIdentityResolution Class
Create, delete, get, run, and update Data Cloud identity resolution rulesets.

Namespace
ConnectApi

CdpIdentityResolution Methods
These methods are for CdpIdentityResolution. All methods are static.

IN THIS SECTION:
createIdentityResolution(input)
Create an identity resolution ruleset.
deleteIdentityResolution(identityResolution)
Delete an identity resolution ruleset.
getIdentityResolution(identityResolution)
Get an identity resolution ruleset.
getIdentityResolutions()
Get identity resolution rulesets.

631
Apex Reference Guide CdpIdentityResolution Class

runIdentityResolutionNow(identityResolution, input)
Trigger an immediate identity resolution ruleset job run.
updateIdentityResolution(identityResolution, input)
Update an identity resolution ruleset.

createIdentityResolution(input)
Create an identity resolution ruleset.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpIdentityResolutionOutput
createIdentityResolution(ConnectApi.CdpIdentityResolutionConfigInput input)

Parameters
input
Type: ConnectApi.CdpIdentityResolutionConfigInput
Input representation for creating an identity resolution ruleset.

Return Value
Type: ConnectApi.CdpIdentityResolutionOutput

deleteIdentityResolution(identityResolution)
Delete an identity resolution ruleset.

API Version
57.0

Requires Chatter
No

Signature
public static Void deleteIdentityResolution(String identityResolution)

632
Apex Reference Guide CdpIdentityResolution Class

Parameters
identityResolution
Type: String
Developer name or ID of the ruleset.

Return Value
Type: Void

getIdentityResolution(identityResolution)
Get an identity resolution ruleset.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpIdentityResolutionOutput getIdentityResolution(String
identityResolution)

Parameters
identityResolution
Type: String
Developer name or ID of the ruleset.

Return Value
Type: ConnectApi.CdpIdentityResolutionOutput

getIdentityResolutions()
Get identity resolution rulesets.

API Version
57.0

Requires Chatter
No

633
Apex Reference Guide CdpIdentityResolution Class

Signature
public static ConnectApi.CdpIdentityResolutionsOutput getIdentityResolutions()

Return Value
Type: ConnectApi.CdpIdentityResolutionsOutput

runIdentityResolutionNow(identityResolution, input)
Trigger an immediate identity resolution ruleset job run.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpIdentityResolutionRunNowOutput
runIdentityResolutionNow(String identityResolution,
ConnectApi.CdpIdentityResolutionRunNowInput input)

Parameters
identityResolution
Type: String
Developer name of the ruleset.
input
Type: ConnectApi.CdpIdentityResolutionRunNowInput
Input representation for running an identity resolution ruleset job on demand.

Return Value
Type: ConnectApi.CdpIdentityResolutionRunNowOutput

updateIdentityResolution(identityResolution, input)
Update an identity resolution ruleset.

API Version
57.0

Requires Chatter
No

634
Apex Reference Guide CdpMachineLearning Class

Signature
public static ConnectApi.CdpIdentityResolutionOutput updateIdentityResolution(String
identityResolution, ConnectApi.CdpIdentityResolutionConfigPatchInput input)

Parameters
identityResolution
Type: String
Developer name or ID of the ruleset.
input
Type: ConnectApi.CdpIdentityResolutionConfigPatchInput
Input representation for updating an identity resolution ruleset.

Return Value
Type: ConnectApi.CdpIdentityResolutionOutput

CdpMachineLearning Class
Make a machine-learning prediction with Data Cloud.

Namespace
ConnectApi

CdpMachineLearning Methods
These methods are for CdpMachineLearning. All methods are static.

IN THIS SECTION:
predict(predict)
Make a prediction using a specified model and parameters. This request is synchronous.

predict(predict)
Make a prediction using a specified model and parameters. This request is synchronous.

API Version
59.0

Requires Chatter
No

635
Apex Reference Guide CdpQuery Class

Signature
public static ConnectApi.CdpMlPredictResult predict(ConnectApi.CdpMlBasePredictInput
predict)

Parameters
predict
Type: ConnectApi.CdpMlBasePredictInput
Input representation for a prediction.

Return Value
Type: ConnectApi.CdpMlPredictResult

CdpQuery Class
Get Data Cloud metadata and query data.

Namespace
ConnectApi

CdpQuery Methods
These methods are for CdpQuery. All methods are static.

IN THIS SECTION:
getAllMetadata()
Get all metadata, including Calculated Insights, Engagement, Profile, and other objects, as well as their relationships to other objects.
getAllMetadata(entityType, entityCategory, entityName)
Get all metadata, filtering for entity type, category, and name.
getAllMetadata(entityType, entityCategory, entityName, dataspace)
Get all metadata, filtering for entity type, category, name, and data space.
getInsightsMetadata()
Get Insight metadata, including Calculated Insight objects, their dimensions and measures.
getInsightsMetadata(ciName)
Get metadata for a Calculated Insight object. Metadata includes dimensions and measures.
getInsightsMetadata(ciName, dataspace)
Get metadata for a Calculated Insight object and specify the data space. Metadata includes dimensions and measures.
getProfileMetadata()
Get metadata for data model objects in the profile category, including Individual, Contact Point Email, Unified Individual, and Contact
Point Address objects. Metadata includes the objects, their fields, and category.

636
Apex Reference Guide CdpQuery Class

getProfileMetadata(dataModelName)
Get metadata for a data model object in the profile category, such as Individual, Contact Point Email, Unified Individual, and Contact
Point Address. Metadata includes the list of fields, data types, and indexes available for lookup.
getProfileMetadata(dataModelName, dataspace)
Get metadata for a data model object in the profile category, such as Individual, Contact Point Email, Unified Individual, and Contact
Point Address. Also, specify the data space. Metadata includes the list of fields, data types, and indexes available for lookup.
queryANSISql(input)
Synchronously query data across data model, lake, unified, and linked objects. This query returns up to 49,999 rows.
queryANSISql(input, batchSize, offset, orderby)
Synchronously query data across data model, lake, unified, and linked objects. Specify batch size, offset, and order of the results. This
query returns up to 49,999 rows.
queryANSISql(input, batchSize, offset, orderby, dataspace)
Synchronously query data across data model, lake, unified, and linked objects. Specify batch size, offset, order of the results, and data
space. This query returns up to 49,999 rows.
queryAnsiSqlV2(input)
Query data across data model, lake, unified, and linked objects.
queryAnsiSqlV2(input, dataspace)
Query data across data model, lake, unified, and linked objects. Also, specify the data space.
nextBatchAnsiSqlV2(nextBatchId)
Get the next batch of data across data model, lake, unified, and linked objects.
nextBatchAnsiSqlV2(nextBatchId, dataspace)
Get the next batch of data across data model, lake, unified, and linked objects. Also, specify the data space.
querySql(input)
Submit an SQL query request for execution and retrieve the first chunk of data.
querySql(input, dataspace)
Submit an SQL query request for execution and specify the data space.
querySql(input, workloadName, dataspace)
Submit an SQL query request for execution and specify the workload name and data space.
querySqlRows(queryId, offset, rowLimit)
Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the
offset and row limit. Results are available for up to 24 hours.
querySqlRows(queryId, offset, rowLimit, omitSchema)
Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the
offset and row limit. Also, specify whether to include metadata in the response or not. Results are available for up to 24 hours.
querySqlRows(queryId, offset, rowLimit, dataspace)
Get additional query results that weren’t returned in the initial request. Paginate through existing query results by specifying the
offset and row limit. Also, specify the data space. Results are available for up to 24 hours.
querySqlRows(queryId, offset, rowLimit, omitSchema, dataspace)
Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the
offset and row limit. Also, specify the data space and whether or not to exclude metadata from the response. Results are available
for up to 24 hours.

637
Apex Reference Guide CdpQuery Class

querySqlRows(queryId, offset, rowLimit, workloadName, dataspace)


Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the
offset and row limit. Also, specify the workload name and data space. Results are available for up to 24 hours.
querySqlRows(queryId, offset, rowLimit, omitSchema, workloadName, dataspace)
Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the
offset and row limit. Also, specify the workload name, data space, and whether or not to exclude metadata from the response. Results
are available for up to 24 hours.
cancelQuerySql(queryId)
Delete the specified query and terminate long-running queries that are no longer needed to manage resource consumption.
cancelQuerySql(queryId, dataspace)
Delete the specified query and terminate long-running queries that are no longer needed to manage resource consumption. Specify
the data space.
cancelQuerySql(queryId, workloadName, dataspace)
Delete the specified query and terminate long-running queries that are no longer needed to manage resource consumption. Specify
the data space and workload name.
querySqlStatus(queryId)
Get the status of an SQL query request. Results are available for up to 24 hours.
querySqlStatus(queryId, waitTimeMs)
Get the status of an SQL query request and specify the time to wait before returning the response. Results are available for up to 24
hours.
querySqlStatus(queryId, dataspace)
Get the status of an SQL query request and specify the data space. Results are available for up to 24 hours.
querySqlStatus(queryId, dataspace, waitTimeMs)
Get the status of an SQL query request. Specify the data space and time to wait before returning the response. Results are available
for up to 24 hours.
querySqlStatus(queryId, workloadName, dataspace)
Get the status of an SQL query request. Specify the workload name and data space. Results are available for up to 24 hours.
querySqlStatus(queryId, workloadName, dataspace, waitTimeMs)
Get the status of an SQL query request. Specify the workload name, data space, and time to wait before returning the response.
Results are available for up to 24 hours.
queryCalculatedInsights(ciName, dimensions, measures, orderby, filters, batchSize, offset)
Query a Calculated Insight object.
queryCalculatedInsights(ciName, dimensions, measures, orderby, filters, batchSize, offset, timeGranularity)
Query a Calculated Insight object within a specified time range.
queryCalculatedInsights(ciName, dimensions, measures, orderby, filters, batchSize, offset, timeGranularity, dataspace)
Query a Calculated Insight object within a specified time range and specify the data space.
queryProfileApi(dataModelName, filters, fields, batchSize, offset, orderby)
Query a Profile data model object using filters.
queryProfileApi(dataModelName, id, searchKey, filters, fields, batchSize, offset, orderby)
Query a Profile data model object using filters and a search key.
queryProfileApi(dataModelName, id, childDataModelName, searchKey, filters, fields, batchSize, offset, orderby)
Query a Profile data model object and a child object using filters and a search key.

638
Apex Reference Guide CdpQuery Class

queryProfileApi(dataModelName, id, ciName, searchKey, dimensions, measures, filters, fields, batchSize, offset, orderby)
Query a Profile data model object and a Calculated Insight object using filters and a search key.
queryProfileApi(dataModelName, id, ciName, searchKey, dimensions, measures, filters, fields, batchSize, offset, orderby, timeGranularity)
Query a Profile data model object and a Calculated Insight object using filters, a search key, and a time range.
queryProfileApi(dataModelName, id, ciName, searchKey, dimensions, measures, filters, fields, batchSize, offset, orderby, timeGranularity,
dataspace)
Query a Profile data model object and a Calculated Insight object using filters, a search key, a time range, and a data space.
universalIdLookupBySourceId(entityName, dataSourceId, dataSourceObjectId, sourceRecordId)
Look up objects by source ID.
universalIdLookupBySourceId(entityName, dataSourceId, dataSourceObjectId, sourceRecordId, dataspace)
Look up objects by source ID and specify the data space.

getAllMetadata()
Get all metadata, including Calculated Insights, Engagement, Profile, and other objects, as well as their relationships to other objects.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getAllMetadata()

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getAllMetadata(entityType, entityCategory, entityName)


Get all metadata, filtering for entity type, category, and name.

API Version
54.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getAllMetadata(String entityType, String
entityCategory, String entityName)

639
Apex Reference Guide CdpQuery Class

Parameters
entityType
Type: String
Type of metadata entity requested. Valid values are DataLakeObject, DataModelObject, and CalculatedInsight.
If unspecified, all types are returned.
entityCategory
Type: String
Category of the metadata entity. Valid values are Profile, Engagement, and Related. If unspecified, all category entities
are returned.
entityName
Type: String
Metadata name of the entity, for example UnifiedIndividual__dlm. If unspecified, a complete list of entities is returned.

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getAllMetadata(entityType, entityCategory, entityName, dataspace)


Get all metadata, filtering for entity type, category, name, and data space.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getAllMetadata(String entityType, String
entityCategory, String entityName, String dataspace)

Parameters
entityType
Type: String
Type of metadata entity requested. Valid values are DataLakeObject, DataModelObject, and CalculatedInsight.
If unspecified, all types are returned.
entityCategory
Type: String
Category of the metadata entity. Valid values are Profile, Engagement, and Related. If unspecified, all category entities
are returned.
entityName
Type: String

640
Apex Reference Guide CdpQuery Class

Metadata name of the entity, for example UnifiedIndividual__dlm. If unspecified, a complete list of entities is returned.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getInsightsMetadata()
Get Insight metadata, including Calculated Insight objects, their dimensions and measures.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getInsightsMetadata()

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getInsightsMetadata(ciName)
Get metadata for a Calculated Insight object. Metadata includes dimensions and measures.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getInsightsMetadata(String ciName)

Parameters
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.

641
Apex Reference Guide CdpQuery Class

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getInsightsMetadata(ciName, dataspace)
Get metadata for a Calculated Insight object and specify the data space. Metadata includes dimensions and measures.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getInsightsMetadata(String ciName,
String dataspace)

Parameters
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getProfileMetadata()
Get metadata for data model objects in the profile category, including Individual, Contact Point Email, Unified Individual, and Contact
Point Address objects. Metadata includes the objects, their fields, and category.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getProfileMetadata()

642
Apex Reference Guide CdpQuery Class

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getProfileMetadata(dataModelName)
Get metadata for a data model object in the profile category, such as Individual, Contact Point Email, Unified Individual, and Contact
Point Address. Metadata includes the list of fields, data types, and indexes available for lookup.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getProfileMetadata(String dataModelName)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

getProfileMetadata(dataModelName, dataspace)
Get metadata for a data model object in the profile category, such as Individual, Contact Point Email, Unified Individual, and Contact
Point Address. Also, specify the data space. Metadata includes the list of fields, data types, and indexes available for lookup.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryMetadataOutput getProfileMetadata(String dataModelName,
String dataspace)

643
Apex Reference Guide CdpQuery Class

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryMetadataOutput

queryANSISql(input)
Synchronously query data across data model, lake, unified, and linked objects. This query returns up to 49,999 rows.

Note: A newer version of the Query API is available. We recommend using queryAnsiSqlV2(input) and
nextBatchAnsiSqlV2(nextBatchId) to take advantage of subsequent requests and larger response sizes.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryANSISql(ConnectApi.CdpQueryInput input)

Parameters
input
Type: ConnectApi.CdpQueryInput
A ConnectApi.CdpQueryInput body with the SQL query.

Return Value
Type: ConnectApi.CdpQueryOutput

queryANSISql(input, batchSize, offset, orderby)


Synchronously query data across data model, lake, unified, and linked objects. Specify batch size, offset, and order of the results. This
query returns up to 49,999 rows.

Note: A newer version of the Query API is available. We recommend using queryAnsiSqlV2(input) and
nextBatchAnsiSqlV2(nextBatchId) to take advantage of subsequent requests and larger response sizes.

644
Apex Reference Guide CdpQuery Class

API Version
53.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryANSISql(ConnectApi.CdpQueryInput input,
Integer batchSize, Integer offset, String orderby)

Parameters
input
Type: ConnectApi.CdpQueryInput
A ConnectApi.CdpQueryInput body with the SQL query.
batchSize
Type: Integer
Number of records to return. Values are from 1-49999. The default value is 49999.
offset
Type: Integer
Number of rows to skip before returning results. The sum of offset and batchSize must be less than 2147483647. The
default value is 0.
orderby
Type: String
Comma-separated values to sort the results in ascending or descending order, for example, GenderId__c
ASC,Occupation__c DESC.

Return Value
Type: ConnectApi.CdpQueryOutput

queryANSISql(input, batchSize, offset, orderby, dataspace)


Synchronously query data across data model, lake, unified, and linked objects. Specify batch size, offset, order of the results, and data
space. This query returns up to 49,999 rows.

Note: A newer version of the Query API is available. We recommend using queryAnsiSqlV2(input) and
nextBatchAnsiSqlV2(nextBatchId) to take advantage of subsequent requests and larger response sizes.

API Version
57.0

Requires Chatter
No

645
Apex Reference Guide CdpQuery Class

Signature
public static ConnectApi.CdpQueryOutput queryANSISql(ConnectApi.CdpQueryInput input,
Integer batchSize, Integer offset, String orderby, String dataspace)

Parameters
input
Type: ConnectApi.CdpQueryInput
A ConnectApi.CdpQueryInput body with the SQL query.
batchSize
Type: Integer
Number of records to return. Values are from 1-49999. The default value is 49999.
offset
Type: Integer
Number of rows to skip before returning results. The sum of offset and batchSize must be less than 2147483647. The
default value is 0.
orderby
Type: String
Comma-separated values to sort the results in ascending or descending order, for example, GenderId__c
ASC,Occupation__c DESC.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryOutput

queryAnsiSqlV2(input)
Query data across data model, lake, unified, and linked objects.

API Version
54.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutputV2 queryAnsiSqlV2(ConnectApi.CdpQueryInput input)

646
Apex Reference Guide CdpQuery Class

Parameters
input
Type: ConnectApi.CdpQueryInput
A ConnectApi.CdpQueryInput body with the SQL query.

Return Value
Type: ConnectApi.CdpQueryOutputV2

Usage
Use the nextBatchId in the ConnectApi.CdpQueryOutputV2 output class as the nextBatchId parameter in the
nextBatchAnsiSqlV2(nextBatchId) method to continue getting batches of data for up to an hour.

queryAnsiSqlV2(input, dataspace)
Query data across data model, lake, unified, and linked objects. Also, specify the data space.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutputV2 queryAnsiSqlV2(ConnectApi.CdpQueryInput input,
String dataspace)

Parameters
input
Type: ConnectApi.CdpQueryInput
A ConnectApi.CdpQueryInput body with the SQL query.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryOutputV2

Usage
Use the nextBatchId in the ConnectApi.CdpQueryOutputV2 output class as the nextBatchId parameter in the
nextBatchAnsiSqlV2(nextBatchId) method to continue getting batches of data for up to an hour.

647
Apex Reference Guide CdpQuery Class

nextBatchAnsiSqlV2(nextBatchId)
Get the next batch of data across data model, lake, unified, and linked objects.

API Version
54.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutputV2 nextBatchAnsiSqlV2(String nextBatchId)

Parameters
nextBatchId
Type: String
ID of the next batch. See the Usage section for more information.

Return Value
Type: ConnectApi.CdpQueryOutputV2

Usage
Initially, use the queryAnsiSqlV2(input) method to query up to 8 MB of data. Use the nextBatchId from the
ConnectApi.CdpQueryOutputV2 output class as the nextBatchId parameter in this method to get the next batch of
data. You can continue using subsequent next batch IDs for up to an hour.

nextBatchAnsiSqlV2(nextBatchId, dataspace)
Get the next batch of data across data model, lake, unified, and linked objects. Also, specify the data space.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutputV2 nextBatchAnsiSqlV2(String nextBatchId, String
dataspace)

648
Apex Reference Guide CdpQuery Class

Parameters
nextBatchId
Type: String
ID of the next batch. See the Usage section for more information.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryOutputV2

Usage
Initially, use the queryAnsiSqlV2(input) method to query up to 8 MB of data. Use the nextBatchId from the
ConnectApi.CdpQueryOutputV2 output class as the nextBatchId parameter in this method to get the next batch of
data. You can continue using subsequent next batch IDs for up to an hour.

querySql(input)
Submit an SQL query request for execution and retrieve the first chunk of data.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlOutput querySql(ConnectApi.QuerySqlInput input)

Parameters
input
Type: ConnectApi.QuerySqlInput
Input representation for an SQL query.

Return Value
Type: ConnectApi.QuerySqlOutput

Usage
To get started with writing queries, see Write a Simple Query. For more information about creating SQL statements, see Data Cloud SQL
Syntax.

649
Apex Reference Guide CdpQuery Class

Example
Submit a query, check its status, then retrieve and process data in chunks until all results are fetched:
ConnectApi.QuerySqlInput query = new ConnectApi.QuerySqlInput();
query.sql = 'SELECT street_address__c FROM test__dll limit 200000';

Integer numProcessed = 0;
Long startTime = System.currentTimeMillis();
System.debug('Query execution started at: ' + startTime);

ConnectApi.QuerySqlOutput queryOutput = ConnectApi.CdpQuery.querySql(query,


'sample_workload', 'default');
ConnectApi.QuerySqlStatus status = queryOutput.status;

// Process chunks as they become available


while(status.completionStatus != ConnectApi.QuerySqlStatusEnum.FINISHED || numProcessed <
status.rowCount) {

// If we have unprocessed rows available, fetch and process them


if (status.rowCount > numProcessed) {
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(status.queryId, numProcessed, 10000, 'sample_workload',
'default');

// Process this chunk - inline max length calculation


Integer maxLength = 0;
for (ConnectApi.QuerySqlRow rowObj : pageOutput.dataRows) {
String streetAddress = (String) rowObj.row[0];
if (streetAddress.length() > maxLength) {
maxLength = streetAddress.length();
}
}

System.debug('Chunk - Rows: ' + pageOutput.dataRows.size() + ', Max street_address


length: ' + maxLength);
numProcessed += pageOutput.dataRows.size();

} else if (status.completionStatus != ConnectApi.QuerySqlStatusEnum.FINISHED) {


// No new rows available yet, wait a bit before checking status again
System.debug('Query in progress. Total rows available: ' + status.rowCount + ',
Processed: ' + numProcessed);

// Small delay to avoid excessive polling (adjust as needed)


// Note: In Apex, we can't use Thread.sleep(), so we'll just continue to next
iteration
}

// Update status if query is still running


if (status.completionStatus != ConnectApi.QuerySqlStatusEnum.FINISHED) {
status = ConnectApi.CdpQuery.querySqlStatus(status.queryId, 'sample_workload',
'default');
}
}

650
Apex Reference Guide CdpQuery Class

Long completionTime = System.currentTimeMillis();


System.debug('Query and processing completed at: ' + completionTime + ', Total time: ' +
(completionTime - startTime) + ' ms');
System.debug('Total rows processed: ' + numProcessed + ' out of ' + status.rowCount + '
total rows');

querySql(input, dataspace)
Submit an SQL query request for execution and specify the data space.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlOutput querySql(ConnectApi.QuerySqlInput input, String
dataspace)

Parameters
input
Type: ConnectApi.QuerySqlInput
Input representation for an SQL query.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlOutput

Usage
To get started with writing queries, see Write a Simple Query. For more information about creating SQL statements, see Data Cloud SQL
Syntax.

Example
Submit a query with a data space:
ConnectApi.QuerySqlInput input = new ConnectApi.QuerySqlInput();
input.sql = 'select * from "passenger2__dll"';

ConnectApi.QuerySqlOutput output = ConnectApi.CdpQuery.querySql(input, 'default');


System.debug(output);

651
Apex Reference Guide CdpQuery Class

System.debug(output.dataRows);
System.debug(output.metadata);
System.debug(output.status);
System.debug(output.returnedRows);

querySql(input, workloadName, dataspace)


Submit an SQL query request for execution and specify the workload name and data space.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlOutput querySql(ConnectApi.QuerySqlInput input, String
workloadName, String dataspace)

Parameters
input
Type: ConnectApi.QuerySqlInput
Input representation for an SQL query.
workloadName
Type: String
Description of the scenario, task, or application name that your query handles. Set this value to help Salesforce Customer Support
assist you with debugging issues.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlOutput

Usage
To get started with writing queries, see Write a Simple Query. For more information about creating SQL statements, see Data Cloud SQL
Syntax.

652
Apex Reference Guide CdpQuery Class

Example
Submit a query with a data space and workload name:
ConnectApi.QuerySqlInput input = new ConnectApi.QuerySqlInput();
input.sql = 'select * from "passenger2__dll"';

ConnectApi.QuerySqlOutput output = ConnectApi.CdpQuery.querySql(input, 'workloadName',


'default');
System.debug(output);

System.debug(output.dataRows);
System.debug(output.metadata);
System.debug(output.status);
System.debug(output.returnedRows);

querySqlRows(queryId, offset, rowLimit)


Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the offset
and row limit. Results are available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlPageOutput querySqlRows(String queryId, Long offset,
Long rowLimit)

Parameters
queryId
Type: String
ID from the initial query to retrieve more results, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
offset
Type: Long
Row number to start with when retrieving the next chunk of query results. Value must be less than the total number of available
rows. If unspecified, no rows are skipped.
rowLimit
Type: Long
Maximum number of rows to include in the response. Value must be greater than 0. Fewer rows may be returned.

653
Apex Reference Guide CdpQuery Class

Return Value
Type: ConnectApi.QuerySqlPageOutput

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Query additional rows with an offset and row limit:
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(output.status.queryId, 100, 200);
System.debug(pageOutput);
System.debug(pageOutput.dataRows);
System.debug(pageOutput.metadata);
System.debug(pageOutput.returnedRows);

querySqlRows(queryId, offset, rowLimit, omitSchema)


Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the offset
and row limit. Also, specify whether to include metadata in the response or not. Results are available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlPageOutput querySqlRows(String queryId, Long offset,
Long rowLimit, Boolean omitSchema)

Parameters
queryId
Type: String
ID from the initial query to retrieve more results, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
offset
Type: Long
Row number to start with when retrieving the next chunk of query results. Value must be less than the total number of available
rows. If unspecified, no rows are skipped.

654
Apex Reference Guide CdpQuery Class

rowLimit
Type: Long
Maximum number of rows to include in the response. Value be greater than 0. Fewer rows may be returned.
omitSchema
Type: Boolean
Indicates whether to exclude metadata from the response (true) or not (false). Omitting the schema reduces the amount of
data returned and improves performance.

Return Value
Type: ConnectApi.QuerySqlPageOutput

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Query additional rows with an offset, a row limit, and omitting the schema:
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(output.status.queryId, 100, 200, true);
System.debug(pageOutput);
System.debug(pageOutput.dataRows);
System.debug(pageOutput.metadata);
System.debug(pageOutput.returnedRows);

querySqlRows(queryId, offset, rowLimit, dataspace)


Get additional query results that weren’t returned in the initial request. Paginate through existing query results by specifying the offset
and row limit. Also, specify the data space. Results are available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlPageOutput querySqlRows(String queryId, Long offset,
Long rowLimit, String dataspace)

Parameters
queryId
Type: String

655
Apex Reference Guide CdpQuery Class

ID from the initial query to retrieve more results, for example


MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
offset
Type: Long
Row number to start with when retrieving the next chunk of query results. Value must be less than the total number of available
rows. If unspecified, no rows are skipped.
rowLimit
Type: Long
Maximum number of rows to include in the response. Value be greater than 0. Fewer rows may be returned.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlPageOutput

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Query additional rows with an offset, row limit, and data space:
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(output.status.queryId, 100, 200, 'default');
System.debug(pageOutput);
System.debug(pageOutput.dataRows);
System.debug(pageOutput.metadata);
System.debug(pageOutput.returnedRows);

querySqlRows(queryId, offset, rowLimit, omitSchema, dataspace)


Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the offset
and row limit. Also, specify the data space and whether or not to exclude metadata from the response. Results are available for up to 24
hours.

API Version
62.0

Requires Chatter
No

656
Apex Reference Guide CdpQuery Class

Signature
public static ConnectApi.QuerySqlPageOutput querySqlRows(String queryId, Long offset,
Long rowLimit, Boolean omitSchema, String dataspace)

Parameters
queryId
Type: String
ID from the initial query to retrieve more results, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
offset
Type: Long
Row number to start with when retrieving the next chunk of query results. Value must be less than the total number of available
rows. If unspecified, no rows are skipped.
rowLimit
Type: Long
Maximum number of rows to include in the response. Value be greater than 0. Fewer rows may be returned.
omitSchema
Type: Boolean
Indicates whether to exclude metadata from the response (true) or not (false). Omitting the schema reduces the amount of
data returned and improves performance.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlPageOutput

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Query additional rows with an offset, row limit, data space, and omitting the schema:
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(output.status.queryId, 100, 200, true, 'default');
System.debug(pageOutput);
System.debug(pageOutput.dataRows);
System.debug(pageOutput.metadata);
System.debug(pageOutput.returnedRows);

657
Apex Reference Guide CdpQuery Class

querySqlRows(queryId, offset, rowLimit, workloadName, dataspace)


Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the offset
and row limit. Also, specify the workload name and data space. Results are available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlPageOutput querySqlRows(String queryId, Long offset,
Long rowLimit, String workloadName, String dataspace)

Parameters
queryId
Type: String
ID from the initial query to retrieve more results, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
offset
Type: Long
Row number to start with when retrieving the next chunk of query results. Value must be less than the total number of available
rows. If unspecified, no rows are skipped.
rowLimit
Type: Long
Maximum number of rows to include in the response. Value be greater than 0. Fewer rows may be returned.
workloadName
Type: String
Description of the scenario, task, or application name that your query handles. Set this value to help Salesforce Customer Support
assist you with debugging issues.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlPageOutput

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

658
Apex Reference Guide CdpQuery Class

Example
Query additional rows with an offset, row limit, workload name, and data space:
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(output.status.queryId, 100, 200, 'workloadName', 'default');
System.debug(pageOutput);
System.debug(pageOutput.dataRows);
System.debug(pageOutput.metadata);
System.debug(pageOutput.returnedRows);

querySqlRows(queryId, offset, rowLimit, omitSchema, workloadName, dataspace)


Get additional query results that weren't returned in the initial request. Paginate through existing query results by specifying the offset
and row limit. Also, specify the workload name, data space, and whether or not to exclude metadata from the response. Results are
available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlPageOutput querySqlRows(String queryId, Long offset,
Long rowLimit, Boolean omitSchema, String workloadName, String dataspace)

Parameters
queryId
Type: String
ID from the initial query to retrieve more results, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
offset
Type: Long
Row number to start with when retrieving the next chunk of query results. Value must be less than the total number of available
rows. If unspecified, no rows are skipped.
rowLimit
Type: Long
Maximum number of rows to include in the response. Value be greater than 0. Fewer rows may be returned.
omitSchema
Type: Boolean
Indicates whether to exclude metadata from the response (true) or not (false). Omitting the schema reduces the amount of
data returned and improves performance.

659
Apex Reference Guide CdpQuery Class

workloadName
Type: String
Description of the scenario, task, or application name that your query handles. Set this value to help Salesforce Customer Support
assist you with debugging issues.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlPageOutput

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Query additional rows with an offset, row limit, workload name, data space, and omitting the schema:
ConnectApi.QuerySqlPageOutput pageOutput =
ConnectApi.CdpQuery.querySqlRows(output.status.queryId, 100, 200, true, 'workloadName',
'default');
System.debug(pageOutput);
System.debug(pageOutput.dataRows);
System.debug(pageOutput.metadata);
System.debug(pageOutput.returnedRows);

cancelQuerySql(queryId)
Delete the specified query and terminate long-running queries that are no longer needed to manage resource consumption.

API Version
62.0

Requires Chatter
No

Signature
public static Void cancelQuerySql(String queryId)

Parameters
queryId
Type: String

660
Apex Reference Guide CdpQuery Class

ID of the query to cancel, for example MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548.


The query ID is returned in the querySql response.

Return Value
Type: Void

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Cancel a query:
ConnectApi.CdpQuery.cancelQuerySql(output.status.queryId);
System.debug('done');

cancelQuerySql(queryId, dataspace)
Delete the specified query and terminate long-running queries that are no longer needed to manage resource consumption. Specify
the data space.

API Version
62.0

Requires Chatter
No

Signature
public static Void cancelQuerySql(String queryId, String dataspace)

Parameters
queryId
Type: String
ID of the query to cancel, for example MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548.
The query ID is returned in the querySql response.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: Void

661
Apex Reference Guide CdpQuery Class

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Cancel a query with a data space:
ConnectApi.CdpQuery.cancelQuerySql(output.status.queryId, 'default');
System.debug('done');

cancelQuerySql(queryId, workloadName, dataspace)


Delete the specified query and terminate long-running queries that are no longer needed to manage resource consumption. Specify
the data space and workload name.

API Version
62.0

Requires Chatter
No

Signature
public static Void cancelQuerySql(String queryId, String workloadName, String dataspace)

Parameters
queryId
Type: String
ID of the query to cancel, for example MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548.
The query ID is returned in the querySql response.
workloadName
Type: String
Description of the scenario, task, or application name that your query handles. Set this value to help Salesforce Customer Support
assist you with debugging issues.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: Void

662
Apex Reference Guide CdpQuery Class

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Cancel a query with a workload name and data space:
ConnectApi.CdpQuery.cancelQuerySql(output.status.queryId, 'workloadName', 'default');
System.debug('done');

querySqlStatus(queryId)
Get the status of an SQL query request. Results are available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlStatus querySqlStatus(String queryId)

Parameters
queryId
Type: String
ID of the query to return the status for, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.

Return Value
Type: ConnectApi.QuerySqlStatus

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Get the status of a query:
ConnectApi.QuerySqlStatus statusOutput =
ConnectApi.CdpQuery.querySqlStatus(output.status.queryId);
System.debug(statusOutput);

663
Apex Reference Guide CdpQuery Class

querySqlStatus(queryId, waitTimeMs)
Get the status of an SQL query request and specify the time to wait before returning the response. Results are available for up to 24
hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlStatus querySqlStatus(String queryId, Integer
waitTimeMs)

Parameters
queryId
Type: String
ID of the query to return the status for, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
waitTimeMs
Type: Integer
Maximum time (in milliseconds) to wait for the result. Configure a wait time up to 10 seconds before returning the status without
chunk information. If unspecified, the status is returned immediately. Use this to avoid resource limits by delaying requests.

Return Value
Type: ConnectApi.QuerySqlStatus

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Get the status of a query with wait time:
ConnectApi.QuerySqlStatus statusOutput =
ConnectApi.CdpQuery.querySqlStatus(output.status.queryId, 55);
System.debug(statusOutput);

querySqlStatus(queryId, dataspace)
Get the status of an SQL query request and specify the data space. Results are available for up to 24 hours.

664
Apex Reference Guide CdpQuery Class

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlStatus querySqlStatus(String queryId, String dataspace)

Parameters
queryId
Type: String
ID of the query to return the status for, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlStatus

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Get the status of a query with a data space:
ConnectApi.QuerySqlStatus statusOutput =
ConnectApi.CdpQuery.querySqlStatus(output.status.queryId, 'default');
System.debug(statusOutput);

querySqlStatus(queryId, dataspace, waitTimeMs)


Get the status of an SQL query request. Specify the data space and time to wait before returning the response. Results are available for
up to 24 hours.

API Version
62.0

665
Apex Reference Guide CdpQuery Class

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlStatus querySqlStatus(String queryId, String dataspace,
Integer waitTimeMs)

Parameters
queryId
Type: String
ID of the query to return the status for, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.
waitTimeMs
Type: Integer
Maximum time (in milliseconds) to wait for the result. Configure a wait time up to 10 seconds before returning the status without
chunk information. If unspecified, the status is returned immediately. Use this to avoid resource limits by delaying requests.

Return Value
Type: ConnectApi.QuerySqlStatus

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Get the status of a query with a data space and wait time:
ConnectApi.QuerySqlStatus statusOutput =
ConnectApi.CdpQuery.querySqlStatus(output.status.queryId, 'default', 100);
System.debug(statusOutput);

querySqlStatus(queryId, workloadName, dataspace)


Get the status of an SQL query request. Specify the workload name and data space. Results are available for up to 24 hours.

API Version
62.0

666
Apex Reference Guide CdpQuery Class

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlStatus querySqlStatus(String queryId, String
workloadName, String dataspace)

Parameters
queryId
Type: String
ID of the query to return the status for, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
workloadName
Type: String
Description of the scenario, task, or application name that your query handles. Set this value to help Salesforce Customer Support
assist you with debugging issues.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.QuerySqlStatus

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

Example
Get the status of a query with a workload name and data space:
ConnectApi.QuerySqlInput input = new ConnectApi.QuerySqlInput();
input.sql = 'select * from "passenger2__dll"';
ConnectApi.QuerySqlOutput output = ConnectApi.CdpQuery.querySql(input);
System.debug(output);

ConnectApi.QuerySqlStatus statusOutput =
ConnectApi.CdpQuery.querySqlStatus(output.status.queryId, 'workloadName', 'default');
System.debug(statusOutput);

667
Apex Reference Guide CdpQuery Class

querySqlStatus(queryId, workloadName, dataspace, waitTimeMs)


Get the status of an SQL query request. Specify the workload name, data space, and time to wait before returning the response. Results
are available for up to 24 hours.

API Version
62.0

Requires Chatter
No

Signature
public static ConnectApi.QuerySqlStatus querySqlStatus(String queryId, String
workloadName, String dataspace, Integer waitTimeMs)

Parameters
queryId
Type: String
ID of the query to return the status for, for example
MTAuMjMuMTU2LjIwODo3NDg0_49169cf8-a6f4-738f-6544-c3a7ba2ff548. The query ID is returned in the
querySql response.
workloadName
Type: String
Description of the scenario, task, or application name that your query handles. Set this value to help Salesforce Customer Support
assist you with debugging issues.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.
waitTimeMs
Type: Integer
Maximum time (in milliseconds) to wait for the result. Configure a wait time up to 10 seconds before returning the status without
chunk information. If unspecified, the status is returned immediately. Use this to avoid resource limits by delaying requests.

Return Value
Type: ConnectApi.QuerySqlStatus

Usage
Retrieve the queryId from the initial query request. To submit an SQL query request for execution, call querySql(input),
querySql(input, dataspace), or querySql(input, workloadName, dataspace).

668
Apex Reference Guide CdpQuery Class

Example
Get the status of a query with a workload name, data space, and wait time:
ConnectApi.QuerySqlStatus statusOutput =
ConnectApi.CdpQuery.querySqlStatus(output.status.queryId, 'workloadName', 'default', 100);
System.debug(statusOutput);

queryCalculatedInsights(ciName, dimensions, measures, orderby, filters,


batchSize, offset)
Query a Calculated Insight object.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryCalculatedInsights(String ciName, String
dimensions, String measures, String orderby, String filters, Integer batchSize, Integer
offset)

Parameters
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.
dimensions
Type: String
Comma-separated list of up to 10 dimensions, such as GenderId__c, to project. If unspecified, this parameter includes all of the
available dimensions.
measures
Type: String
Comma-separated list of up to 5 measures, such as TotalSales__c, to project. If unspecified, this parameter includes all of the
available measures.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
filters
Type: String
Filter the result set to a more narrow scope or specific type, such as [GenderId__c=Male,FirstName__c=Angel].

669
Apex Reference Guide CdpQuery Class

batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 4999.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.

Return Value
Type: ConnectApi.CdpQueryOutput

queryCalculatedInsights(ciName, dimensions, measures, orderby, filters,


batchSize, offset, timeGranularity)
Query a Calculated Insight object within a specified time range.

API Version
54.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryCalculatedInsights(String ciName, String
dimensions, String measures, String orderby, String filters, Integer batchSize, Integer
offset, String timeGranularity)

Parameters
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.
dimensions
Type: String
Comma-separated list of up to 10 dimensions, such as GenderId__c, to project. If unspecified, this parameter includes all of the
available dimensions.
measures
Type: String
Comma-separated list of up to 5 measures, such as TotalSales__c, to project. If unspecified, this parameter includes all of the
available measures.
orderby
Type: String

670
Apex Reference Guide CdpQuery Class

Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
filters
Type: String
Filter the result set to a more narrow scope or specific type, such as [GenderId__c=Male,FirstName__c=Angel].
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 4999.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
timeGranularity
Type: String
Time range for the measures. Values are:
• HOUR
• DAY
• MONTH
• QUARTER
• YEAR
If unspecified, no time range is applied.

Return Value
Type: ConnectApi.CdpQueryOutput

queryCalculatedInsights(ciName, dimensions, measures, orderby, filters,


batchSize, offset, timeGranularity, dataspace)
Query a Calculated Insight object within a specified time range and specify the data space.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryCalculatedInsights(String ciName, String
dimensions, String measures, String orderby, String filters, Integer batchSize, Integer
offset, String timeGranularity, String dataspace)

671
Apex Reference Guide CdpQuery Class

Parameters
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.
dimensions
Type: String
Comma-separated list of up to 10 dimensions, such as GenderId__c, to project. If unspecified, this parameter includes all of the
available dimensions.
measures
Type: String
Comma-separated list of up to 5 measures, such as TotalSales__c, to project. If unspecified, this parameter includes all of the
available measures.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
filters
Type: String
Filter the result set to a more narrow scope or specific type, such as [GenderId__c=Male,FirstName__c=Angel].
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 4999.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
timeGranularity
Type: String
Time range for the measures. Values are:
• HOUR
• DAY
• MONTH
• QUARTER
• YEAR
If unspecified, no time range is applied.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryOutput

672
Apex Reference Guide CdpQuery Class

queryProfileApi(dataModelName, filters, fields, batchSize, offset, orderby)


Query a Profile data model object using filters.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryProfileApi(String dataModelName, String
filters, String fields, Integer batchSize, Integer offset, String orderby)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
filters
Type: String
Comma-separated list of equality expressions within square brackets, for example, [FirstName__c=DON].
fields
Type: String
Comma-separated list of up to 50 field names that you want to include in the result, for example, Id__c,FirstName__c,
GenderId__c,Occupation__c. If unspecified, Id__c is returned.
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 100.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.

Return Value
Type: ConnectApi.CdpQueryOutput

673
Apex Reference Guide CdpQuery Class

queryProfileApi(dataModelName, id, searchKey, filters, fields, batchSize,


offset, orderby)
Query a Profile data model object using filters and a search key.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryProfileApi(String dataModelName, String
id, String searchKey, String filters, String fields, Integer batchSize, Integer offset,
String orderby)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
id
Type: String
Value of the primary or secondary key field, for example, John. If unspecified, defaults to the value of the primary key field.
searchKey
Type: String
If a field other than the primary key is used, name of the key field, for example, FirstName__c.
filters
Type: String
Comma-separated list of equality expressions within square brackets, for example, [FirstName__c=DON].
fields
Type: String
Comma-separated list of up to 50 field names that you want to include in the result, for example, Id__c,FirstName__c,
GenderId__c,Occupation__c. If unspecified, Id__c is returned.
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 100.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String

674
Apex Reference Guide CdpQuery Class

Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.

Return Value
Type: ConnectApi.CdpQueryOutput

queryProfileApi(dataModelName, id, childDataModelName, searchKey, filters,


fields, batchSize, offset, orderby)
Query a Profile data model object and a child object using filters and a search key.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryProfileApi(String dataModelName, String
id, String childDataModelName, String searchKey, String filters, String fields, Integer
batchSize, Integer offset, String orderby)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
id
Type: String
Value of the primary or secondary key field, for example, John. If unspecified, defaults to the value of the primary key field.
childDataModelName
Type: String
Name of the child data model object, for example, UnifiedContactPointEmail__dlm.
searchKey
Type: String
If a field other than the primary key is used, name of the key field, for example, FirstName__c.
filters
Type: String
Comma-separated list of equality expressions within square brackets, for example, [FirstName__c=DON]. Filters are applied
to the parent object only.
fields
Type: String

675
Apex Reference Guide CdpQuery Class

Comma-separated list of child object field names that you want to include in the result, for example, Id__c,EmailAddress__c.
If unspecified, the first 10 alphabetically sorted fields are returned.
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 100.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.

Return Value
Type: ConnectApi.CdpQueryOutput

queryProfileApi(dataModelName, id, ciName, searchKey, dimensions, measures,


filters, fields, batchSize, offset, orderby)
Query a Profile data model object and a Calculated Insight object using filters and a search key.

API Version
52.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryProfileApi(String dataModelName, String
id, String ciName, String searchKey, String dimensions, String measures, String filters,
String fields, Integer batchSize, Integer offset, String orderby)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
id
Type: String
Value of the primary or secondary key field, for example, John. If unspecified, defaults to the value of the primary key field.
ciName
Type: String

676
Apex Reference Guide CdpQuery Class

Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.


searchKey
Type: String
If a field other than the primary key is used, name of the key field, for example, FirstName__c.
dimensions
Type: String
Comma-separated list of up to 10 dimensions, such as GenderId__c, to project. If unspecified, this parameter includes all of the
available dimensions.
measures
Type: String
Comma-separated list of up to 5 measures, such as TotalSales__c, to project. If unspecified, this parameter includes all of the
available measures.
filters
Type: String
Comma-separated list of equality expressions within square brackets, for example, [FirstName__c=DON].
fields
Type: String
Comma-separated list of up to 50 field names that you want to include in the result, for example, Id__c,FirstName__c,
GenderId__c,Occupation__c. If unspecified, Id__c is returned.
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 100.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.

Return Value
Type: ConnectApi.CdpQueryOutput

queryProfileApi(dataModelName, id, ciName, searchKey, dimensions, measures,


filters, fields, batchSize, offset, orderby, timeGranularity)
Query a Profile data model object and a Calculated Insight object using filters, a search key, and a time range.

API Version
54.0

677
Apex Reference Guide CdpQuery Class

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryProfileApi(String dataModelName, String
id, String ciName, String searchKey, String dimensions, String measures, String filters,
String fields, Integer batchSize, Integer offset, String orderby, String timeGranularity)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
id
Type: String
Value of the primary or secondary key field, for example, John. If unspecified, defaults to the value of the primary key field.
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.
searchKey
Type: String
If a field other than the primary key is used, name of the key field, for example, FirstName__c.
dimensions
Type: String
Comma-separated list of up to 10 dimensions, such as GenderId__c, to project. If unspecified, this parameter includes all of the
available dimensions.
measures
Type: String
Comma-separated list of up to 5 measures, such as TotalSales__c, to project. If unspecified, this parameter includes all of the
available measures.
filters
Type: String
Comma-separated list of equality expressions within square brackets, for example, [FirstName__c=DON].
fields
Type: String
Comma-separated list of up to 50 field names that you want to include in the result, for example, Id__c,FirstName__c,
GenderId__c,Occupation__c. If unspecified, Id__c is returned.
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 100.
offset
Type: Integer

678
Apex Reference Guide CdpQuery Class

Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
timeGranularity
Type: String
Time range for the measures. Values are:
• HOUR
• DAY
• MONTH
• QUARTER
• YEAR
If unspecified, no time range is applied.

Return Value
Type: ConnectApi.CdpQueryOutput

queryProfileApi(dataModelName, id, ciName, searchKey, dimensions, measures,


filters, fields, batchSize, offset, orderby, timeGranularity, dataspace)
Query a Profile data model object and a Calculated Insight object using filters, a search key, a time range, and a data space.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryOutput queryProfileApi(String dataModelName, String
id, String ciName, String searchKey, String dimensions, String measures, String filters,
String fields, Integer batchSize, Integer offset, String orderby, String timeGranularity,
String dataspace)

Parameters
dataModelName
Type: String
Name of the data model object, for example, UnifiedIndividual__dlm.
id
Type: String

679
Apex Reference Guide CdpQuery Class

Value of the primary or secondary key field, for example, John. If unspecified, defaults to the value of the primary key field.
ciName
Type: String
Name of the Calculated Insight object, for example, IndividualChildrenCount__cio.
searchKey
Type: String
If a field other than the primary key is used, name of the key field, for example, FirstName__c.
dimensions
Type: String
Comma-separated list of up to 10 dimensions, such as GenderId__c, to project. If unspecified, this parameter includes all of the
available dimensions.
measures
Type: String
Comma-separated list of up to 5 measures, such as TotalSales__c, to project. If unspecified, this parameter includes all of the
available measures.
filters
Type: String
Comma-separated list of equality expressions within square brackets, for example, [FirstName__c=DON].
fields
Type: String
Comma-separated list of up to 50 field names that you want to include in the result, for example, Id__c,FirstName__c,
GenderId__c,Occupation__c. If unspecified, Id__c is returned.
batchSize
Type: Integer
Number of items to return. Values are from 1–4,999. If unspecified, the default value is 100.
offset
Type: Integer
Number of rows to skip before returning results. If unspecified, no rows are skipped.
orderby
Type: String
Sort order for the result set, such as GenderId__c ASC,Occupation__c DESC. If unspecified, items are returned in the
order they are retrieved.
timeGranularity
Type: String
Time range for the measures. Values are:
• HOUR
• DAY
• MONTH
• QUARTER
• YEAR

680
Apex Reference Guide CdpQuery Class

If unspecified, no time range is applied.


dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryOutput

universalIdLookupBySourceId(entityName, dataSourceId, dataSourceObjectId,


sourceRecordId)
Look up objects by source ID.

API Version
54.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryDataOutput universalIdLookupBySourceId(String
entityName, String dataSourceId, String dataSourceObjectId, String sourceRecordId)

Parameters
entityName
Type: String
Entity name.
dataSourceId
Type: String
Data source ID.
dataSourceObjectId
Type: String
Data source object ID.
sourceRecordId
Type: String
Source record ID.

Return Value
Type: ConnectApi.CdpQueryDataOutput

681
Apex Reference Guide CdpSegment Class

universalIdLookupBySourceId(entityName, dataSourceId, dataSourceObjectId,


sourceRecordId, dataspace)
Look up objects by source ID and specify the data space.

API Version
57.0

Requires Chatter
No

Signature
public static ConnectApi.CdpQueryDataOutput universalIdLookupBySourceId(String
entityName, String dataSourceId, String dataSourceObjectId, String sourceRecordId,
String dataspace)

Parameters
entityName
Type: String
Entity name.
dataSourceId
Type: String
Data source ID.
dataSourceObjectId
Type: String
Data source object ID.
sourceRecordId
Type: String
Source record ID.
dataspace
Type: String
Name of the data space to query. If unspecified, the default data space is used.

Return Value
Type: ConnectApi.CdpQueryDataOutput

CdpSegment Class
Create, delete, get, publish, and update Data Cloud segments.

682
Apex Reference Guide CdpSegment Class

Namespace
ConnectApi

CdpSegment Methods
These methods are for CdpSegment. All methods are static.

IN THIS SECTION:
createSegment(input)
Create a segment.
createSegment(input, dataspace)
Create a segment in a dataspace.
deactivateSegmentByApiName(segmentApiName)
Deactivate a segment by API name.
deactivateSegmentById(segmentId)
Deactivate a segment by ID.
deleteSegment(segmentApiName)
Delete a segment.
executePublishAdhoc(segmentId)
Publish a segment.
getSegment(segmentApiName)
Get a segment by API name.
getSegmentById(segmentId)
Get a segment by ID.
getSegments()
Get segments.
getSegmentsPaginated(batchSize, offset, orderBy)
Get an ordered batch of paginated segments.
getSegmentsPaginated(batchSize, offset, orderBy, dataspace)
Get an ordered batch of paginated segments in a dataspace.
getSegmentsFilteredPaginated(batchSize, offset, orderBy, filters)
Get an ordered and filtered batch of paginated segments.
getSegmentsFilteredPaginated(batchSize, offset, orderBy, dataspace, filters)
Get an ordered and filtered batch of paginated segments in a dataspace.
updateSegment(segmentApiName, input)
Update a segment.

createSegment(input)
Create a segment.

683
Apex Reference Guide CdpSegment Class

API Version
55.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentOutput createSegment(ConnectApi.CdpSegmentInput
input)

Parameters
input
Type: ConnectApi.CdpSegmentInput
A ConnectApi.CdpSegmentInput class.

Return Value
Type: ConnectApi.CdpSegmentOutput

createSegment(input, dataspace)
Create a segment in a dataspace.

API Version
58.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentOutput createSegment(ConnectApi.CdpSegmentInput
input, String dataspace)

Parameters
input
Type: ConnectApi.CdpSegmentInput
A ConnectApi.CdpSegmentInput class.
dataspace
Type: String
Name of the dataspace in which to perform the action. The user must have permission to the specified dataspace. Specify default
to use the default dataspace.

684
Apex Reference Guide CdpSegment Class

Return Value
Type: ConnectApi.CdpSegmentOutput

deactivateSegmentByApiName(segmentApiName)
Deactivate a segment by API name.

API Version
59.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentActionOutput deactivateSegmentByApiName(String
segmentApiName)

Parameters
segmentApiName
Type: String
API name of the segment.

Return Value
Type: ConnectApi.CdpSegmentActionOutput

deactivateSegmentById(segmentId)
Deactivate a segment by ID.

API Version
59.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentActionOutput deactivateSegmentById(String segmentId)

Parameters
segmentId
Type: String

685
Apex Reference Guide CdpSegment Class

ID of the segment.

Return Value
Type: ConnectApi.CdpSegmentActionOutput

deleteSegment(segmentApiName)
Delete a segment.

API Version
56.0

Requires Chatter
No

Signature
public static Void deleteSegment(String segmentApiName)

Parameters
segmentApiName
Type: String
API name of the segment.

Return Value
Type: Void

executePublishAdhoc(segmentId)
Publish a segment.

API Version
56.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentActionOutput executePublishAdhoc(String segmentId)

686
Apex Reference Guide CdpSegment Class

Parameters
segmentId
Type: String
ID of the segment to publish.

Return Value
Type: ConnectApi.CdpSegmentActionOutput

getSegment(segmentApiName)
Get a segment by API name.

API Version
56.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegment(String segmentApiName)

Parameters
segmentApiName
Type: String
API name of the segment.

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

getSegmentById(segmentId)
Get a segment by ID.

API Version
65.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegmentById(String segmentId)

687
Apex Reference Guide CdpSegment Class

Parameters
segmentId
Type: String
ID of the segment.

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

getSegments()
Get segments.

API Version
55.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegments()

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

getSegmentsPaginated(batchSize, offset, orderBy)


Get an ordered batch of paginated segments.

API Version
56.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegmentsPaginated(Integer
batchSize, Integer offset, String orderBy)

Parameters
batchSize
Type: Integer

688
Apex Reference Guide CdpSegment Class

Number of segments to return at one time. Values are from 1 through 200. For example, specify 20 to return 20 segments.
offset
Type: Integer
Number of segments to skip before returning results. Specify 0 to skip no segments.
orderBy
Type: String
Sort order for the result set. Specify a field value followed by an optional sort order, ASC or DESC. For example, Name ASC sorts
results by Name in ascending order, and MarketSegmentType DESC sorts results by MarketSegmentType in descending
order. Omit ASC and DESC to return results in ascending order by default.

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

getSegmentsPaginated(batchSize, offset, orderBy, dataspace)


Get an ordered batch of paginated segments in a dataspace.

API Version
58.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegmentsPaginated(Integer
batchSize, Integer offset, String orderBy, String dataspace)

Parameters
batchSize
Type: Integer
Number of segments to return at one time. Values are from 1 through 200. For example, specify 20 to return 20 segments.
offset
Type: Integer
Number of segments to skip before returning results. Specify 0 to skip no segments.
orderBy
Type: String
Sort order for the result set. Specify a field value followed by an optional sort order, ASC or DESC. For example, Name ASC sorts
results by Name in ascending order, and MarketSegmentType DESC sorts results by MarketSegmentType in descending
order. Omit ASC and DESC to return results in ascending order by default.
dataspace
Type: String

689
Apex Reference Guide CdpSegment Class

Name of the dataspace in which to perform the action. The user must have permission to the specified dataspace. Specify default
to use the default dataspace.

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

getSegmentsFilteredPaginated(batchSize, offset, orderBy, filters)


Get an ordered and filtered batch of paginated segments.

API Version
65.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegmentsFilteredPaginated(Integer
batchSize, Integer offset, String orderBy, String filters)

Parameters
batchSize
Type: Integer
Number of segments to return at one time. Values are from 1 through 200. For example, specify 20 to return 20 segments.
offset
Type: Integer
Number of segments to skip before returning results. Specify 0 to skip no segments.
orderBy
Type: String
Sort order for the result set. Specify a field value followed by an optional sort order, ASC or DESC. For example, Name ASC sorts
results by Name in ascending order, and MarketSegmentType DESC sorts results by MarketSegmentType in descending
order. Omit ASC and DESC to return results in ascending order by default.
filters
Type: String
Filter the result set to a more narrow scope based on segment attributes. Specify a maximum of 10 filters. Separate each filter by an
AND logical operator.
These values are supported:
• LastPublishedEndDateTime - Not present in the output type. Indicates the end date and time when the segment was
last published. Use only the != operator with this value.
• MarketSegmentType - Matches field segmentType.
• Name - Matches field disaplyName.

690
Apex Reference Guide CdpSegment Class

• SegmentOn - Matches field segmentOnApiName.


• SegmentStatus - Matches field segmentStatus.
These operators are supported:
• contains - Search operator for identifying strings or substrings within a field.
• eq - Equality operator for identifying values that match exactly.
• in - Comparison operator for determining whether a field matches one or more specified values.
• != - Inequality operator for determining values that don't match.
These are examples of filter parameter specifications:
• Name != NULL AND Name In Seg 01,seg 02 AND Name contains seg AND Name eq seg 01
• SegmentStatus != NULL AND SegmentStatus In Processing,Active AND SegmentStatus
contains ive AND SegmentStatus eq active
• MarketSegmentType != NULL AND MarketSegmentType In UI,Dbt AND MarketSegmentType
contains i AND MarketSegmentType eq UI
• SegmentOn != NULL AND SegmentOn In individual,account AND SegmentOn contains ual
AND SegmentOn eq Account
• SegmentOn != NULL AND SegmentOn In individual,account AND SegmentOn contains nt
AND SegmentOn eq Account
• LastPublishedEndDateTime != NULL

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

getSegmentsFilteredPaginated(batchSize, offset, orderBy, dataspace, filters)


Get an ordered and filtered batch of paginated segments in a dataspace.

API Version
65.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentContainerOutput getSegmentsFilteredPaginated(Integer
batchSize, Integer offset, String orderBy, String dataspace, String filters)

Parameters
batchSize
Type: Integer
Number of segments to return at one time. Values are from 1 through 200. For example, specify 20 to return 20 segments.

691
Apex Reference Guide CdpSegment Class

offset
Type: Integer
Number of segments to skip before returning results. Specify 0 to skip no segments.
orderBy
Type: String
Sort order for the result set. Specify a field value followed by an optional sort order, ASC or DESC. For example, Name ASC sorts
results by Name in ascending order, and MarketSegmentType DESC sorts results by MarketSegmentType in descending
order. Omit ASC and DESC to return results in ascending order by default.
dataspace
Type: String
Name of the dataspace in which to perform the action. The user must have permission to the specified dataspace. Specify default
to use the default dataspace.
filters
Type: String
Filter the result set to a more narrow scope based on segment attributes. Specify a maximum of 10 filters. Separate each filter by an
AND logical operator.
These values are supported:
• LastPublishedEndDateTime - Not present in the output type. Indicates the end date and time when the segment was
last published. Use only the != operator with this value.
• MarketSegmentType - Matches field segmentType.
• Name - Matches field disaplyName.
• SegmentOn - Matches field segmentOnApiName.
• SegmentStatus - Matches field segmentStatus.
These operators are supported:
• contains - Search operator for identifying strings or substrings within a field.
• eq - Equality operator for identifying values that match exactly.
• in - Comparison operator for determining whether a field matches one or more specified values.
• != - Inequality operator for determining values that don't match.
These are examples of filter parameter specifications:
• Name != NULL AND Name In Seg 01,seg 02 AND Name contains seg AND Name eq seg 01
• SegmentStatus != NULL AND SegmentStatus In Processing,Active AND SegmentStatus
contains ive AND SegmentStatus eq active
• MarketSegmentType != NULL AND MarketSegmentType In UI,Dbt AND MarketSegmentType
contains i AND MarketSegmentType eq UI
• SegmentOn != NULL AND SegmentOn In individual,account AND SegmentOn contains ual
AND SegmentOn eq Account
• SegmentOn != NULL AND SegmentOn In individual,account AND SegmentOn contains nt
AND SegmentOn eq Account
• LastPublishedEndDateTime != NULL

692
Apex Reference Guide Chatter Class

Return Value
Type: ConnectApi.CdpSegmentContainerOutput

updateSegment(segmentApiName, input)
Update a segment.

API Version
56.0

Requires Chatter
No

Signature
public static ConnectApi.CdpSegmentOutput updateSegment(String segmentApiName,
ConnectApi.CdpSegmentInput input)

Parameters
segmentApiName
Type: String
API name of the segment.
input
Type: ConnectApi.CdpSegmentInput
A ConnectApi.CdpSegmentInput class with the updates.

Return Value
Type: ConnectApi.CdpSegmentOutput

Chatter Class
Access information about followers and subscriptions for records.

Namespace
ConnectApi

Chatter Methods
These methods are for Chatter. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

693
Apex Reference Guide Chatter Class

IN THIS SECTION:
deleteSubscription(communityId, subscriptionId)
Delete a subscription. Use this method to stop following a record, a user, or a file.
getFollowers(communityId, recordId)
Get the first page of followers for a record.
getFollowers(communityId, recordId, pageParam, pageSize)
Get a page of followers for a record.
getSubscription(communityId, subscriptionId)
Get information about a subscription.
submitDigestJob(period)
Submit a daily or weekly Chatter email digest job.

deleteSubscription(communityId, subscriptionId)
Delete a subscription. Use this method to stop following a record, a user, or a file.

API Version
28.0

Requires Chatter
Yes

Signature
public static void deleteSubscription(String communityId, String subscriptionId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subscriptionId
Type: String
The ID for a subscription.

Return Value
Type: Void

Usage
“Following” a user, group, or record is the same as “subscribing” to a user, group, or record. A “follower” is the user who followed the
user, group, or record. A “subscription” is an object describing the relationship between the follower and the user, group, or record they
followed.
To leave a group, call deleteMember(communityId, membershipId).

694
Apex Reference Guide Chatter Class

Example
When you follow a user, the call to ConnectApi.ChatterUsers.follow returns a ConnectApi.Subscription object.
To stop following the user, pass the id property of that object to this method.
ConnectApi.Chatter.deleteSubscription(null, '0E8RR0000004CnK0AU');

SEE ALSO:
Follow a Record
follow(communityId, userId, subjectId)

getFollowers(communityId, recordId)
Get the first page of followers for a record.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FollowerPage getFollowers(String communityId, String recordId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
recordId
Type: String
ID for a record or the keyword me.

Return Value
Type: ConnectApi.FollowerPage

Usage
“Following” a user, group, or record is the same as “subscribing” to a user, group, or record. A “follower” is the user who followed the
user, group, or record. A “subscription” is an object describing the relationship between the follower and the user, group, or record they
followed.

SEE ALSO:
Follow a Record

695
Apex Reference Guide Chatter Class

getFollowers(communityId, recordId, pageParam, pageSize)


Get a page of followers for a record.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FollowerPage getFollowers(String communityId, String recordId,
Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
recordId
Type: String
ID for a record or the keyword me.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.FollowerPage

Usage
“Following” a user, group, or record is the same as “subscribing” to a user, group, or record. A “follower” is the user who followed the
user, group, or record. A “subscription” is an object describing the relationship between the follower and the user, group, or record they
followed.

SEE ALSO:
Follow a Record

getSubscription(communityId, subscriptionId)
Get information about a subscription.

696
Apex Reference Guide Chatter Class

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.Subscription getSubscription(String communityId, String
subscriptionId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subscriptionId
Type: String
The ID for a subscription.

Return Value
Type: ConnectApi.Subscription

Usage
“Following” a user, group, or record is the same as “subscribing” to a user, group, or record. A “follower” is the user who followed the
user, group, or record. A “subscription” is an object describing the relationship between the follower and the user, group, or record they
followed.

SEE ALSO:
Follow a Record

submitDigestJob(period)
Submit a daily or weekly Chatter email digest job.

API Version
37.0

Requires Chatter
Yes

697
Apex Reference Guide ChatterFavorites Class

Signature
public static ConnectApi.DigestJobRepresentation submitDigestJob(ConnectApi.DigestPeriod
period)

Parameters
period
Type: ConnectApi.DigestPeriod
Time period that’s included in a Chatter email digest. Values are:
• DailyDigest—The email includes up to the 50 latest posts from the previous day.
• WeeklyDigest—The email includes up to the 50 latest posts from the previous week.

Return Value
Type: ConnectApi.DigestJob

Usage
The times when Chatter sends email digests are not configurable in the UI. To control when email digests are sent and to use this method,
contact Salesforce to enable API-only Chatter Digests.

Warning: Enabling API-only Chatter Digests disables the scheduled digests for your org. You must call the API for your users to
receive their digests.
We recommend scheduling digest jobs by implementing the Apex Schedulable interface with this method. To monitor your digest
jobs from Setup, enter Background Jobs in the Quick Find box, then select Background Jobs.

Example
Schedule daily digests:
global class ExampleDigestJob1 implements Schedulable {
global void execute(SchedulableContext context) {
ConnectApi.Chatter.submitDigestJob(ConnectApi.DigestPeriod.DailyDigest);
}
}

Schedule weekly digests:


global class ExampleDigestJob2 implements Schedulable {
global void execute(SchedulableContext context) {
ConnectApi.Chatter.submitDigestJob(ConnectApi.DigestPeriod.WeeklyDigest);
}
}

SEE ALSO:
Apex Scheduler

ChatterFavorites Class
Chatter favorites give you easy access to topics, list views, and feed searches.

698
Apex Reference Guide ChatterFavorites Class

Namespace
ConnectApi

Usage
Use Connect in Apex to get and delete topics, list views, and feed searches that have been added as favorites. Add topics and feed
searches as favorites, and update the last view date of a feed search or list view feed to the current system time.
In this image of Salesforce, “Build Issues” is a topic, “All Accounts” is a list view, and “United” is a feed search.

ChatterFavorites Methods
These methods are for ChatterFavorites. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

IN THIS SECTION:
addFavorite(communityId, subjectId, searchText)
Add a feed search favorite for a user.
addRecordFavorite(communityId, subjectId, targetId)
Add a topic as a favorite.
deleteFavorite(communityId, subjectId, favoriteId)
Delete a favorite.
getFavorite(communityId, subjectId, favoriteId)
Get information about a favorite.
getFavorites(communityId, subjectId)
Get a list of favorites for a user.

699
Apex Reference Guide ChatterFavorites Class

getFeedElements(communityId, subjectId, favoriteId)


Get the first page of feed elements for a favorite.
getFeedElements(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam)
Get a page of sorted feed elements for a favorite.
getFeedElements(communityId, subjectId, favoriteId, recentCommentCount, elementsPerBundle, pageParam, pageSize, sortParam)
Get a page of sorted feed elements for a favorite. Include no more than the specified number of comments per feed element.
updateFavorite(communityId, subjectId, favoriteId, updateLastViewDate)
Update the last view date of the saved search or list view feed to the current system time.

addFavorite(communityId, subjectId, searchText)


Add a feed search favorite for a user.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedFavorite addFavorite(String communityId, String subjectId,
String searchText)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
searchText
Type: String
Specify the text of the search to be saved as a favorite. This method can only create a feed search favorite, not a list view favorite or
a topic.

Return Value
Type: ConnectApi.FeedFavorite

addRecordFavorite(communityId, subjectId, targetId)


Add a topic as a favorite.

700
Apex Reference Guide ChatterFavorites Class

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedFavorite addRecordFavorite(String communityId, String
subjectId, String targetId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
targetId
Type: String
The ID of the topic to add as a favorite.

Return Value
Type: ConnectApi.FeedFavorite

deleteFavorite(communityId, subjectId, favoriteId)


Delete a favorite.

API Version
28.0

Requires Chatter
Yes

Signature
public static Void deleteFavorite(String communityId, String subjectId, String
favoriteId)

701
Apex Reference Guide ChatterFavorites Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.

Return Value
Type: Void

getFavorite(communityId, subjectId, favoriteId)


Get information about a favorite.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedFavorite getFavorite(String communityId, String subjectId,
String favoriteId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.

702
Apex Reference Guide ChatterFavorites Class

Return Value
Type: ConnectApi.FeedFavorite

getFavorites(communityId, subjectId)
Get a list of favorites for a user.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedFavorites getFavorites(String communityId, String subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.

Return Value
Type: ConnectApi.FeedFavorites

getFeedElements(communityId, subjectId, favoriteId)


Get the first page of feed elements for a favorite.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElements(String communityId, String
subjectId, String favoriteId)

703
Apex Reference Guide ChatterFavorites Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElements(communityId, subjectId, favoriteId, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElements(communityId, subjectId, favoriteId, pageParam, pageSize,


sortParam)
Get a page of sorted feed elements for a favorite.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElements(String communityId, String
subjectId, String favoriteId, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String

704
Apex Reference Guide ChatterFavorites Class

ID for an Experience Cloud site, internal, or null.


subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElements(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElements(communityId, subjectId, favoriteId, recentCommentCount,


elementsPerBundle, pageParam, pageSize, sortParam)
Get a page of sorted feed elements for a favorite. Include no more than the specified number of comments per feed element.

705
Apex Reference Guide ChatterFavorites Class

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElements(String communityId, String
subjectId, String favoriteId, Integer recentCommentCount, Integer elementsPerBundle,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.

706
Apex Reference Guide ChatterFavorites Class

• LastModifiedDateDesc—Sorts by most recent activity.


• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElements(communityId, subjectId, favoriteId, recentCommentCount, elementsPerBundle, pageParam, pageSize,
sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

updateFavorite(communityId, subjectId, favoriteId, updateLastViewDate)


Update the last view date of the saved search or list view feed to the current system time.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedFavorite updateFavorite(String communityId, String
subjectId, String favoriteId, Boolean updateLastViewDate)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String

707
Apex Reference Guide ChatterFavorites Class

ID of a favorite.
updateLastViewDate
Type: Boolean
Specify whether to update the last view date of the specified favorite to the current system time (true) or not (false).

Return Value
Type: ConnectApi.FeedFavorite

ChatterFavorites Test Methods


These test methods are for ChatterFavorites. All methods are static.
For information about using these methods to test your ConnectApi code, see Testing ConnectApi Code.

IN THIS SECTION:
setTestGetFeedElements(communityId, subjectId, favoriteId, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElements is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElements(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElements is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElements(communityId, subjectId, favoriteId, recentCommentCount, elementsPerBundle, pageParam, pageSize,
sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElements is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

setTestGetFeedElements(communityId, subjectId, favoriteId, result)


Register a ConnectApi.FeedElementPage object to be returned when getFeedElements is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElements(String communityId, String subjectId, String
favoriteId, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

708
Apex Reference Guide ChatterFavorites Class

subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElements(communityId, subjectId, favoriteId)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElements(communityId, subjectId, favoriteId, pageParam,


pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElements is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElements(String communityId, String subjectId, String
favoriteId, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.

709
Apex Reference Guide ChatterFavorites Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElements(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElements(communityId, subjectId, favoriteId, recentCommentCount,


elementsPerBundle, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElements is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

710
Apex Reference Guide ChatterFavorites Class

Signature
public static Void setTestGetFeedElements(String communityId, String subjectId, String
favoriteId, Integer recentCommentCount, Integer elementsPerBundle, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage

711
Apex Reference Guide ChatterFavorites Class

Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElements(communityId, subjectId, favoriteId, recentCommentCount, elementsPerBundle, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

Retired ChatterFavorites Methods


These methods for ChatterFavorites are retired.

IN THIS SECTION:
getFeedItems(communityId, subjectId, favoriteId)
Get the first page of feed items for a favorite.
getFeedItems(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam)
Get a page of sorted feed items for a favorite.
getFeedItems(communityId, subjectId, favoriteId, recentCommentCount, pageParam, pageSize, sortParam)
Get a page of sorted feed items for a favorite. Include no more than the specified number of comments per feed item.
setTestGetFeedItems(communityId, subjectId, favoriteId, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItems is called with matching parameters
in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedItems(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItems is called with matching parameters
in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedItems(communityId, subjectId, favoriteId, recentCommentCount, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItems is called with matching parameters
in a test context. Use the method with the same parameters or the code throws an exception.

getFeedItems(communityId, subjectId, favoriteId)


Get the first page of feed items for a favorite.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElements(communityId, subjectId, favoriteId).

Requires Chatter
Yes

712
Apex Reference Guide ChatterFavorites Class

Signature
public static ConnectApi.FeedItemPage getFeedItems(String communityId, String subjectId,
String favoriteId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItems(communityId, subjectId, favoriteId, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItems(communityId, subjectId, favoriteId, pageParam, pageSize,


sortParam)
Get a page of sorted feed items for a favorite.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElements(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam).

Requires Chatter
Yes

713
Apex Reference Guide ChatterFavorites Class

Signature
public static ConnectApi.FeedItemPage getFeedItems(String communityId, String subjectId,
String favoriteId, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

714
Apex Reference Guide ChatterFavorites Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItems(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItems(communityId, subjectId, favoriteId, recentCommentCount,


pageParam, pageSize, sortParam)
Get a page of sorted feed items for a favorite. Include no more than the specified number of comments per feed item.

API Version
29.0–31.0

Important: In version 32.0 and later, use getFeedElements(communityId, subjectId, favoriteId, recentCommentCount,
elementsPerBundle, pageParam, pageSize, sortParam).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItems(String communityId, String subjectId,
String favoriteId, Integer recentCommentCount, String pageParam, Integer pageSize,
FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
pageParam
Type: String

715
Apex Reference Guide ChatterFavorites Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItems(communityId, subjectId, favoriteId, recentCommentCount, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItems(communityId, subjectId, favoriteId, result)


Register a ConnectApi.FeedItemPage object to be returned when getFeedItems is called with matching parameters in
a test context. Use the method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItems(String communityId, String subjectId, String
favoriteId, ConnectApi.FeedItemPage result)

716
Apex Reference Guide ChatterFavorites Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItems(communityId, subjectId, favoriteId)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItems(communityId, subjectId, favoriteId, pageParam, pageSize,


sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItems is called with matching parameters in
a test context. Use the method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItems(String communityId, String subjectId, String
favoriteId, String pageParam, Integer pageSize, FeedSortOrder sortParam,
ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String

717
Apex Reference Guide ChatterFavorites Class

ID of the context user or the alias me.


favoriteId
Type: String
ID of a favorite.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItems(communityId, subjectId, favoriteId, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItems(communityId, subjectId, favoriteId, recentCommentCount,


pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItems is called with matching parameters in
a test context. Use the method with the same parameters or the code throws an exception.

718
Apex Reference Guide ChatterFavorites Class

API Version
29.0–31.0

Signature
public static Void setTestGetFeedItems(String communityId, String subjectId, String
favoriteId, Integer recentCommentCount, String pageParam, Integer pageSize, FeedSortOrder
sortParam, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
favoriteId
Type: String
ID of a favorite.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

719
Apex Reference Guide ChatterFeeds Class

result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItems(communityId, subjectId, favoriteId, recentCommentCount, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

ChatterFeeds Class
Get, post, and delete feed elements, likes, comments, and bookmarks. You can also search feed elements, share feed elements, and vote
on polls.

Namespace
ConnectApi

Usage
The Chatter feed is a container of feed elements. The abstract class ConnectApi.FeedElement is a parent class to the
ConnectApi.FeedItem class, representing feed posts, and the ConnectApi.GenericFeedElement class, representing
bundles and recommendations in the feed. For detailed information, see Working with Feeds and Feed Elements.

Important: Feed item methods aren’t available in version 32.0. In version 32.0 and later, use feed element methods.

Message segments in a feed item are typed as ConnectApi.MessageSegment. Feed item capabilities are typed as
ConnectApi.FeedItemCapability. Record fields are typed as ConnectApi.AbstractRecordField. These classes
are all abstract and have several concrete subclasses. At runtime you can use instanceof to check the concrete types of these objects
and then safely proceed with the corresponding downcast. When you downcast, you must have a default case that handles unknown
subclasses.

Important: The composition of a feed can change between releases. Write your code to handle instances of unknown subclasses.

ChatterFeeds Methods
These methods are for ChatterFeeds. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

IN THIS SECTION:
createStream(communityId, streamInput)
Create a Chatter feed stream.

720
Apex Reference Guide ChatterFeeds Class

deleteComment(communityId, commentId)
Delete a comment.
deleteFeedElement(communityId, feedElementId)
Delete a feed element.
deleteLike(communityId, likeId)
Delete a like on a comment or post.
deleteStream(communityId, streamId)
Delete a Chatter feed stream.
getComment(communityId, commentId)
Get a comment.
getCommentBatch(communityId, commentIds)
Get a list of comments.
getCommentInContext(communityId, commentId, pageSize)
Get a threaded comment in the context of its parent comments and post.
getCommentsForFeedElement(communityId, feedElementId)
Get comments for a feed element.
getCommentsForFeedElement(communityId, feedElementId, threadedCommentsCollapsed)
Get comments in a threaded style for a feed element.
getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize)
Get a page of comments for a feed element.
getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize, threadedCommentsCollapsed)
Get a page of comments in a threaded style for a feed element.
getCommentsForFeedElement(communityId, feedElementId, threadedCommentsCollapsed, sortParam)
Get sorted comments in a threaded style for a feed element.
getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize, threadedCommentsCollapsed, sortParam)
Get a page of sorted comments in a threaded style for a feed element.
getCommentsForFeedElement(communityId, feedElementId, sortParam)
Get sorted comments for a feed element.
getCommentsForFeedElement(communityId, feedElementId, sortParam, threadedCommentsCollapsed)
Get sorted comments in a threaded style for a feed element.
getExtensions(communityId, pageParam, pageSize)
Get extensions.
getFeed(communityId, feedType)
Get a feed.
getFeed(communityId, feedType, sortParam)
Get a sorted feed.
getFeed(communityId, feedType, subjectId)
Get a feed for a record or user.
getFeed(communityId, feedType, subjectId, sortParam)
Get a sorted feed for a record or user.

721
Apex Reference Guide ChatterFeeds Class

getFeedDirectory(String)
Get a list of all feeds available to the context user.
getFeedElement(communityId, feedElementId)
Get a feed element.
getFeedElement(communityId, feedElementId, commentSort)
Get a feed element with sorted comments.
getFeedElement(communityId, feedElementId, threadedCommentsCollapsed)
Get a feed element and its comments in a threaded style.
getFeedElement(communityId, feedElementId, threadedCommentsCollapsed, commentSort)
Get a feed element and its sorted comments in a threaded style.
getFeedElement(communityId, feedElementId, recentCommentCount, elementsPerBundle)
Get a feed element with the specified number of elements per bundle including no more than the specified number of comments
per feed element.
getFeedElement(communityId, feedElementId, recentCommentCount, elementsPerBundle, threadedCommentsCollapsed)
Get a feed element with its comments in a threaded style with the specified number of elements per bundle and comments per
feed element.
getFeedElement(communityId, feedElementId, recentCommentCount, elementsPerBundle, threadedCommentsCollapsed,
commentSort)
Get a feed element with its sorted comments in a threaded style with the specified number of elements per bundle and comments
per feed element.
getFeedElement(communityId, feedElementId, recentCommentCount, elementsPerBundle, commentSort)
Get a feed element with the specified number of elements per bundle including no more than the specified number of sorted
comments per feed element.
getFeedElementBatch(communityId, feedElementIds)
Get a list of feed elements.
getFeedElementPoll(communityId, feedElementId)
Get the poll associated with a feed element.
getFeedElementsFromBundle(communityId, feedElementId)
Get feed elements from a bundle.
getFeedElementsFromBundle(communityId, feedElementId, pageParam, pageSize, elementsPerBundle, recentCommentCount)
Get a page of feed elements from a bundle. Specify the number of elements per bundle and include no more than the specified
number of comments per feed element.
getFeedElementsFromFeed(communityId, feedType)
Get feed elements from the Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview feeds.
getFeedElementsFromFeed(communityId, feedType, pageParam, pageSize, sortParam)
Get a page of sorted feed elements from the Company, DirectMessageModeration, DirectMessages, Home,
Isolated, Moderation, and PendingReview feeds.
getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam)
Get a page of sorted feed elements from the Company, DirectMessageModeration, DirectMessages, Home,
Isolated, Moderation, and PendingReview feeds. Each feed element contains no more than the specified number of
comments.

722
Apex Reference Guide ChatterFeeds Class

getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter)


Get a page of sorted and filtered feed elements from the Home feed. Each feed element contains no more than the specified number
of comments.
getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter,
threadedCommentsCollapsed)
Get a page of filtered and sorted feed elements with comments in a threaded style from the Home feed. Each feed element contains
no more than the specified number of comments.
getFeedElementsFromFeed(communityId, feedType, subjectId)
Get feed elements from any feed other than Company, DirectMessageModeration, DirectMessages, Filter,
Home, Isolated, Landing, Moderation, and PendingReview for a user or record.
getFeedElementsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam)
Get a page of sorted feed elements from any feed other than Company, DirectMessageModeration, DirectMessages,
Filter, Home, Isolated, Landing, Moderation, and PendingReview.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam)
Get a page of sorted feed elements from any feed other than Company, DirectMessageModeration, DirectMessages,
Filter, Home, Isolated, Landing, Moderation, and PendingReview. Each feed element includes no more than
the specified number of comments.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
showInternalOnly)
Get a page of sorted feed elements from a record feed. Each feed element includes no more than the specified number of comments.
Specify whether to return feed elements posted by internal (non-Experience Cloud site) users only.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
filter)
Get a page of sorted and filtered feed elements from the UserProfile feed.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
filter, threadedCommentsCollapsed)
Get a page of feed elements with comments in a threaded style from the UserProfile feed.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
customFilter)
Get a page of sorted and filtered feed elements from the case feed.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly)
Get a page of sorted feed elements from a record feed. Specify the number of elements per bundle and include no more than the
specified number of comments per feed element. Specify whether to return feed elements posted by internal (non-Experience Cloud
site) users only.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter)
Get a page of sorted and filtered feed elements from a record feed. Specify the number of elements per bundle and include no more
than the specified number of comments per feed element. Specify whether to return feed elements posted by internal (non-Experience
Cloud site) users only.

723
Apex Reference Guide ChatterFeeds Class

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,


pageSize, sortParam, showInternalOnly, filter, threadedCommentsCollapsed)
Get a page of sorted and filtered feed elements with comments in a threaded style for a record feed. Specify the number of elements
per bundle and include no more than the specified number of comments per feed element. Specify whether to return feed elements
posted by internal (non-Experience Cloud site) users only.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter)
Get a page of sorted and filtered feed elements from a case feed.
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter, threadedCommentsCollapsed)
Get a page of filtered and sorted feed elements with comments in a threaded style from a case feed.
getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix)
Get feed elements from a feed filtered by a key prefix for a user.
getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam)
Get a page of sorted feed elements from a feed filtered by a key prefix for a user.
getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam)
Get a page of sorted feed elements from a feed filtered by a key prefix for a user. Each feed element contains no more than the
specified number of comments.
getFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle,
density, pageParam, pageSize, updatedSince)
Get a page of feed elements from a feed filtered by a key prefix for a user. Include only feed elements that have been updated since
the time specified in the updatedSince parameter.
getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince)
Get a page of feed elements from the Company, DirectMessageModeration, Home, and Moderation feeds. Include
only feed elements that have been updated since the time specified in the updatedSince parameter. Each feed element contains
no more than the specified number of comments.
getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince, filter)
Get a page of filtered feed elements from the Home feed. Include only feed elements that have been updated since the time
specified in the updatedSince parameter. Each feed element contains no more than the specified number of comments.
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince)
Get a page of feed elements from the Files, Groups, News, People, and Record feeds. Include only feed elements that
have been updated since the time specified in the updatedSince parameter. Each feed element contains no more than the
specified number of comments.
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly)
Get a page of feed elements from a record feed. Include only feed elements that have been updated since the time specified in the
updatedSince parameter. Specify whether to return feed elements posted by internal (non-Experience Cloud site) users only.
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, filter)
Get a page of filtered feed elements from a UserProfile feed. Include only feed elements that have been updated since the
time specified in the updatedSince parameter.

724
Apex Reference Guide ChatterFeeds Class

getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,


pageSize, updatedSince, customFilter)
Get a page of filtered feed elements from a case feed. Include only feed elements that have been updated since the time specified
in the updatedSince parameter.
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, showInternalOnly)
Get a page of feed elements from a record feed. Include only feed elements that have been updated since the time specified in the
updatedSince parameter. Specify the maximum number of feed elements in a bundle and whether to return feed elements
posted by internal (non-Experience Cloud site) users only.
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, showInternalOnly, filter)
Get a page of filtered feed elements from a record feed. Include only feed elements that have been updated since the time specified
in the updatedSince parameter. Specify the maximum number of feed elements in a bundle and whether to return feed
elements posted by internal (non-Experience Cloud site) users only.
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, showInternalOnly, customFilter)
Get a page of filtered feed elements from a case feed. Include only feed elements that have been updated since the time specified
in the updatedSince parameter.
getFeedWithFeedElements(communityId, feedType, pageSize)
Get information about a feed and a page of feed elements from the feed.
getFeedWithFeedElements(communityId, feedType, pageSize, recentCommentCount)
Get a page of information about the feed and the feed elements with the specified number of comments per feed element from
the feed.
getFilterFeed(communityId, subjectId, keyPrefix)
Get a feed filtered by a key prefix for a user.
getFilterFeed(communityId, subjectId, keyPrefix, sortParam)
Get a sorted feed filtered by a key prefix for a user.
getFilterFeedDirectory(communityId, subjectId)
Get a feed directory of filter feeds available to the context user.
getLike(communityId, likeId)
Get a like on a post or comment.
getLikesForComment(communityId, commentId)
Get likes for a comment.
getLikesForComment(communityId, commentId, pageParam, pageSize)
Get a page of likes for a comment.
getLikesForFeedElement(communityId, feedElementId)
Get likes for a feed element.
getLikesForFeedElement(communityId, feedElementId, pageParam, pageSize)
Get a page of likes for a feed element.
getLinkMetadata(communityId, urls)
Get link metadata for URLs.

725
Apex Reference Guide ChatterFeeds Class

getPinnedFeedElementsFromFeed(communityId, feedType, subjectId)


Get pinned feed elements from a group or topic feed.
getReadByForFeedElement(communityId, feedElementId)
Get information about who read a feed element and when.
getReadByForFeedElement(communityId, feedElementId, pageParam, pageSize)
Get a page of information about who read a feed element and when.
getRelatedPosts(communityId, feedElementId, filter, maxResults)
Get posts related to the context feed element.
getStream(communityId, streamId)
Get information about a Chatter feed stream.
getStream(communityId, streamId, globalScope)
Get information about a Chatter feed stream, regardless of Experience Cloud site.
getStreams(communityId)
Get the Chatter feed streams for the context user.
getStreams(communityId, sortParam)
Get and sort the Chatter feed streams for the context user.
getStreams(communityId, pageParam, pageSize)
Get a page of Chatter feed streams for the context user.
getStreams(communityId, pageParam, pageSize, sortParam)
Get a sorted page of Chatter feed streams for the context user.
getStreams(communityId, pageParam, pageSize, sortParam, globalScope)
Get a sorted page of Chatter feed streams from all Enterprise Cloud sites for the context user.
getSupportedEmojis()
Get supported emojis for the org.
getThreadsForFeedComment(communityId, commentId)
Get threaded comments for a comment.
getThreadsForFeedComment(communityId, commentId, pageParam, pageSize)
Get a page of threaded comments for a comment.
getThreadsForFeedComment(communityId, commentId, threadedCommentsCollapsed)
Access the comments capability for a comment.
getTopUnansweredQuestions(communityId) (Pilot)
Get top unanswered questions for the context user in aExperience Cloud site.
getTopUnansweredQuestions(communityId, filter) (Pilot)
Get filtered top unanswered questions for the context user in an Experience Cloud site.
getTopUnansweredQuestions(communityId, pageSize) (Pilot)
Get a page of top unanswered questions for the context user in an Experience Cloud site.
getTopUnansweredQuestions(communityId, filter, pageSize) (Pilot)
Get a page of filtered top unanswered questions for the context user in an Experience Cloud site.
getVotesForComment(communityId, commentId, vote)
Get the first page of users who upvoted or downvoted a comment.

726
Apex Reference Guide ChatterFeeds Class

getVotesForComment(communityId, commentId, vote, pageParam, pageSize)


Get a page of users who upvoted or downvoted a comment.
getVotesForFeedElement(communityId, feedElementId, vote)
Get the first page of users who upvoted or downvoted a feed element.
getVotesForFeedElement(communityId, feedElementId, vote, pageParam, pageSize)
Get a page of users who upvoted or downvoted a feed element.
isCommentEditableByMe(communityId, commentId)
Discover whether the context user can edit a comment.
isFeedElementEditableByMe(communityId, feedElementId)
Discover whether the context user can edit a feed element.
isModified(communityId, feedType, subjectId, since)
Discover whether a news feed has been updated or changed. Use this method to poll a news feed for updates.
likeComment(communityId, commentId)
Like a comment for the context user.
likeFeedElement(communityId, feedElementId)
Like a feed element.
postCommentToFeedElement(communityId, feedElementId, text)
Post a plain-text comment to a feed element.
postCommentToFeedElement(communityId, feedElementId, comment, feedElementFileUpload)
Post a rich-text comment to a feed element. Use this method to include mentions and to attach a file.
postFeedElement(communityId, subjectId, feedElementType, text)
Post a plain-text feed element.
postFeedElement(communityId, feedElement)
Post a rich-text feed element. Include mentions and hashtag topics, attach already uploaded files to a feed element, and associate
action link groups with a feed element. You can also use this method to share a feed element and add a comment.
postFeedElementBatch(communityId, feedElements)
Post a list of feed elements.
publishDraftFeedElement(communityId, feedElementId, feedElement)
Publish a draft feed element.
searchFeedElements(communityId, q)
Get the first page of feed elements that match the search criteria.
searchFeedElements(communityId, q, sortParam)
Get the first page of sorted feed elements that match the search criteria.
searchFeedElements(communityId, q, threadedCommentsCollapsed)
Get the feed elements and comments that match the search criteria.
searchFeedElements(communityId, q, pageParam, pageSize)
Get a page of feed elements that match the search criteria.
searchFeedElements(communityId, q, pageParam, pageSize, sortParam)
Get a page of sorted feed elements that match the search criteria.
searchFeedElements(communityId, q, pageParam, pageSize, threadedCommentsCollapsed)
Get a page of feed elements with comments in a threaded style that match the search criteria.

727
Apex Reference Guide ChatterFeeds Class

searchFeedElements(communityId, q, recentCommentCount, pageParam, pageSize, sortParam)


Get a page of sorted feed elements that match the search criteria. Each feed element includes no more than the specified number
of comments.
searchFeedElementsInFeed(communityId, feedType, q)
Get the feed elements from the Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview feeds that match the search criteria.
searchFeedElementsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from the Company, DirectMessageModeration, Home, Isolated, Moderation,
and PendingReview feeds that match the search criteria.
searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from the Company, DirectMessageModeration, Home, Isolated, Moderation,
and PendingReview feeds that match the search criteria. Each feed element includes no more than the specified number of
comments.
searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q, filter)
Get a page of sorted and filtered feed elements from the Home feed that match the search criteria. Each feed element includes no
more than the specified number of comments.
searchFeedElementsInFeed(communityId, feedType, subjectId, q)
Search up to 5,000 of the most recent feed elements in a feed for a subject ID that match the search string. Feed elements are
returned in order of most recent activity.
searchFeedElementsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from a feed for a record or user that match the search criteria.
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
q)
Get a page of sorted feed elements from a feed that match the search criteria. Each feed element includes no more than the specified
number of comments.
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
filter)
Get a page of sorted and filtered feed elements from a UserProfile feed that match the search criteria.
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
customFilter)
Get a page of sorted and filtered feed elements from a case feed that match the search criteria.
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly)
Get a page of sorted feed elements from a feed for a record or user that match the search criteria. Each feed element includes no
more than the specified number of comments. Specify whether to return feed elements posted by internal (non-Experience Cloud
site) users only.
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, filter)
Get a page of sorted and filtered feed elements from a feed for a record or user that match the search criteria. Each feed element
includes no more than the specified number of comments. Specify whether to return feed elements posted by internal (non-Experience
Cloud site) users only.
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, customFilter)
Get a page of sorted and filtered feed elements from a case feed that match the search criteria.

728
Apex Reference Guide ChatterFeeds Class

searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q)


Get the feed elements from a feed filtered by a key prefix that match the search criteria.
searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from a feed filtered by a key prefix that match the search criteria.
searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam,
q)
Get a page of sorted feed elements from a feed filtered by a key prefix that match the search criteria. Each feed element includes no
more than the specified number of comments.
searchStreams(communityId, q)
Search the Chatter feed streams for the context user.
searchStreams(communityId, q, sortParam)
Search and sort the Chatter feed streams for the context user.
searchStreams(communityId, q, pageParam, pageSize)
Search the Chatter feed streams for the context user and return a page of results.
searchStreams(communityId, q, pageParam, pageSize, sortParam)
Search the Chatter feed streams for the context user and return a sorted page of results.
searchStreams(communityId, q, pageParam, pageSize, sortParam, globalScope)
Search the Chatter feed streams from all Experience Cloud sites for the context user and return a sorted page of results.
setCommentIsVerified(communityId, commentId, isVerified)
Mark a comment as verified or unverified.
setCommentIsVerifiedByAnonymized(communityId, commentId, isVerified, isVerifiedByAnonymized)
Mark a comment as verified by an anonymous user.
setCommentVote(communityId, commentId, upDownVote)
Upvote or downvote a comment.
setFeedCommentStatus(communityId, commentId, status)
Set the status of a comment.
setFeedElementIsClosed(communityId, feedElementId, isClosed)
Set a feed element to closed.
setFeedElementVote(communityId, feedElementId, upDownVote)
Upvote or downvote a feed element.
setFeedEntityStatus(communityId, feedElementId, status)
Set the status of a feed post.
setIsMutedByMe(communityId, feedElementId, isMutedByMe)
Mute or unmute a feed element.
setIsReadByMe(communityId, feedElementId, readBy)
Mark a feed element as read for the context user using an input class.
setIsReadByMe(communityId, feedElementId, isReadByMe)
Mark a feed element as read for the context user.
updateComment(communityId, commentId, comment)
Edit a comment.

729
Apex Reference Guide ChatterFeeds Class

updateDirectMessage(communityId, feedElementId, directMessage)


Update the members of a direct message.
updateFeedElement(communityId, feedElementId, feedElement)
Edit a feed element.
updateFeedElementBookmarks(communityId, feedElementId, bookmarks)
Bookmark a feed element or remove a bookmark from a feed element using an input class.
updateFeedElementBookmarks(communityId, feedElementId, isBookmarkedByCurrentUser)
Bookmark a feed element or remove a bookmark from a feed element.
updateFeedElementReadByCapabilityBatch(communityId, feedElementIds, readBy)
Mark multiple feed elements as read by the context user at the same time using an input class.
updateFeedElementReadByCapabilityBatch(communityId, feedElementIds, isReadByMe)
Mark multiple feed elements as read by the context user at the same time.
updateLikeForComment(communityId, commentId, isLikedByCurrentUser)
Like or unlike a comment.
updateLikeForFeedElement(communityId, feedElementId, isLikedByCurrentUser)
Like or unlike a feed element.
updatePinnedFeedElements(communityId, feedType, subjectId, pin)
Pin or unpin feed elements to a group or topic feed.
updateStream(communityId, streamId, streamInput)
Update a Chatter feed stream.
voteOnFeedElementPoll(communityId, feedElementId, myChoiceId)
Vote on a poll or change your vote on a poll.

createStream(communityId, streamInput)
Create a Chatter feed stream.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStream createStream(String communityId,
ConnectApi.ChatterStreamInput streamInput)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

730
Apex Reference Guide ChatterFeeds Class

streamInput
Type: ConnectApi.ChatterStreamInput
A ConnectApi.ChatterStreamInput body.

Return Value
Type: ConnectApi.ChatterStream

deleteComment(communityId, commentId)
Delete a comment.

API Version
28.0

Requires Chatter
Yes

Signature
public static Void deleteComment(String communityId, String commentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID for a comment.

Return Value
Type: Void

deleteFeedElement(communityId, feedElementId)
Delete a feed element.

API Version
31.0

Requires Chatter
Yes

731
Apex Reference Guide ChatterFeeds Class

Signature
public static deleteFeedElement(String communityId, String feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: Void

deleteLike(communityId, likeId)
Delete a like on a comment or post.

API Version
28.0

Requires Chatter
Yes

Signature
public static Void deleteLike(String communityId, String likeId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
likeId
Type: String
ID for a like.

Return Value
Type: Void

deleteStream(communityId, streamId)
Delete a Chatter feed stream.

732
Apex Reference Guide ChatterFeeds Class

API Version
39.0

Requires Chatter
Yes

Signature
public static Void deleteStream(String communityId, String streamId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
streamId
Type: String
ID of the Chatter feed stream.

Return Value
Type: Void

getComment(communityId, commentId)
Get a comment.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.Comment getComment(String communityId, String commentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

733
Apex Reference Guide ChatterFeeds Class

commentId
Type: String
ID for a comment.

Return Value
Type: ConnectApi.Comment

getCommentBatch(communityId, commentIds)
Get a list of comments.

API Version
42.0

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] getCommentBatch(String communityId, List<String>
commentIds)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentIds
Type: List<String>
A list of up to 100 comment IDs.

Return Value
Type: ConnectApi.BatchResult[]
The ConnectApi.BatchResult.getResult() method returns a ConnectApi.Comment object and errors for comments
that didn’t load.

getCommentInContext(communityId, commentId, pageSize)


Get a threaded comment in the context of its parent comments and post.

API Version
44.0

734
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getCommentInContext(String communityId, String
commentId, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you don’t specify a value, the default size is 25.

Return Value
Type: ConnectApi.FeedElement
If the comment doesn’t support the comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId)
Get comments for a feed element.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

735
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.CommentPage getCommentsForFeedElement(String communityId,
String feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.CommentPage
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId,
threadedCommentsCollapsed)
Get comments in a threaded style for a feed element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getCommentsForFeedElement(String communityId,
String feedElementId, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String

736
Apex Reference Guide ChatterFeeds Class

ID of the feed element.


threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.CommentPage
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize)


Get a page of comments for a feed element.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getCommentsForFeedElement(String communityId,
String feedElementId, String pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of comments per page. Valid values are from 1 through 100. If you pass null, the default size is 25.

737
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.CommentPage
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize,


threadedCommentsCollapsed)
Get a page of comments in a threaded style for a feed element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getCommentsForFeedElement(String communityId,
String feedElementId, String pageParam, Integer pageSize, Boolean
threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of comments per page. Valid values are from 1 through 100. If you pass null, the default size is 25.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

738
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.CommentPage
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId,
threadedCommentsCollapsed, sortParam)
Get sorted comments in a threaded style for a feed element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentsCapability getCommentsForFeedElement(String communityId,
String feedElementId, Boolean threadedCommentsCollapsed, ConnectApi.FeedCommentSortOrder
sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
sortParam
Type: ConnectApi.FeedCommentSortOrder
Order of comments. Values are:
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.

739
Apex Reference Guide ChatterFeeds Class

Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.CommentPage
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize,


threadedCommentsCollapsed, sortParam)
Get a page of sorted comments in a threaded style for a feed element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getCommentsForFeedElement(String communityId,
String feedElementId, String pageParam, Integer pageSize, Boolean
threadedCommentsCollapsed, ConnectApi.FeedCommentSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of comments per page. Valid values are from 1 through 100. If you pass null, the default size is 25.
threadedCommentsCollapsed
Type: Boolean

740
Apex Reference Guide ChatterFeeds Class

Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
sortParam
Type: ConnectApi.FeedCommentSortOrder
Order of comments. Values are:
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.
Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.CommentPage
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId, sortParam)


Get sorted comments for a feed element.

API Version
41.0

Available to Guest Users


41.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentsCapability getCommentsForFeedElement(String communityId,
String feedElementId, ConnectApi.FeedCommentSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
sortParam
Type: ConnectApi.FeedCommentSortOrder

741
Apex Reference Guide ChatterFeeds Class

Order of comments. Values are:


• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.
Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.CommentsCapability
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getCommentsForFeedElement(communityId, feedElementId, sortParam,


threadedCommentsCollapsed)
Get sorted comments in a threaded style for a feed element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentsCapability getCommentsForFeedElement(String communityId,
String feedElementId, ConnectApi.FeedCommentSortOrder sortParam, Boolean
threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
sortParam
Type: ConnectApi.FeedCommentSortOrder
Order of comments. Values are:
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.

742
Apex Reference Guide ChatterFeeds Class

• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.


• Relevance—Sorts by most relevant content.
Sorting in descending order isn’t supported.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.CommentsCapability
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

getExtensions(communityId, pageParam, pageSize)


Get extensions.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ExtensionDefinitions getExtensions(String communityId, String
pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. The default size is 15.

743
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.ExtensionDefinitions

getFeed(communityId, feedType)
Get a feed.

API Version
28.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFeed(String communityId, ConnectApi.FeedType feedType)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.

Return Value
Type: ConnectApi.Feed

getFeed(communityId, feedType, sortParam)


Get a sorted feed.

API Version
28.0

Available to Guest Users


32.0

744
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFeed(String communityId, ConnectApi.FeedType feedType,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
If feedType is DirectMessages, sortParam must be LastModifiedDateDesc.

Return Value
Type: ConnectApi.Feed

getFeed(communityId, feedType, subjectId)


Get a feed for a record or user.

API Version
28.0

Available to Guest Users


32.0

745
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFeed(String communityId, ConnectApi.FeedType feedType,
String subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.

Return Value
Type: ConnectApi.Feed

getFeed(communityId, feedType, subjectId, sortParam)


Get a sorted feed for a record or user.

API Version
28.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFeed(String communityId, ConnectApi.FeedType feedType,
String subjectId, ConnectApi.FeedSortOrder sortParam)

746
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.Feed

getFeedDirectory(String)
Get a list of all feeds available to the context user.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedDirectory getFeedDirectory(String communityId)

747
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

Return Value
Type: ConnectApi.FeedDirectory

getFeedElement(communityId, feedElementId)
Get a feed element.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, commentSort)


Get a feed element with sorted comments.

748
Apex Reference Guide ChatterFeeds Class

API Version
41.0

Available to Guest Users


41.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, ConnectApi.FeedCommentSortOrder commentSort)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
commentSort
Type: ConnectApi.FeedCommentSortOrder
Order of comments.
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.
The default value is CreatedDateLatestAsc.
Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, threadedCommentsCollapsed)


Get a feed element and its comments in a threaded style.

API Version
44.0

749
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, threadedCommentsCollapsed,


commentSort)
Get a feed element and its sorted comments in a threaded style.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

750
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, Boolean threadedCommentsCollapsed, ConnectApi.FeedCommentSortOrder
commentSort)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
commentSort
Type: ConnectApi.FeedCommentSortOrder
Order of comments.
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.
Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, recentCommentCount,


elementsPerBundle)
Get a feed element with the specified number of elements per bundle including no more than the specified number of comments per
feed element.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

751
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, Integer recentCommentCount, Integer elementsPerBundle)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, recentCommentCount,


elementsPerBundle, threadedCommentsCollapsed)
Get a feed element with its comments in a threaded style with the specified number of elements per bundle and comments per feed
element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, Integer recentCommentCount, Integer elementsPerBundle, Boolean
threadedCommentsCollapsed)

752
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, recentCommentCount,


elementsPerBundle, threadedCommentsCollapsed, commentSort)
Get a feed element with its sorted comments in a threaded style with the specified number of elements per bundle and comments per
feed element.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, Integer recentCommentCount, Integer elementsPerBundle, Boolean
threadedCommentsCollapsed, ConnectApi.FeedCommentSortOrder commentSort)

753
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
commentSort
Type: ConnectApi.FeedCommentSortOrder
Order of comments.
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.
Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.FeedElement

getFeedElement(communityId, feedElementId, recentCommentCount,


elementsPerBundle, commentSort)
Get a feed element with the specified number of elements per bundle including no more than the specified number of sorted comments
per feed element.

API Version
41.0

Available to Guest Users


41.0

754
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement getFeedElement(String communityId, String
feedElementId, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedCommentSortOrder commentSort)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
commentSort
Type: ConnectApi.FeedCommentSortOrder
Order of comments.
• CreatedDateLatestAsc—Sorts by most recently created comments in ascending order.
• CreatedDateOldestAsc—Sorts by oldest comments in ascending order.
• Relevance—Sorts by most relevant content.
The default value is CreatedDateLatestAsc.
Sorting in descending order isn’t supported.

Return Value
Type: ConnectApi.FeedElement

getFeedElementBatch(communityId, feedElementIds)
Get a list of feed elements.

API Version
31.0

755
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] getFeedElementBatch(String communityId,
List<String> feedElementIds)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementIds
Type: List<String>
A list of up to 500 feed element IDs.

Return Value
Type: ConnectApi.BatchResult[]
The ConnectApi.BatchResult.getResult() method returns a ConnectApi.FeedElement object and errors for
feed elements that didn’t load.

getFeedElementPoll(communityId, feedElementId)
Get the poll associated with a feed element.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.PollCapability getFeedElementPoll(String communityId, String
feedElementId)

756
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.PollCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

Note: Triggers on FeedItem objects run before their attachment and capabilities information is saved, which means that
ConnectApi.FeedItem.attachment information and ConnectApi.FeedElement.capabilities information
may not be available in the trigger.

getFeedElementsFromBundle(communityId, feedElementId)
Get feed elements from a bundle.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromBundle(String communityId,
String feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.FeedElementPage

757
Apex Reference Guide ChatterFeeds Class

getFeedElementsFromBundle(communityId, feedElementId, pageParam, pageSize,


elementsPerBundle, recentCommentCount)
Get a page of feed elements from a bundle. Specify the number of elements per bundle and include no more than the specified number
of comments per feed element.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromBundle(String communityId,
String feedElementId, String pageParam, Integer pageSize, Integer elementsPerBundle,
Integer recentCommentCount)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.

Return Value
Type: ConnectApi.FeedElementPage

758
Apex Reference Guide ChatterFeeds Class

getFeedElementsFromFeed(communityId, feedType)
Get feed elements from the Company, DirectMessageModeration, DirectMessages, Home, Isolated, Moderation,
and PendingReview feeds.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, pageParam, pageSize, sortParam)


Get a page of sorted feed elements from the Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview feeds.

759
Apex Reference Guide ChatterFeeds Class

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

760
Apex Reference Guide ChatterFeeds Class

If feedType is DirectMessages, sortParam must be LastModifiedDateDesc.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam)
Get a page of sorted feed elements from the Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview feeds. Each feed element contains no more than the specified number of comments.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.

761
Apex Reference Guide ChatterFeeds Class

recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
If feedType is DirectMessages, sortParam must be LastModifiedDateDesc.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

762
Apex Reference Guide ChatterFeeds Class

getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam, filter)
Get a page of sorted and filtered feed elements from the Home feed. Each feed element contains no more than the specified number
of comments.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.

763
Apex Reference Guide ChatterFeeds Class

When the sortParam is MostViewed, you must pass in null for the pageParam.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
When the sortParam is MostViewed, the pageSize must be a value from 1 to 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

764
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter,
result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam, filter, threadedCommentsCollapsed)
Get a page of filtered and sorted feed elements with comments in a threaded style from the Home feed. Each feed element contains
no more than the specified number of comments.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedFilter filter, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.

765
Apex Reference Guide ChatterFeeds Class

recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
When the sortParam is MostViewed, you must pass in null for the pageParam.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
When the sortParam is MostViewed, the pageSize must be a value from 1 to 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.

766
Apex Reference Guide ChatterFeeds Class

• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate


answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter,
threadedCommentsCollapsed, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId)


Get feed elements from any feed other than Company, DirectMessageModeration, DirectMessages, Filter, Home,
Isolated, Landing, Moderation, and PendingReview for a user or record.

API Version
31.0

Available to Guest Users


31.0

767
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

Example for Getting the Context User’s News Feed


ConnectApi.FeedElementPage fep =
ConnectApi.ChatterFeeds.getFeedElementsFromFeed(Network.getNetworkId(),
ConnectApi.FeedType.News, 'me');

Example for Getting Another User’s Profile Feed


ConnectApi.FeedElementPage fep =
ConnectApi.ChatterFeeds.getFeedElementsFromFeed(Network.getNetworkId(),
ConnectApi.FeedType.UserProfile, '005R0000000HwMA');

768
Apex Reference Guide ChatterFeeds Class

Example for Getting Another User’s Record Feed


ConnectApi.FeedElementPage fep =
ConnectApi.ChatterFeeds.getFeedElementsFromFeed(Network.getNetworkId(),
ConnectApi.FeedType.Record, '005R0000000HwMA');

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, pageParam, pageSize,


sortParam)
Get a page of sorted feed elements from any feed other than Company, DirectMessageModeration, DirectMessages,
Filter, Home, Isolated, Landing, Moderation, and PendingReview.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.

769
Apex Reference Guide ChatterFeeds Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
The number of feed elements per page.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam)
Get a page of sorted feed elements from any feed other than Company, DirectMessageModeration, DirectMessages,
Filter, Home, Isolated, Landing, Moderation, and PendingReview. Each feed element includes no more than the
specified number of comments.

API Version
31.0

770
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer

771
Apex Reference Guide ChatterFeeds Class

Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, showInternalOnly)
Get a page of sorted feed elements from a record feed. Each feed element includes no more than the specified number of comments.
Specify whether to return feed elements posted by internal (non-Experience Cloud site) users only.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

772
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.

773
Apex Reference Guide ChatterFeeds Class

• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, filter)
Get a page of sorted and filtered feed elements from the UserProfile feed.

API Version
35.0

Available to Guest Users


35.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedFilter filter)

774
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter

775
Apex Reference Guide ChatterFeeds Class

Value must be ConnectApi.FeedFilter.CommunityScoped or ConnectApi.FeedFilter.AuthoredBy.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

Example
This example gets only community-specific feed elements.
ConnectApi.FeedElementPage fep =
ConnectApi.ChatterFeeds.getFeedElementsFromFeed(Network.getNetworkId(),
ConnectApi.FeedType.UserProfile, 'me', 3, ConnectApi.FeedDensity.FewerUpdates, null, null,
ConnectApi.FeedSortOrder.LastModifiedDateDesc, ConnectApi.FeedFilter.CommunityScoped);

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, filter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, filter, threadedCommentsCollapsed)
Get a page of feed elements with comments in a threaded style from the UserProfile feed.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedFilter filter, Boolean
threadedCommentsCollapsed)

776
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter

777
Apex Reference Guide ChatterFeeds Class

Value must be ConnectApi.FeedFilter.CommunityScoped or ConnectApi.FeedFilter.AuthoredBy.


threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, filter, threadedCommentsCollapsed, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, customFilter)
Get a page of sorted and filtered feed elements from the case feed.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String customFilter)

Parameters
communityId
Type: String

778
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.

779
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, customFilter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


elementsPerBundle, density, pageParam, pageSize, sortParam, showInternalOnly)
Get a page of sorted feed elements from a record feed. Specify the number of elements per bundle and include no more than the
specified number of comments per feed element. Specify whether to return feed elements posted by internal (non-Experience Cloud
site) users only.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.

780
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

781
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


elementsPerBundle, density, pageParam, pageSize, sortParam, showInternalOnly,
filter)
Get a page of sorted and filtered feed elements from a record feed. Specify the number of elements per bundle and include no more
than the specified number of comments per feed element. Specify whether to return feed elements posted by internal (non-Experience
Cloud site) users only.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, ConnectApi.FeedFilter
filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType

782
Apex Reference Guide ChatterFeeds Class

Value must be ConnectApi.FeedType.Record.


subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter

783
Apex Reference Guide ChatterFeeds Class

Specifies the feed filters.


• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


elementsPerBundle, density, pageParam, pageSize, sortParam, showInternalOnly,
filter, threadedCommentsCollapsed)
Get a page of sorted and filtered feed elements with comments in a threaded style for a record feed. Specify the number of elements
per bundle and include no more than the specified number of comments per feed element. Specify whether to return feed elements
posted by internal (non-Experience Cloud site) users only.

784
Apex Reference Guide ChatterFeeds Class

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, ConnectApi.FeedFilter
filter, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String

785
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.

786
Apex Reference Guide ChatterFeeds Class

• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter, threadedCommentsCollapsed, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


elementsPerBundle, density, pageParam, pageSize, sortParam, showInternalOnly,
customFilter)
Get a page of sorted and filtered feed elements from a case feed.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, String customFilter)

787
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.

788
Apex Reference Guide ChatterFeeds Class

If you pass in null, the default value CreatedDateDesc is used.


showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,


elementsPerBundle, density, pageParam, pageSize, sortParam, showInternalOnly,
customFilter, threadedCommentsCollapsed)
Get a page of filtered and sorted feed elements with comments in a threaded style from a case feed.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, String customFilter,
Boolean threadedCommentsCollapsed)

789
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.

790
Apex Reference Guide ChatterFeeds Class

If you pass in null, the default value CreatedDateDesc is used.


showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter, threadedCommentsCollapsed, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix)


Get feed elements from a feed filtered by a key prefix for a user.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFilterFeed(String
communityId, String subjectId, String keyPrefix)

791
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam,


pageSize, sortParam)
Get a page of sorted feed elements from a feed filtered by a key prefix for a user.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFilterFeed(String
communityId, String subjectId, String keyPrefix, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

792
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

793
Apex Reference Guide ChatterFeeds Class

getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam)
Get a page of sorted feed elements from a feed filtered by a key prefix for a user. Each feed element contains no more than the specified
number of comments.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFilterFeed(String
communityId, String subjectId, String keyPrefix, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.

794
Apex Reference Guide ChatterFeeds Class

• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince)
Get a page of feed elements from a feed filtered by a key prefix for a user. Include only feed elements that have been updated since the
time specified in the updatedSince parameter.

API Version
31.0

795
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsFromFilterFeedUpdatedSince(String
communityId, String subjectId, String keyPrefix, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

796
Apex Reference Guide ChatterFeeds Class

updatedSince
Type: String
Opaque token defining the modification timestamp of the feed and the sort order.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle,
density, pageParam, pageSize, updatedSince, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, updatedSince)
Get a page of feed elements from the Company, DirectMessageModeration, Home, and Moderation feeds. Include only
feed elements that have been updated since the time specified in the updatedSince parameter. Each feed element contains no
more than the specified number of comments.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, String updatedSince)

Parameters
communityId
Type: String

797
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, and Moderation.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince,
result)
Apex Developer Guide: Testing ConnectApi Code

798
Apex Reference Guide ChatterFeeds Class

getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, updatedSince, filter)
Get a page of filtered feed elements from the Home feed. Include only feed elements that have been updated since the time specified
in the updatedSince parameter. Each feed element contains no more than the specified number of comments.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, String updatedSince, ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.

799
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

Return Value
Type: ConnectApi.FeedElementPage

800
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince,
filter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, updatedSince)
Get a page of feed elements from the Files, Groups, News, People, and Record feeds. Include only feed elements that have
been updated since the time specified in the updatedSince parameter. Each feed element contains no more than the specified
number of comments.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of these values:
• Files
• Groups
• News
• People

801
Apex Reference Guide ChatterFeeds Class

• Record
subjectId
Type: String
If feedType is ConnectApi.Record, subjectId can be any record ID, including a group ID. Otherwise, it must be the
context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, result)
Apex Developer Guide: Testing ConnectApi Code

802
Apex Reference Guide ChatterFeeds Class

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly)
Get a page of feed elements from a record feed. Include only feed elements that have been updated since the time specified in the
updatedSince parameter. Specify whether to return feed elements posted by internal (non-Experience Cloud site) users only.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince,
Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.

803
Apex Reference Guide ChatterFeeds Class

• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, filter)
Get a page of filtered feed elements from a UserProfile feed. Include only feed elements that have been updated since the time
specified in the updatedSince parameter.

API Version
35.0

804
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


35.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer

805
Apex Reference Guide ChatterFeeds Class

Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
Opaque token defining the modification timestamp of the feed and the sort order.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
filter
Type: ConnectApi.FeedFilter
Value must be ConnectApi.FeedFilter.CommunityScoped. Filters the feed to include only feed elements that are
scoped to Experience Cloud sites. Feed elements that are always visible in all sites are filtered out.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, filter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, customFilter)
Get a page of filtered feed elements from a case feed. Include only feed elements that have been updated since the time specified in
the updatedSince parameter.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer

806
Apex Reference Guide ChatterFeeds Class

elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,


String updatedSince, String customFilter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
Opaque token defining the modification timestamp of the feed and the sort order.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.

807
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, customFilter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, showInternalOnly)
Get a page of feed elements from a record feed. Include only feed elements that have been updated since the time specified in the
updatedSince parameter. Specify the maximum number of feed elements in a bundle and whether to return feed elements posted
by internal (non-Experience Cloud site) users only.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.

808
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

Return Value
Type: ConnectApi.FeedElementPage

809
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, showInternalOnly, filter)
Get a page of filtered feed elements from a record feed. Include only feed elements that have been updated since the time specified in
the updatedSince parameter. Specify the maximum number of feed elements in a bundle and whether to return feed elements
posted by internal (non-Experience Cloud site) users only.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, Boolean showInternalOnly, ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.

810
Apex Reference Guide ChatterFeeds Class

recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.

811
Apex Reference Guide ChatterFeeds Class

• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate


answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, showInternalOnly, filter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, showInternalOnly, customFilter)
Get a page of filtered feed elements from a case feed. Include only feed elements that have been updated since the time specified in
the updatedSince parameter.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

812
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElementPage getFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, Boolean showInternalOnly, String customFilter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.

813
Apex Reference Guide ChatterFeeds Class

showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, showInternalOnly, customFilter, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedWithFeedElements(communityId, feedType, pageSize)


Get information about a feed and a page of feed elements from the feed.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFeedWithFeedElements(String communityId,
ConnectApi.FeedType feedType, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

814
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
The type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Landing, Moderation, and PendingReview. Landing is valid only when communityId is internal.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in 0, feed elements aren’t returned
with the feed.

Return Value
Type: ConnectApi.Feed

getFeedWithFeedElements(communityId, feedType, pageSize, recentCommentCount)


Get a page of information about the feed and the feed elements with the specified number of comments per feed element from the
feed.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFeedWithFeedElements(String communityId,
ConnectApi.FeedType feedType, Integer pageSize, Integer recentCommentCount)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Landing, Moderation, and PendingReview. Landing is valid only when communityId is internal.
pageSize
Type: Integer

815
Apex Reference Guide ChatterFeeds Class

Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in 0, feed elements aren’t returned
with the feed.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.

Return Value
Type: ConnectApi.Feed

getFilterFeed(communityId, subjectId, keyPrefix)


Get a feed filtered by a key prefix for a user.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFilterFeed(String communityId, String subjectId, String
keyPrefix)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix is the first three characters of a record ID, which specifies the object type.

Return Value
Type: ConnectApi.Feed

getFilterFeed(communityId, subjectId, keyPrefix, sortParam)


Get a sorted feed filtered by a key prefix for a user.

816
Apex Reference Guide ChatterFeeds Class

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.Feed getFilterFeed(String communityId, String subjectId, String
keyPrefix, ConnectApi.FeedType sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
sortParam
Type: ConnectApi.FeedType
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.Feed

getFilterFeedDirectory(communityId, subjectId)
Get a feed directory of filter feeds available to the context user.

817
Apex Reference Guide ChatterFeeds Class

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedDirectory getFilterFeedDirectory(String communityId, String
subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.

Return Value
Type: ConnectApi.FeedDirectory
This feed directory contains a list of filter feeds, which are the news feed filtered to include feed items whose parent is a specific entity
type.

Usage
Call this method to return a directory containing a list of ConnectApi.FeedDirectoryItem objects. Each object contains a
key prefix associated with an entity type the context user is following. A key prefix is the first three characters of a record ID, which specifies
the object type.
Use key prefixes to filter the news feed so that it contains only feed items whose parent is the entity type associated with the key prefix.
For example, get all the feed items whose parent is an Account. To get the feed items, pass a key prefix to the
ConnectApi.getFeedItemsFromFilterFeed method.
The information about filter feeds never contains the key prefixes for users (005) or groups (0F9), but all users can use those key prefixes
as filters.
The ConnectApi.FeedDirectory.favorites property is always empty when returned by a call to
getFilterFeedDirectory because you can’t filter a news feed by favorites.

Example
This example calls getFilterFeedDirectory and loops through the returned FeedDirectoryItem objects to find the
key prefixes the context user can use to filter their news feed. It then copies each keyPrefix value to a list. Finally, it passes one of

818
Apex Reference Guide ChatterFeeds Class

the key prefixes from the list to the getFeedItemsFromFilterFeed method. The returned feed items include every feed item
from the news feed whose parent is the entity type specified by the passed key prefix.
String communityId = null;
String subjectId = 'me';

// Create a list to populate with key prefixes.


List<String> keyPrefixList = new List<String>();

// Prepopulate with User and Group record types


// which are available to all users.
keyPrefixList.add('005');
keyPrefixList.add('0F9');

System.debug(keyPrefixList);

// Get the key prefixes available to the context user.


ConnectApi.FeedDirectory myFeedDirectory =
ConnectApi.ChatterFeeds.getFilterFeedDirectory(null, 'me');

// Loop through the returned feeds list.


for (ConnectApi.FeedDirectoryItem i : myFeedDirectory.feeds) {

// Grab each key prefix and add it to the list.


keyPrefixList.add(i.keyPrefix);
}
System.debug(keyPrefixList);

// Use a key prefix from the list to filter the feed items in the news feed.
ConnectApi.FeedItemPage myFeedItemPage =
ConnectApi.ChatterFeeds.getFeedItemsFromFilterFeed(communityId, subjectId,
keyPrefixList[0]);
System.debug(myFeedItemPage);

getLike(communityId, likeId)
Get a like on a post or comment.

API Version
28.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLike getLike(String communityId, String likeId)

819
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
likeId
Type: String
ID for a like.

Return Value
Type: ConnectApi.ChatterLike

getLikesForComment(communityId, commentId)
Get likes for a comment.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage getLikesForComment(String communityId, String
commentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID for a comment.

Return Value
Type: ConnectApi.ChatterLikePage

820
Apex Reference Guide ChatterFeeds Class

getLikesForComment(communityId, commentId, pageParam, pageSize)


Get a page of likes for a comment.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage getLikesForComment(String communityId, String
commentId, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID for a comment.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterLikePage

getLikesForFeedElement(communityId, feedElementId)
Get likes for a feed element.

API Version
32.0

821
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage getLikesForFeedElement(String communityId,
String feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.ChatterLikePage
If the feed element doesn’t support the ChatterLikes capability, the return value is ConnectApi.NotFoundException.

getLikesForFeedElement(communityId, feedElementId, pageParam, pageSize)


Get a page of likes for a feed element.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage getLikesForFeedElement(String communityId,
String feedElementId, Integer pageParam, Integer pageSize)

822
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterLikePage
If the feed element doesn’t support the ChatterLikes capability, the return value is ConnectApi.NotFoundException.

getLinkMetadata(communityId, urls)
Get link metadata for URLs.

API Version
42.0

Available to Guest Users


42.0

Requires Chatter
No

Signature
public static ConnectApi.LinkMetadataCollection getLinkMetadata(String communityId,
String urls)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

823
Apex Reference Guide ChatterFeeds Class

urls
Type: String
Comma-separated list of URL-encoded URLs.

Return Value
Type: ConnectApi.LinkMetadataCollection

getPinnedFeedElementsFromFeed(communityId, feedType, subjectId)


Get pinned feed elements from a group or topic feed.

API Version
41.0

Available to Guest Users


41.0

Requires Chatter
Yes

Signature
public static ConnectApi.PinnedFeedElements getPinnedFeedElementsFromFeed(String
communityId, ConnectApi.FeedType feedType, String subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. Valid values are Record and Topics.
subjectId
Type: String
If feedType is Record, subjectId must be a group ID. If feedType is Topics, subjectId must be a topic ID.

Return Value
Type: ConnectApi.PinnedFeedElements
If the feed doesn’t support this capability, the return value is ConnectApi.NotFoundException.

824
Apex Reference Guide ChatterFeeds Class

Usage
In the UI, pinned feed elements don’t show all auxiliary information, such as comments, likes, interaction counts, or read by information.
As a result, the ConnectApi.PinnedFeedElements output class doesn’t include all the information for these capabilities.

getReadByForFeedElement(communityId, feedElementId)
Get information about who read a feed element and when.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ReadByPage getReadByForFeedElement(String communityId, String
feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.ReadByPage
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

getReadByForFeedElement(communityId, feedElementId, pageParam, pageSize)


Get a page of information about who read a feed element and when.

API Version
40.0

Requires Chatter
Yes

825
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.ReadByPage getReadByForFeedElement(String communityId, String
feedElementId, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ReadByPage
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

getRelatedPosts(communityId, feedElementId, filter, maxResults)


Get posts related to the context feed element.

API Version
37.0

Available to Guest Users


37.0

Requires Chatter
Yes

Signature
public static ConnectApi.RelatedFeedPosts getRelatedPosts(String communityId, String
feedElementId, ConnectApi.RelatedFeedPostType filter, Integer maxResults)

826
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element. The feed element must be a question.
filter
Type: ConnectApi.RelatedFeedPostType
Specifies the type of related post. Values are:
• Answered—Related questions that have at least one answer.
• BestAnswer—Related questions that have a best answer.
• Generic—All types of related questions, including answered, with a best answer, and unanswered.
• Unanswered—Related questions that don’t have answers.
Generic is the default value.
maxResults
Type: Integer
The maximum number of results to return. You can return up to 25 results; 5 is the default.

Return Value
Type: ConnectApi.RelatedFeedPosts
In version 37.0 and later, related feed posts are questions.
Each related feed post has a score indicating how closely it’s related to the context feed post. We return related feed posts sorted by
score, with the highest score first.

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

getStream(communityId, streamId)
Get information about a Chatter feed stream.

API Version
39.0

Requires Chatter
Yes

827
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.ChatterStream getStream(String communityId, String streamId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
streamId
Type: String
ID of the Chatter feed stream.

Return Value
Type: ConnectApi.ChatterStream

getStream(communityId, streamId, globalScope)


Get information about a Chatter feed stream, regardless of Experience Cloud site.

API Version
41.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStream getStream(String communityId, String streamId,
Boolean globalScope)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
streamId
Type: String
ID of the Chatter feed stream.
globalScope
Type: Boolean
Specifies whether to get streams from all the context user’s Experience Cloud sites, regardless of the communityId value.

Tip: If you know the communityId for the stream, we recommend setting globalScope to false.

828
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.ChatterStream

getStreams(communityId)
Get the Chatter feed streams for the context user.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage getStreams(String communityId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

Return Value
Type: ConnectApi.ChatterStreamPage

getStreams(communityId, sortParam)
Get and sort the Chatter feed streams for the context user.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage getStreams(String communityId,
ConnectApi.SortOrder sortParam)

Parameters
communityId
Type: String

829
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.

Return Value
Type: ConnectApi.ChatterStreamPage

getStreams(communityId, pageParam, pageSize)


Get a page of Chatter feed streams for the context user.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage getStreams(String communityId, Integer
pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.

Return Value
Type: ConnectApi.ChatterStreamPage

830
Apex Reference Guide ChatterFeeds Class

getStreams(communityId, pageParam, pageSize, sortParam)


Get a sorted page of Chatter feed streams for the context user.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage getStreams(String communityId, Integer
pageParam, Integer pageSize, ConnectApi.SortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.

Return Value
Type: ConnectApi.ChatterStreamPage

getStreams(communityId, pageParam, pageSize, sortParam, globalScope)


Get a sorted page of Chatter feed streams from all Enterprise Cloud sites for the context user.

831
Apex Reference Guide ChatterFeeds Class

API Version
41.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage getStreams(String communityId, Integer
pageParam, Integer pageSize, ConnectApi.SortOrder sortParam, Boolean globalScope)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.
globalScope
Type: Boolean
Specifies whether to get streams from all the context user’s Experience Cloud sites, regardless of the communityId value.

Tip: If you know the communityId for the streams, we recommend setting globalScope to false.

Return Value
Type: ConnectApi.ChatterStreamPage

getSupportedEmojis()
Get supported emojis for the org.

832
Apex Reference Guide ChatterFeeds Class

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.SupportedEmojis getSupportedEmojis()

Return Value
Type: ConnectApi.SupportedEmojis

Usage
To get the list, emojis must be enabled in your org.

getThreadsForFeedComment(communityId, commentId)
Get threaded comments for a comment.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getThreadsForFeedComment(String communityId, String
commentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.

833
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.CommentPage
If the comment doesn’t support the comments capability, the return value is ConnectApi.NotFoundException.

getThreadsForFeedComment(communityId, commentId, pageParam, pageSize)


Get a page of threaded comments for a comment.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getThreadsForFeedComment(String communityId, String
commentId, String pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.CommentPage
If the comment doesn’t support the comments capability, the return value is ConnectApi.NotFoundException.

834
Apex Reference Guide ChatterFeeds Class

getThreadsForFeedComment(communityId, commentId, threadedCommentsCollapsed)


Access the comments capability for a comment.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.CommentsCapability getThreadsForFeedComment(String communityId,
String commentId, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.CommentsCapability
If the comment doesn’t support the comments capability, the return value is ConnectApi.NotFoundException.

getTopUnansweredQuestions(communityId) (Pilot)
Get top unanswered questions for the context user in aExperience Cloud site.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

835
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getTopUnansweredQuestions(String communityId)

Parameters
communityId
Type: String
ID of the Experience Cloud site.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetTopUnansweredQuestions(communityId, result) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

getTopUnansweredQuestions(communityId, filter) (Pilot)


Get filtered top unanswered questions for the context user in an Experience Cloud site.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getTopUnansweredQuestions(String communityId,
ConnectApi.TopUnansweredQuestionsFilterType filter)

836
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID of the Experience Cloud site.
filter
Type: ConnectApi.FeedFilter
Specifies the filter for the feed. UnansweredQuestionsWithCandidateAnswers is the only valid value.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetTopUnansweredQuestions(communityId, filter, result) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

getTopUnansweredQuestions(communityId, pageSize) (Pilot)


Get a page of top unanswered questions for the context user in an Experience Cloud site.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getTopUnansweredQuestions(String communityId,
Integer pageSize)

Parameters
communityId
Type: String
ID of the Experience Cloud site.
pageSize
Type: Integer

837
Apex Reference Guide ChatterFeeds Class

Specifies the number of items per page. Valid values are from 0 through 10. If you pass in null, the default size is 5.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetTopUnansweredQuestions(communityId, pageSize, result) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

getTopUnansweredQuestions(communityId, filter, pageSize) (Pilot)


Get a page of filtered top unanswered questions for the context user in an Experience Cloud site.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage getTopUnansweredQuestions(String communityId,
ConnectApi.FeedFilter filter, Integer pageSize)

Parameters
communityId
Type: String
ID of the Experience Cloud site.
filter
Type: ConnectApi.FeedFilter
Specifies the filter for the feed. UnansweredQuestionsWithCandidateAnswers is the only valid value.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 0 through 10. If you pass in null, the default size is 5.

838
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetTopUnansweredQuestions(communityId, filter, pageSize, result) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

getVotesForComment(communityId, commentId, vote)


Get the first page of users who upvoted or downvoted a comment.

API Version
42.0

Available to Guest Users


42.0

Requires Chatter
Yes

Signature
public static ConnectApi.VotePage getVotesForComment(String communityId, String
commentId, ConnectApi.UpDownVoteValue vote)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
vote
Type: ConnectApi.UpDownVoteValue
Specifies the value of the vote for the feed element. Values are:
• Down
• Up

839
Apex Reference Guide ChatterFeeds Class

You can’t specify None.

Return Value
Type: ConnectApi.VotePage
If the comment doesn’t support this capability, the return value is ConnectApi.NotFoundException.

getVotesForComment(communityId, commentId, vote, pageParam, pageSize)


Get a page of users who upvoted or downvoted a comment.

API Version
42.0

Available to Guest Users


42.0

Requires Chatter
Yes

Signature
public static ConnectApi.VotePage getVotesForComment(String communityId, String
commentId, ConnectApi.UpDownVoteValue vote, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
vote
Type: ConnectApi.UpDownVoteValue
Specifies the value of the vote for the feed element. Values are:
• Down
• Up
You can’t specify None.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.

840
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.VotePage
If the comment doesn’t support this capability, the return value is ConnectApi.NotFoundException.

getVotesForFeedElement(communityId, feedElementId, vote)


Get the first page of users who upvoted or downvoted a feed element.

API Version
42.0

Available to Guest Users


42.0

Requires Chatter
Yes

Signature
public static ConnectApi.VotePage getVotesForFeedElement(String communityId, String
feedElementId, ConnectApi.UpDownVoteValue vote)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
vote
Type: ConnectApi.UpDownVoteValue
Specifies the value of the vote for the feed element. Values are:
• Down
• Up
You can’t specify None.

841
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.VotePage
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

getVotesForFeedElement(communityId, feedElementId, vote, pageParam, pageSize)


Get a page of users who upvoted or downvoted a feed element.

API Version
42.0

Available to Guest Users


42.0

Requires Chatter
Yes

Signature
public static ConnectApi.VotePage getVotesForFeedElement(String communityId, String
feedElementId, ConnectApi.UpDownVoteValue vote, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
vote
Type: ConnectApi.UpDownVoteValue
Specifies the value of the vote for the feed element. Values are:
• Down
• Up
You can’t specify None.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

842
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.VotePage
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

isCommentEditableByMe(communityId, commentId)
Discover whether the context user can edit a comment.

API Version
34.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedEntityIsEditable isCommentEditableByMe(String communityId,
String commentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.

Return Value
Type: ConnectApi.FeedEntityIsEditable
If the comment doesn’t support the edit capability, the return value is ConnectApi.NotFoundException.

SEE ALSO:
Edit a Comment

isFeedElementEditableByMe(communityId, feedElementId)
Discover whether the context user can edit a feed element.

API Version
34.0

843
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedEntityIsEditable isFeedElementEditableByMe(String
communityId, String feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element. Feed items are the only type of feed element that can be edited.

Return Value
Type: ConnectApi.FeedEntityIsEditable
If the feed element doesn’t support the edit capability, the return value is ConnectApi.NotFoundException.

SEE ALSO:
Edit a Feed Element
Edit a Question Title and Post

isModified(communityId, feedType, subjectId, since)


Discover whether a news feed has been updated or changed. Use this method to poll a news feed for updates.

Important: This feature is available through a Feed Polling pilot program. This pilot program is closed and not accepting new
participants.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedModifiedInfo isModified(String communityId,
ConnectApi.FeedType feedType, String subjectId, String since)

844
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Specifies the type of feed. The only supported type is News
subjectId
Type: String
ID of the context user or the alias me.
since
Type: String
An opaque token containing information about the last modified date of the feed. Retrieve this token from the
FeedElementPage.isModifiedToken property.

Return Value
Type: ConnectApi.FeedModifiedInfo

likeComment(communityId, commentId)
Like a comment for the context user.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLike likeComment(String communityId, String commentId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID for a comment.

845
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.ChatterLike
If the context user has already liked the comment, this method is a non-operation and returns the existing like.

likeFeedElement(communityId, feedElementId)
Like a feed element.

API Version
32.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLike likeFeedElement(String communityId, String
feedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

Return Value
Type: ConnectApi.ChatterLike
If the feed element doesn’t support the ChatterLikes capability, the return value is ConnectApi.NotFoundException.

Example
ConnectApi.ChatterLike chatterLike = ConnectApi.ChatterFeeds.likeFeedElement(null,
'0D5D0000000KuGh');

postCommentToFeedElement(communityId, feedElementId, text)


Post a plain-text comment to a feed element.

API Version
32.0

846
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.Comment postCommentToFeedElement(String communityId, String
feedElementId, String text)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
text
Type: String
Text of the comment. A comment can contain up to 10,000 characters.

Return Value
Type: ConnectApi.Comment
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

Example
ConnectApi.Comment comment = ConnectApi.ChatterFeeds.postCommentToFeedElement(null,
'0D5D0000000KuGh', 'I agree with the proposal.' );

postCommentToFeedElement(communityId, feedElementId, comment,


feedElementFileUpload)
Post a rich-text comment to a feed element. Use this method to include mentions and to attach a file.

API Version
32.0

Requires Chatter
Yes

847
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.Comment postCommentToFeedElement(String communityId, String
feedElementId, ConnectApi.CommentInput comment, ConnectApi.BinaryInput
feedElementFileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
comment
Type: ConnectApi.CommentInput
The comment body, including text and mentions, and capabilities, such as information about an attached file. A comment can
contain up to 10,000 characters.
feedElementFileUpload
Type: ConnectApi.BinaryInput
A new binary file to attach to the comment, or null. If you specify a binary file, specify the title and description of the file in the
comment parameter.

Return Value
Type: ConnectApi.Comment
If the feed element doesn’t support the Comments capability, the return value is ConnectApi.NotFoundException.

Example for Posting a Comment with Mentions


You can post comments with mentions two ways. Use the ConnectApiHelper repository on GitHub to write a single line of code, or use
this method example.
String communityId = null;
String feedElementId = '0D5D0000000KtW3';

ConnectApi.CommentInput commentInput = new ConnectApi.CommentInput();


ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

textSegmentInput.text = 'Does anyone in this group have an idea? ';


messageBodyInput.messageSegments.add(textSegmentInput);

mentionSegmentInput.id = '005D00000000oOT';
messageBodyInput.messageSegments.add(mentionSegmentInput);

848
Apex Reference Guide ChatterFeeds Class

commentInput.body = messageBodyInput;

ConnectApi.Comment commentRep = ConnectApi.ChatterFeeds.postCommentToFeedElement(communityId,


feedElementId, commentInput, null);

Example for Posting a Comment with an Existing File


String feedElementId = '0D5D0000000KtW3';

ConnectApi.CommentInput commentInput = new ConnectApi.CommentInput();

ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();


ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

textSegmentInput.text = 'I attached this file from Salesforce Files.';

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();


messageBodyInput.messageSegments.add(textSegmentInput);
commentInput.body = messageBodyInput;

ConnectApi.CommentCapabilitiesInput commentCapabilitiesInput = new


ConnectApi.CommentCapabilitiesInput();
ConnectApi.ContentCapabilityInput contentCapabilityInput = new
ConnectApi.ContentCapabilityInput();

commentCapabilitiesInput.content = contentCapabilityInput;
contentCapabilityInput.contentDocumentId = '069D00000001rNJ';

commentInput.capabilities = commentCapabilitiesInput;

ConnectApi.Comment commentRep =
ConnectApi.ChatterFeeds.postCommentToFeedElement(Network.getNetworkId(), feedElementId,
commentInput, null);

Example for Posting a Comment with a New File


String feedElementId = '0D5D0000000KtW3';

ConnectApi.CommentInput commentInput = new ConnectApi.CommentInput();

ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();


ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

textSegmentInput.text = 'Enjoy this new file.';

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();


messageBodyInput.messageSegments.add(textSegmentInput);
commentInput.body = messageBodyInput;

ConnectApi.CommentCapabilitiesInput commentCapabilitiesInput = new


ConnectApi.CommentCapabilitiesInput();
ConnectApi.ContentCapabilityInput contentCapabilityInput = new

849
Apex Reference Guide ChatterFeeds Class

ConnectApi.ContentCapabilityInput();

commentCapabilitiesInput.content = contentCapabilityInput;
contentCapabilityInput.title = 'Title';

commentInput.capabilities = commentCapabilitiesInput;

String text = 'These are the contents of the new file.';


Blob myBlob = Blob.valueOf(text);
ConnectApi.BinaryInput binInput = new ConnectApi.BinaryInput(myBlob, 'text/plain',
'fileName');

ConnectApi.Comment commentRep =
ConnectApi.ChatterFeeds.postCommentToFeedElement(Network.getNetworkId(), feedElementId,
commentInput, binInput);

Example for Posting a Rich-Text Comment with an Inline Image


You can post rich-text comments with inline images and mentions two ways. Use the ConnectApiHelper repository on GitHub to write
a single line of code, or use this method example. In this example, the image file is existing content that has already been uploaded to
Salesforce.
String communityId = null;
String feedElementId = '0D5R0000000SBEr';
String imageId = '069R00000000IgQ';
String mentionedUserId = '005R0000000DiMz';

ConnectApi.CommentInput input = new ConnectApi.CommentInput();


ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegment;
ConnectApi.MentionSegmentInput mentionSegment;
ConnectApi.MarkupBeginSegmentInput markupBeginSegment;
ConnectApi.MarkupEndSegmentInput markupEndSegment;
ConnectApi.InlineImageSegmentInput inlineImageSegment;

messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

markupBeginSegment = new ConnectApi.MarkupBeginSegmentInput();


markupBeginSegment.markupType = ConnectApi.MarkupType.Bold;
messageInput.messageSegments.add(markupBeginSegment);

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = 'Hello ';
messageInput.messageSegments.add(textSegment);

mentionSegment = new ConnectApi.MentionSegmentInput();


mentionSegment.id = mentionedUserId;
messageInput.messageSegments.add(mentionSegment);

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = '!';
messageInput.messageSegments.add(textSegment);

850
Apex Reference Guide ChatterFeeds Class

markupEndSegment = new ConnectApi.MarkupEndSegmentInput();


markupEndSegment.markupType = ConnectApi.MarkupType.Bold;
messageInput.messageSegments.add(markupEndSegment);

inlineImageSegment = new ConnectApi.InlineImageSegmentInput();


inlineImageSegment.altText = 'image one';
inlineImageSegment.fileId = imageId;
messageInput.messageSegments.add(inlineImageSegment);

input.body = messageInput;

ConnectApi.ChatterFeeds.postCommentToFeedElement(communityId, feedElementId, input, null);

Example for Posting a Rich-Text Comment with a Code Block


String communityId = null;
String feedElementId = '0D5R0000000SBEr';
String codeSnippet = '<html>\n\t<body>\n\t\tHello, world!\n\t</body>\n</html>';

ConnectApi.CommentInput input = new ConnectApi.CommentInput();


ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegment;
ConnectApi.MarkupBeginSegmentInput markupBeginSegment;
ConnectApi.MarkupEndSegmentInput markupEndSegment;

messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

markupBeginSegment = new ConnectApi.MarkupBeginSegmentInput();


markupBeginSegment.markupType = ConnectApi.MarkupType.Code;
messageInput.messageSegments.add(markupBeginSegment);

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = codeSnippet;
messageInput.messageSegments.add(textSegment);

markupEndSegment = new ConnectApi.MarkupEndSegmentInput();


markupEndSegment.markupType = ConnectApi.MarkupType.Code;
messageInput.messageSegments.add(markupEndSegment);

input.body = messageInput;

ConnectApi.ChatterFeeds.postCommentToFeedElement(communityId, feedElementId, input, null);

postFeedElement(communityId, subjectId, feedElementType, text)


Post a plain-text feed element.

API Version
31.0

851
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement postFeedElement(String communityId, String
subjectId, ConnectApi.FeedElementType feedElementType, String text)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
The ID of the parent this feed element is being posted to. This value can be the ID of a user, group, or record, or the string me to
indicate the context user.
feedElementType
Type: ConnectApi.FeedElementType
The only possible value is FeedItem.
text
Type: String
The text of the feed element. A feed element can contain up to 10,000 characters.

Return Value
Type: ConnectApi.FeedElement

Example
ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), '0F9d0000000TreH',
ConnectApi.FeedElementType.FeedItem, 'On vacation this week.');

postFeedElement(communityId, feedElement)
Post a rich-text feed element. Include mentions and hashtag topics, attach already uploaded files to a feed element, and associate action
link groups with a feed element. You can also use this method to share a feed element and add a comment.

API Version
36.0

Requires Chatter
Yes

852
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElement postFeedElement(String communityId,
ConnectApi.FeedElementInput feedElement)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElement
Type: ConnectApi.FeedElementInput
Specify rich text, including mentions. Optionally, specify a link, a poll, or up to 10 existing files.

Return Value
Type: ConnectApi.FeedElement

Example for Posting a Feed Element with a Mention


You can post feed elements with mentions two ways. Use the ConnectApiHelper repository on GitHub to write a single line of code, or
use this method example.
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

mentionSegmentInput.id = '005RR000000Dme9';
messageBodyInput.messageSegments.add(mentionSegmentInput);

textSegmentInput.text = 'Could you take a look?';


messageBodyInput.messageSegments.add(textSegmentInput);

feedItemInput.body = messageBodyInput;
feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
feedItemInput.subjectId = '0F9RR0000004CPw';

ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);

Example for Posting a Feed Element with Existing Content


// Define the FeedItemInput object to pass to postFeedElement
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
feedItemInput.subjectId = 'me';

ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();


textSegmentInput.text = 'Would you please review these docs?';

853
Apex Reference Guide ChatterFeeds Class

// The MessageBodyInput object holds the text in the post


ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
messageBodyInput.messageSegments.add(textSegmentInput);
feedItemInput.body = messageBodyInput;

// The FeedElementCapabilitiesInput object holds the capabilities of the feed item.


// For this feed item, we define a files capability to hold the file(s).

List<String> fileIds = new List<String>();


fileIds.add('069xx00000000QO');
fileIds.add('069xx00000000QT');
fileIds.add('069xx00000000Qn');
fileIds.add('069xx00000000Qi');
fileIds.add('069xx00000000Qd');

ConnectApi.FilesCapabilityInput filesInput = new ConnectApi.FilesCapabilityInput();


filesInput.items = new List<ConnectApi.FileIdInput>();

for (String fileId : fileIds) {


ConnectApi.FileIdInput idInput = new ConnectApi.FileIdInput();
idInput.id = fileId;
filesInput.items.add(idInput);
}

ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new


ConnectApi.FeedElementCapabilitiesInput();
feedElementCapabilitiesInput.files = filesInput;

feedItemInput.capabilities = feedElementCapabilitiesInput;

// Post the feed item.


ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);

Example for Posting a Rich-Text Feed Element with an Inline Image


You can post rich-text feed elements with inline images and mentions two ways. Use the ConnectApiHelper repository on GitHub to
write a single line of code, or use this method example. In this example, the image file is existing content that has already been uploaded
to Salesforce. The post also includes text and a mention.
String communityId = null;
String imageId = '069D00000001INA';
String mentionedUserId = '005D0000001QNpr';
String targetUserOrGroupOrRecordId = '005D0000001Gif0';
ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
input.subjectId = targetUserOrGroupOrRecordId;
input.feedElementType = ConnectApi.FeedElementType.FeedItem;

ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();


ConnectApi.TextSegmentInput textSegment;
ConnectApi.MentionSegmentInput mentionSegment;
ConnectApi.MarkupBeginSegmentInput markupBeginSegment;
ConnectApi.MarkupEndSegmentInput markupEndSegment;

854
Apex Reference Guide ChatterFeeds Class

ConnectApi.InlineImageSegmentInput inlineImageSegment;

messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

markupBeginSegment = new ConnectApi.MarkupBeginSegmentInput();


markupBeginSegment.markupType = ConnectApi.MarkupType.Bold;
messageInput.messageSegments.add(markupBeginSegment);

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = 'Hello ';
messageInput.messageSegments.add(textSegment);

mentionSegment = new ConnectApi.MentionSegmentInput();


mentionSegment.id = mentionedUserId;
messageInput.messageSegments.add(mentionSegment);

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = '!';
messageInput.messageSegments.add(textSegment);

markupEndSegment = new ConnectApi.MarkupEndSegmentInput();


markupEndSegment.markupType = ConnectApi.MarkupType.Bold;
messageInput.messageSegments.add(markupEndSegment);

inlineImageSegment = new ConnectApi.InlineImageSegmentInput();


inlineImageSegment.altText = 'image one';
inlineImageSegment.fileId = imageId;
messageInput.messageSegments.add(inlineImageSegment);

input.body = messageInput;

ConnectApi.ChatterFeeds.postFeedElement(communityId, input);

Example for Posting a Rich-Text Feed Element with a Code Block


String communityId = null;
String targetUserOrGroupOrRecordId = 'me';
String codeSnippet = '<html>\n\t<body>\n\t\tHello, world!\n\t</body>\n</html>';
ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
input.subjectId = targetUserOrGroupOrRecordId;
input.feedElementType = ConnectApi.FeedElementType.FeedItem;

ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();


ConnectApi.TextSegmentInput textSegment;
ConnectApi.MarkupBeginSegmentInput markupBeginSegment;
ConnectApi.MarkupEndSegmentInput markupEndSegment;

messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

markupBeginSegment = new ConnectApi.MarkupBeginSegmentInput();


markupBeginSegment.markupType = ConnectApi.MarkupType.Code;
messageInput.messageSegments.add(markupBeginSegment);

textSegment = new ConnectApi.TextSegmentInput();

855
Apex Reference Guide ChatterFeeds Class

textSegment.text = codeSnippet;
messageInput.messageSegments.add(textSegment);

markupEndSegment = new ConnectApi.MarkupEndSegmentInput();


markupEndSegment.markupType = ConnectApi.MarkupType.Code;
messageInput.messageSegments.add(markupEndSegment);

input.body = messageInput;

ConnectApi.ChatterFeeds.postFeedElement(communityId, input);

Example for Sharing a Feed Element (in Version 39.0 and Later)
// Define the FeedItemInput object to pass to postFeedElement
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
feedItemInput.subjectId = 'me';
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
textSegmentInput.text = 'Look at this post I'm sharing.';
// The MessageBodyInput object holds the text in the post
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
messageBodyInput.messageSegments.add(textSegmentInput);
feedItemInput.body = messageBodyInput;

ConnectApi.FeedEntityShareCapabilityInput shareInput = new


ConnectApi.FeedEntityShareCapabilityInput();
shareInput.feedEntityId = '0D5R0000000SEbc';
ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new
ConnectApi.FeedElementCapabilitiesInput();
feedElementCapabilitiesInput.feedEntityShare = shareInput;
feedItemInput.capabilities = feedElementCapabilitiesInput;
// Post the feed item.
ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);

Example for Sending a Direct Message


// Define the FeedItemInput object to pass to postFeedElement
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();

ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();


textSegmentInput.text = 'Thanks for attending my presentation test run this morning. Send
me any feedback.';

// The MessageBodyInput object holds the text in the post


ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
messageBodyInput.messageSegments.add(textSegmentInput);
feedItemInput.body = messageBodyInput;

// The FeedElementCapabilitiesInput object holds the capabilities of the feed item.


// For this feed item, we define a direct message capability to hold the member(s) and the
subject.

856
Apex Reference Guide ChatterFeeds Class

List<String> memberIds = new List<String>();


memberIds.add('005B00000016OUQ');
memberIds.add('005B0000001rIN6');

ConnectApi.DirectMessageCapabilityInput dmInput = new


ConnectApi.DirectMessageCapabilityInput();
dmInput.subject = 'Thank you!';
dmInput.membersToAdd = memberIds;

ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new


ConnectApi.FeedElementCapabilitiesInput();
feedElementCapabilitiesInput.directMessage = dmInput;

feedItemInput.capabilities = feedElementCapabilitiesInput;

// Post the feed item.


ConnectApi.FeedElement feedElement =
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);

postFeedElementBatch(communityId, feedElements)
Post a list of feed elements.

API Version
32.0

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] postFeedElementBatch(String communityId,
List<ConnectApi.BatchInput> feedElements)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElements
Type: List<ConnectApi.BatchInput>
The list can contain up to 500 ConnectApi.BatchInput objects. In the ConnectApi.BatchInput constructor, the
input object must be a concrete instance of the abstract ConnectApi.FeedElementInput class.

Return Value
Type: ConnectApi.BatchResult[]

857
Apex Reference Guide ChatterFeeds Class

The ConnectApi.BatchResult.getResult() method returns a ConnectApi.FeedElement object.


The returned objects correspond to each of the input objects and are returned in the same order as the input objects.
The method call fails only if an error occurs that affects the entire operation (such as a parsing failure). If an individual object causes an
error, the error is embedded within the ConnectApi.BatchResult list.

Usage
Use this method to post a list of feed elements efficiently. Create a list containing up to 500 objects and insert them all for the cost of
one DML statement.
In version 36.0 and later, you can attach only one already uploaded file to each post. The ConnectApi.BatchInput has three
constructors, but the postFeedElementBatch method supports only ConnectApi.BatchInput(Object input)
in version 35.0 and later. This constructor doesn’t support a binary input.
In version 32.0–35.0, this method supports both ConnectApi.BatchInput(Object input) and
ConnectApi.BatchInput(Object input, ConnectApi.BinaryInput binary) constructors. The
ConnectApi.BatchInput(Object input, ConnectApi.BinaryInput binary) constructor allows for a single
binary input.
In each constructor, the input object must be an instance of ConnectApi.FeedElementInput.

Example
This trigger bulk posts to the feeds of newly inserted accounts.
trigger postFeedItemToAccount on Account (after insert) {
Account[] accounts = Trigger.new;

// Bulk post to the account feeds.

List<ConnectApi.BatchInput> batchInputs = new List<ConnectApi.BatchInput>();

for (Account a : accounts) {


ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();

input.subjectId = a.id;

ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();


body.messageSegments = new List<ConnectApi.MessageSegmentInput>();

ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = 'Let\'s win the ' + a.name + ' account.';

body.messageSegments.add(textSegment);
input.body = body;

ConnectApi.BatchInput batchInput = new ConnectApi.BatchInput(input);


batchInputs.add(batchInput);
}

ConnectApi.ChatterFeeds.postFeedElementBatch(Network.getNetworkId(), batchInputs);
}

858
Apex Reference Guide ChatterFeeds Class

publishDraftFeedElement(communityId, feedElementId, feedElement)


Publish a draft feed element.

API Version
44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement publishDraftFeedElement(String communityId, String
feedElementId, ConnectApi.FeedElementInput feedElement)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element to publish.
feedElement
Type: ConnectApi.FeedElementInput
Use this optional parameter to edit your draft before publishing.

Return Value
Type: ConnectApi.FeedElement
The published feed element has a new ID.

searchFeedElements(communityId, q)
Get the first page of feed elements that match the search criteria.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

859
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElements(communityId, q, sortParam)
Get the first page of sorted feed elements that match the search criteria.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q, ConnectApi.FeedSortOrder sortParam)

860
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElements(communityId, q, threadedCommentsCollapsed)
Get the feed elements and comments that match the search criteria.

API Version
44.0

Available to Guest Users


44.0

861
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, threadedCommentsCollapsed, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElements(communityId, q, pageParam, pageSize)


Get a page of feed elements that match the search criteria.

API Version
31.0

Available to Guest Users


31.0

862
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q, String pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, pageParam, pageSize, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElements(communityId, q, pageParam, pageSize, sortParam)


Get a page of sorted feed elements that match the search criteria.

API Version
31.0

863
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

864
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElements(communityId, q, pageParam, pageSize,


threadedCommentsCollapsed)
Get a page of feed elements with comments in a threaded style that match the search criteria.

API Version
44.0

Available to Guest Users


44.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q, String pageParam, Integer pageSize, Boolean threadedCommentsCollapsed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

865
Apex Reference Guide ChatterFeeds Class

threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, pageParam, pageSize, threadedCommentsCollapsed, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElements(communityId, q, recentCommentCount, pageParam, pageSize,


sortParam)
Get a page of sorted feed elements that match the search criteria. Each feed element includes no more than the specified number of
comments.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElements(String communityId, String
q, Integer recentCommentCount, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

866
Apex Reference Guide ChatterFeeds Class

q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElements(communityId, q, recentCommentCount, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, q)
Get the feed elements from the Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview feeds that match the search criteria.

867
Apex Reference Guide ChatterFeeds Class

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, q, result)
Apex Developer Guide: Testing ConnectApi Code

868
Apex Reference Guide ChatterFeeds Class

searchFeedElementsInFeed(communityId, feedType, pageParam, pageSize,


sortParam, q)
Get a page of sorted feed elements from the Company, DirectMessageModeration, Home, Isolated, Moderation,
and PendingReview feeds that match the search criteria.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.

869
Apex Reference Guide ChatterFeeds Class

• LastModifiedDateDesc—Sorts by most recent activity.


• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from the Company, DirectMessageModeration, Home, Isolated, Moderation,
and PendingReview feeds that match the search criteria. Each feed element includes no more than the specified number of
comments.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q)

870
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

871
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q,
result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam, q, filter)
Get a page of sorted and filtered feed elements from the Home feed that match the search criteria. Each feed element includes no more
than the specified number of comments.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q,
ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.

872
Apex Reference Guide ChatterFeeds Class

recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
When the sortParam is MostViewed, you must pass in null for the pageParam.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
When the sortParam is MostViewed, the pageSize must be a value from 1 to 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.

873
Apex Reference Guide ChatterFeeds Class

• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q,
filter, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, q)


Search up to 5,000 of the most recent feed elements in a feed for a subject ID that match the search string. Feed elements are returned
in order of most recent activity.

API Version
31.0

Available to Guest Users


31.0

874
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, Streams, and Topics.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is UserProfile,
subjectId can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the
alias me.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, pageParam,


pageSize, sortParam, q)
Get a page of sorted feed elements from a feed for a record or user that match the search criteria.

875
Apex Reference Guide ChatterFeeds Class

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, Streams, and Topics.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is UserProfile,
subjectId can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the
alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Order of feed items in the feed.
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.

876
Apex Reference Guide ChatterFeeds Class

• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Search term. Searches keywords in the user or group name. A minimum of one character is required. This parameter doesn’t support
wildcards. This parameter is required.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from a feed that match the search criteria. Each feed element includes no more than the specified
number of comments.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

877
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, Streams, and Topics.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is UserProfile,
subjectId can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the
alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

878
Apex Reference Guide ChatterFeeds Class

q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q, filter)
Get a page of sorted and filtered feed elements from a UserProfile feed that match the search criteria.

API Version
35.0

Available to Guest Users


35.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

879
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
One or more keywords to search for in the feed elements visible to the context user. The search string can contain wildcards and
must contain at least two characters that aren’t wildcards. See Wildcards.
filter
Type: ConnectApi.FeedFilter

880
Apex Reference Guide ChatterFeeds Class

Value must be ConnectApi.FeedFilter.CommunityScoped. Filters the feed to include only feed elements that are
scoped to Experience Cloud sites. Feed elements that are always visible in all sites are filtered out.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, filter, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q, customFilter)
Get a page of sorted and filtered feed elements from a case feed that match the search criteria.

API Version
40.0

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, String customFilter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType

881
Apex Reference Guide ChatterFeeds Class

Value must be ConnectApi.FeedType.Record.


subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
One or more keywords to search for in the feed elements visible to the context user. The search string can contain wildcards and
must contain at least two characters that aren’t wildcards. See Wildcards.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.

882
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, customFilter, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q, showInternalOnly)
Get a page of sorted feed elements from a feed for a record or user that match the search criteria. Each feed element includes no more
than the specified number of comments. Specify whether to return feed elements posted by internal (non-Experience Cloud site) users
only.

API Version
31.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.

883
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

884
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q, showInternalOnly, filter)
Get a page of sorted and filtered feed elements from a feed for a record or user that match the search criteria. Each feed element includes
no more than the specified number of comments. Specify whether to return feed elements posted by internal (non-Experience Cloud
site) users only.

API Version
32.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly,
ConnectApi.FeedFilter filter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.

885
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter

886
Apex Reference Guide ChatterFeeds Class

Specifies the feed filters.


• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, showInternalOnly, filter, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q, showInternalOnly, customFilter)
Get a page of sorted and filtered feed elements from a case feed that match the search criteria.

API Version
40.0

887
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


40.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly, String
customFilter)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

888
Apex Reference Guide ChatterFeeds Class

sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, showInternalOnly, customFilter, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q)


Get the feed elements from a feed filtered by a key prefix that match the search criteria.

API Version
31.0

889
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFilterFeed(String
communityId, String subjectId, String keyPrefix, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, pageParam,


pageSize, sortParam, q)
Get a page of sorted feed elements from a feed filtered by a key prefix that match the search criteria.

API Version
31.0

890
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFilterFeed(String
communityId, String subjectId, String keyPrefix, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

891
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElementPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed elements from a feed filtered by a key prefix that match the search criteria. Each feed element includes no
more than the specified number of comments.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElementPage searchFeedElementsInFilterFeed(String
communityId, String subjectId, String keyPrefix, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer

892
Apex Reference Guide ChatterFeeds Class

Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedElementPage

893
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize,
sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchStreams(communityId, q)
Search the Chatter feed streams for the context user.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage searchStreams(String communityId, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterStreamPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchStreams(communityId, q, result)
Apex Developer Guide: Testing ConnectApi Code

894
Apex Reference Guide ChatterFeeds Class

searchStreams(communityId, q, sortParam)
Search and sort the Chatter feed streams for the context user.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage searchStreams(String communityId, String q,
ConnectApi.SortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.

Return Value
Type: ConnectApi.ChatterStreamPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchStreams(communityId, q, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

895
Apex Reference Guide ChatterFeeds Class

searchStreams(communityId, q, pageParam, pageSize)


Search the Chatter feed streams for the context user and return a page of results.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage searchStreams(String communityId, String q,
Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.

Return Value
Type: ConnectApi.ChatterStreamPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchStreams(communityId, q, pageParam, pageSize, result)
Apex Developer Guide: Testing ConnectApi Code

896
Apex Reference Guide ChatterFeeds Class

searchStreams(communityId, q, pageParam, pageSize, sortParam)


Search the Chatter feed streams for the context user and return a sorted page of results.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage searchStreams(String communityId, String q,
Integer pageParam, Integer pageSize, ConnectApi.SortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.

Return Value
Type: ConnectApi.ChatterStreamPage

897
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchStreams(communityId, q, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchStreams(communityId, q, pageParam, pageSize, sortParam, globalScope)


Search the Chatter feed streams from all Experience Cloud sites for the context user and return a sorted page of results.

API Version
41.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStreamPage searchStreams(String communityId, String q,
Integer pageParam, Integer pageSize, ConnectApi.SortOrder sortParam, Boolean globalScope)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).

898
Apex Reference Guide ChatterFeeds Class

• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.
globalScope
Type: Boolean
Specifies whether to get streams from all the context user’s Experience Cloud sites, regardless of the communityId value.

Tip: If you know the communityId for the streams, we recommend setting globalScope to false.

Return Value
Type: ConnectApi.ChatterStreamPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

setCommentIsVerified(communityId, commentId, isVerified)


Mark a comment as verified or unverified.

API Version
41.0

Requires Chatter
Yes

Signature
public static ConnectApi.VerifiedCapability setCommentIsVerified(String communityId,
String commentId, Boolean isVerified)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment on a question post. Only one comment on a question post can be marked as verified.
isVerified
Type: Boolean
Specifies whether to mark the comment as verified (true) or unverified (false).
Only verified comments can be marked as unverified, and only unverified comments can be marked as verified.

899
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.VerifiedCapability
If the comment doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setCommentIsVerifiedByAnonymized(communityId, commentId, isVerified,


isVerifiedByAnonymized)
Mark a comment as verified by an anonymous user.

API Version
43.0

Requires Chatter
Yes

Signature
public static ConnectApi.VerifiedCapability setCommentIsVerifiedByAnonymized(String
communityId, String commentId, Boolean isVerified, Boolean isVerifiedByAnonymized)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment on a question post. Only one comment on a question post can be marked as verified.
isVerified
Type: Boolean
Specifies whether to mark the comment as verified (true) or unverified (false).
Only verified comments can be marked as unverified, and only unverified comments can be marked as verified.
isVerifiedByAnonymized
Type: Boolean
Specifies whether to mark the comment as verified by an anonymous user (true).
If a user previously verified a comment and then requested the activity to be deleted, use isVerifiedByAnonymized to
maintain the verification and anonymize the value of lastVerifiedByUser.
You can’t set isVerified and isVerifiedByAnonymized to true at the same time. isVerifiedByAnonymized
can be set to true only if isVerified is already set to true.
You can’t set isVerifiedByAnonymized to false. After isVerifiedByAnonymized is set to true, it can be
undone only when another user marks the comment as unverified and then reverifies the comment.

900
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.VerifiedCapability
If the comment doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setCommentVote(communityId, commentId, upDownVote)


Upvote or downvote a comment.

API Version
41.0

Requires Chatter
Yes

Signature
public static ConnectApi.UpDownVoteCapability setCommentVote(String communityId, String
commentId, ConnectApi.UpDownVoteCapabilityInput upDownVote)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
upDownVote
Type: ConnectApi.UpDownVoteCapabilityInput
A ConnectApi.UpDownVoteCapabilityInput object that includes your vote.

Return Value
Type: ConnectApi.UpDownVoteCapability
If the comment doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setFeedCommentStatus(communityId, commentId, status)


Set the status of a comment.

API Version
38.0

901
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.StatusCapability setFeedCommentStatus(String communityId,
String commentId, ConnectApi.StatusCapabilityInput status)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
status
Type: ConnectApi.StatusCapabilityInput
A ConnectApi.StatusCapabilityInput object that includes the status you want to set.

Return Value
Type: ConnectApi.StatusCapability
If the comment doesn’t support this capability, the return value is ConnectApi.NotFoundException.

Usage
Only users with the Can Approve Feed Post and Comment permission can set the status of a feed post or comment.

setFeedElementIsClosed(communityId, feedElementId, isClosed)


Set a feed element to closed.
Users can’t edit (specifically the feed item body or title), comment on, or delete a closed feed element. If the closed feed element is a
poll, users can’t vote on it. Users can’t edit (specifically the comment body) or delete a comment on a closed feed element or select or
remove it as best answer.
Admins and moderators can edit and delete closed feed elements and comments on closed feed elements. Admins and moderators
can select or remove the best answer status on comments on closed feed elements.

API Version
43.0

Requires Chatter
Yes

902
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.CloseCapability setFeedElementIsClosed(String communityId,
String feedElementId, Boolean isClosed)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
isClosed
Type: Boolean
Specifies whether to set the feed element to closed (true) or not (false).

Return Value
Type: ConnectApi.CloseCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setFeedElementVote(communityId, feedElementId, upDownVote)


Upvote or downvote a feed element.

API Version
41.0

Requires Chatter
Yes

Signature
public static ConnectApi.UpDownVoteCapability setFeedElementVote(String communityId,
String feedElementId, ConnectApi.UpDownVoteCapabilityInput upDownVote)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

903
Apex Reference Guide ChatterFeeds Class

upDownVote
Type: ConnectApi.UpDownVoteCapabilityInput
A ConnectApi.UpDownVoteCapabilityInput object that includes your vote.

Return Value
Type: ConnectApi.UpDownVoteCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setFeedEntityStatus(communityId, feedElementId, status)


Set the status of a feed post.

API Version
37.0

Requires Chatter
Yes

Signature
public static ConnectApi.StatusCapability setFeedEntityStatus(String communityId, String
feedElementId, ConnectApi.StatusCapabilityInput status)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
status
Type: ConnectApi.StatusCapabilityInput
A ConnectApi.StatusCapabilityInput object that includes the status you want to set.

Return Value
Type: ConnectApi.StatusCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

Usage
Only users with the Can Approve Feed Post and Comment permission can set the status of a feed post or comment.

904
Apex Reference Guide ChatterFeeds Class

setIsMutedByMe(communityId, feedElementId, isMutedByMe)


Mute or unmute a feed element.

API Version
35.0

Requires Chatter
Yes

Signature
public static ConnectApi.MuteCapability setIsMutedByMe(String communityId, String
feedElementId, Boolean isMutedByMe)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
isMutedByMe
Type: Boolean
Indicates whether the feed element is muted for the context user. Default value is false.

Return Value
Type: ConnectApi.MuteCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setIsReadByMe(communityId, feedElementId, readBy)


Mark a feed element as read for the context user using an input class.

API Version
40.0

Requires Chatter
Yes

905
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.ReadByCapability setIsReadByMe(String communityId, String
feedElementId, ConnectApi.ReadByCapabilityInput readBy)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element to mark as read.
readBy
Type: ConnectApi.ReadByCapabilityInput
A ConnectApi.ReadByCapabilityInput body indicating to mark the feed elements as read.

Return Value
Type: ConnectApi.ReadByCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

setIsReadByMe(communityId, feedElementId, isReadByMe)


Mark a feed element as read for the context user.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.ReadByCapability setIsReadByMe(String communityId, String
feedElementId, Boolean isReadByMe)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element to mark as read.

906
Apex Reference Guide ChatterFeeds Class

isReadByMe
Type: Boolean
Specifies to mark the feed element as read (true) for the context user.

Return Value
Type: ConnectApi.ReadByCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

updateComment(communityId, commentId, comment)


Edit a comment.

API Version
34.0

Requires Chatter
Yes

Signature
public static ConnectApi.Comment updateComment(String communityId, String commentId,
ConnectApi.CommentInput comment)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment to be edited.
comment
Type: ConnectApi.CommentInput
Information about the comment to be edited.

Return Value
Type: ConnectApi.Comment
If the comment doesn’t support the edit capability, the return value is ConnectApi.NotFoundException.

Example
String commentId;
String communityId = Network.getNetworkId();

907
Apex Reference Guide ChatterFeeds Class

// Get the last feed item created by the context user.


List<FeedItem> feedItems = [SELECT Id FROM FeedItem WHERE CreatedById = :UserInfo.getUserId()
ORDER BY CreatedDate DESC];
if (feedItems.isEmpty()) {
// Return null within anonymous apex.
return null;
}
String feedElementId = feedItems[0].id;

ConnectApi.CommentPage commentPage =
ConnectApi.ChatterFeeds.getCommentsForFeedElement(communityId, feedElementId);
if (commentPage.items.isEmpty()) {
// Return null within anonymous apex.
return null;
}
commentId = commentPage.items[0].id;

ConnectApi.FeedEntityIsEditable isEditable =
ConnectApi.ChatterFeeds.isCommentEditableByMe(communityId, commentId);

if (isEditable.isEditableByMe == true){
ConnectApi.CommentInput commentInput = new ConnectApi.CommentInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

textSegmentInput.text = 'This is my edited comment.';


messageBodyInput.messageSegments.add(textSegmentInput);

commentInput.body = messageBodyInput;

ConnectApi.Comment editedComment = ConnectApi.ChatterFeeds.updateComment(communityId,


commentId, commentInput);
}

updateDirectMessage(communityId, feedElementId, directMessage)


Update the members of a direct message.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.DirectMessageCapability updateDirectMessage(String communityId,
String feedElementId, ConnectApi.DirectMessageCapabilityInput directMessage)

908
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
directMessage
Type: ConnectApi.DirectMessageCapabilityInput
A ConnectApi.DirectMessageCapabilityInput body that includes the members to add and remove.

Return Value
Type: ConnectApi.DirectMessageCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

updateFeedElement(communityId, feedElementId, feedElement)


Edit a feed element.

API Version
34.0

Requires Chatter
Yes

Signature
public static ConnectApi.FeedElement updateFeedElement(String communityId, String
feedElementId, ConnectApi.FeedElementInput feedElement)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element to be edited. Feed items are the only type of feed element that can be edited.
feedElement
Type: ConnectApi.FeedElementInput
Information about the feed item to be edited.

909
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedElement
If the feed element doesn’t support the edit capability, the return value is ConnectApi.NotFoundException.

Example for Editing a Feed Post


String communityId = Network.getNetworkId();

// Get the last feed item created by the context user.


List<FeedItem> feedItems = [SELECT Id FROM FeedItem WHERE CreatedById = :UserInfo.getUserId()
ORDER BY CreatedDate DESC];
if (feedItems.isEmpty()) {
// Return null within anonymous apex.
return null;
}
String feedElementId = feedItems[0].id;

ConnectApi.FeedEntityIsEditable isEditable =
ConnectApi.ChatterFeeds.isFeedElementEditableByMe(communityId, feedElementId);

if (isEditable.isEditableByMe == true){
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

textSegmentInput.text = 'This is my edited post.';


messageBodyInput.messageSegments.add(textSegmentInput);

feedItemInput.body = messageBodyInput;

ConnectApi.FeedElement editedFeedElement =
ConnectApi.ChatterFeeds.updateFeedElement(communityId, feedElementId, feedItemInput);
}

Example for Editing a Question Title and Post


String communityId = Network.getNetworkId();

// Get the last feed item created by the context user.


List<FeedItem> feedItems = [SELECT Id FROM FeedItem WHERE CreatedById = :UserInfo.getUserId()
ORDER BY CreatedDate DESC];
if (feedItems.isEmpty()) {
// Return null within anonymous apex.
return null;
}
String feedElementId = feedItems[0].id;

ConnectApi.FeedEntityIsEditable isEditable =
ConnectApi.ChatterFeeds.isFeedElementEditableByMe(communityId, feedElementId);

910
Apex Reference Guide ChatterFeeds Class

if (isEditable.isEditableByMe == true){

ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();


ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new
ConnectApi.FeedElementCapabilitiesInput();
ConnectApi.QuestionAndAnswersCapabilityInput questionAndAnswersCapabilityInput = new
ConnectApi.QuestionAndAnswersCapabilityInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

textSegmentInput.text = 'This is my edited question.';


messageBodyInput.messageSegments.add(textSegmentInput);

feedItemInput.body = messageBodyInput;
feedItemInput.capabilities = feedElementCapabilitiesInput;

feedElementCapabilitiesInput.questionAndAnswers = questionAndAnswersCapabilityInput;
questionAndAnswersCapabilityInput.questionTitle = 'Where is my edited question?';

ConnectApi.FeedElement editedFeedElement =
ConnectApi.ChatterFeeds.updateFeedElement(communityId, feedElementId, feedItemInput);
}

updateFeedElementBookmarks(communityId, feedElementId, bookmarks)


Bookmark a feed element or remove a bookmark from a feed element using an input class.

API Version
32.0

Requires Chatter
Yes

Signature
public static ConnectApi.BookmarksCapability updateFeedElementBookmarks(String
communityId, String feedElementId, ConnectApi.BookmarksCapabilityInput bookmarks)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.

911
Apex Reference Guide ChatterFeeds Class

bookmarks
Type: ConnectApi.BookmarksCapabilityInput
Information about a bookmark.

Return Value
Type: ConnectApi.BookmarksCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

updateFeedElementBookmarks(communityId, feedElementId,
isBookmarkedByCurrentUser)
Bookmark a feed element or remove a bookmark from a feed element.

API Version
32.0

Requires Chatter
Yes

Signature
public static ConnectApi.BookmarksCapability updateFeedElementBookmarks(String
communityId, String feedElementId, Boolean isBookmarkedByCurrentUser)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
isBookmarkedByCurrentUser
Type: Boolean
Specify whether to bookmark the feed element (true) or not (false).

Return Value
Type: ConnectApi.BookmarksCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

912
Apex Reference Guide ChatterFeeds Class

Example
ConnectApi.BookmarksCapability bookmark =
ConnectApi.ChatterFeeds.updateFeedElementBookmarks(null, '0D5D0000000KuGh', true);

updateFeedElementReadByCapabilityBatch(communityId, feedElementIds, readBy)


Mark multiple feed elements as read by the context user at the same time using an input class.

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] updateFeedElementReadByCapabilityBatch(String
communityId, List<String> feedElementIds, ConnectApi.ReadByCapabilityInput readBy)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementIds
Type: List<String>
Up to 500 feed element IDs to mark as read.
readBy
Type: ConnectApi.ReadByCapabilityInput
A ConnectApi.ReadByCapabilityInput body indicating to mark the feed elements as read.

Return Value
Type: ConnectApi.BatchResult[]
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.
The returned objects correspond to each of the input objects and are returned in the same order as the input objects.
The method call fails only if an error occurs that affects the entire operation (such as a parsing failure). If an individual object causes an
error, the error is embedded within the ConnectApi.BatchResult list.

updateFeedElementReadByCapabilityBatch(communityId, feedElementIds,
isReadByMe)
Mark multiple feed elements as read by the context user at the same time.

913
Apex Reference Guide ChatterFeeds Class

API Version
40.0

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] updateFeedElementReadByCapabilityBatch(String
communityId, List<String> feedElementIds, Boolean isReadByMe)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementIds
Type: List<String>
Up to 500 feed element IDs to mark as read.
isReadByMe
Type: Boolean
Specifies to mark the feed element as read (true) for the context user.

Return Value
Type: ConnectApi.BatchResult[]
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

updateLikeForComment(communityId, commentId, isLikedByCurrentUser)


Like or unlike a comment.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage updateLikeForComment(String communityId, String
commentId, Boolean isLikedByCurrentUser)

914
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
commentId
Type: String
ID of the comment.
isLikedByCurrentUser
Type: Boolean
Specifies if the context user likes (true) or unlikes (false) the comment.

Return Value
Type: ConnectApi.ChatterLikePage

updateLikeForFeedElement(communityId, feedElementId, isLikedByCurrentUser)


Like or unlike a feed element.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage updateLikeForFeedElement(String communityId,
String feedElementId, Boolean isLikedByCurrentUser)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
isLikedByCurrentUser
Type: Boolean
Specifies if the context user likes (true) or unlikes (false) the feed element.

915
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.ChatterLikePage
If the feed element doesn’t support the ChatterLikes capability, the return value is ConnectApi.NotFoundException.

updatePinnedFeedElements(communityId, feedType, subjectId, pin)


Pin or unpin feed elements to a group or topic feed.

API Version
41.0

Available to Guest Users


41.0

Requires Chatter
Yes

Signature
public static ConnectApi.PinCapability updatePinnedFeedElements(String communityId,
ConnectApi.FeedType feedType, String subjectId, ConnectApi.PinCapabilityInput pin)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. Valid values are Record and Topics.
subjectId
Type: String
If feedType is Record, subjectId must be a group ID. If feedType is Topics, subjectId must be a topic ID.
pin
Type: ConnectApi.PinCapabilityInput
A ConnectApi.PinCapabilityInput object indicating the feed element to pin or unpin.

Return Value
Type: ConnectApi.PinCapability
If the feed doesn’t support this capability, the return value is ConnectApi.NotFoundException.

916
Apex Reference Guide ChatterFeeds Class

updateStream(communityId, streamId, streamInput)


Update a Chatter feed stream.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterStream updateStream(String communityId, String streamId,
ConnectApi.ChatterStreamInput streamInput)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
streamId
Type: String
ID of the Chatter feed stream.
streamInput
Type: ConnectApi.ChatterStreamInput
A ConnectApi.ChatterStreamInput object.

Return Value
Type: ConnectApi.ChatterStream

voteOnFeedElementPoll(communityId, feedElementId, myChoiceId)


Vote on a poll or change your vote on a poll.

API Version
32.0

Requires Chatter
Yes

Signature
public static ConnectApi.PollCapability voteOnFeedElementPoll(String communityId, String
feedElementId, String myChoiceId)

917
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element.
myChoiceId
Type: String
ID of the poll item you’re voting for. The key prefix for poll items is 09A.

Return Value
Type: ConnectApi.PollCapability
If the feed element doesn’t support this capability, the return value is ConnectApi.NotFoundException.

Example
ConnectApi.PollCapability poll = ConnectApi.ChatterFeeds.voteOnFeedElementPoll(null,
'0D5D0000000XZaUKAW', '09AD000000000TKMAY');

ChatterFeeds Test Methods


These test methods are for ChatterFeeds. All methods are static.
For information about using these methods to test your ConnectApi code, see Testing ConnectApi Code.

IN THIS SECTION:
setTestGetFeedElementsFromFeed(communityId, feedType, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter,
result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

918
Apex Reference Guide ChatterFeeds Class

setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter,


threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getFeedElementsFromFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, filter, threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getFeedElementsFromFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter, threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

919
Apex Reference Guide ChatterFeeds Class

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,


pageSize, sortParam, showInternalOnly, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter, threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getFeedElementsFromFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, result)
a ConnectApi.FeedElementPage object to be returned when the matching getFeedElementsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching getFeedElements
FromFilterFeed method is called in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching getFeedElements
FromFilterFeed method is called in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle,
density, pageParam, pageSize, updatedSince, result)
Register a ConnectApi.FeedElementPage object to be returned when the
getFeedElementsFromFilterFeedUpdatedSince method is called in a test context.
setTestGetFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince,
result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince,
filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

920
Apex Reference Guide ChatterFeeds Class

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,


pageParam, pageSize, updatedSince, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, showInternalOnly, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density,
pageParam, pageSize, updatedSince, showInternalOnly, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetRelatedPosts(communityId, feedElementId, filter, maxResults, result)
Register a ConnectApi.RelatedFeedPosts object to be returned when the matching
ConnectApi.getRelatedPosts(communityId, feedElementId, filter, maxResults) method is
called in a test context. Use the method with the same parameters or you receive an exception.
setTestGetTopUnansweredQuestions(communityId, result) (Pilot)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestGetTopUnansweredQuestions(communityId, filter, result) (Pilot)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestGetTopUnansweredQuestions(communityId, pageSize, result) (Pilot)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestGetTopUnansweredQuestions(communityId, filter, pageSize, result) (Pilot)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElements(communityId, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.
setTestSearchFeedElements(communityId, q, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

921
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElements(communityId, q, threadedCommentsCollapsed, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.
setTestSearchFeedElements(communityId, q, pageParam, pageSize, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.
setTestSearchFeedElements(communityId, q, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.
setTestSearchFeedElements(communityId, q, pageParam, pageSize, threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.
setTestSearchFeedElements(communityId, q, recentCommentCount, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q,
result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q,
filter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

922
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when searchFeedElementsInFeed is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, showInternalOnly, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
sortParam, q, showInternalOnly, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.
setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.

923
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize,


sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.
setTestSearchStreams(communityId, q, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStream(communityId, q) method is called in a test context. Use the method with the same
parameters or you receive an exception.
setTestSearchStreams(communityId, q, sortParam, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStream(communityId, q, sortParam) method is called in a test context. Use the method
with the same parameters or you receive an exception.
setTestSearchStreams(communityId, q, pageParam, pageSize, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStreams(communityId, q, pageParam, pageSize) method is called in a test context.
Use the method with the same parameters or you receive an exception.
setTestSearchStreams(communityId, q, pageParam, pageSize, sortParam, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStreams(communityId, q, pageParam, pageSize, sortParam) method is called
in a test context. Use the method with the same parameters or you receive an exception.
setTestSearchStreams(communityId, q, pageParam, pageSize, sortParam, globalScope, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStreams(communityId, q, pageParam, pageSize, sortParam, globalScope)
method is called in a test context. Use the method with the same parameters or you receive an exception.

setTestGetFeedElementsFromFeed(communityId, feedType, result)


Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

924
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, pageParam, pageSize,


sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The only valid value for this parameter is Company.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.

925
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, Integer recentCommentCount, ConnectApi.FeedDensity density, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedElementPage result)

926
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

927
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
32.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, Integer recentCommentCount, ConnectApi.FeedDensity density, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedFilter filter,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String

928
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

929
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, filter, threadedCommentsCollapsed,
result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getFeedElementsFromFeed method is called in a test context. Use the method with the same parameters or
you receive an exception.

API Version
44.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, Integer recentCommentCount, ConnectApi.FeedDensity density, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedFilter filter,
Boolean threadedCommentsCollapsed, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.

930
Apex Reference Guide ChatterFeeds Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.

931
Apex Reference Guide ChatterFeeds Class

threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
Apex Developer Guide: Testing ConnectApi Code
getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, filter,
threadedCommentsCollapsed)

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, result)


Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The feed type.
subjectId
Type: String
ID of the context user or the alias me.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

932
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId, pageParam,


pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

933
Apex Reference Guide ChatterFeeds Class

sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

934
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

935
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, showInternalOnly,
result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, Boolean
showInternalOnly, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.

936
Apex Reference Guide ChatterFeeds Class

• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

937
Apex Reference Guide ChatterFeeds Class

API Version
35.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedFilter filter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.

938
Apex Reference Guide ChatterFeeds Class

• CreatedDateDesc—Sorts by most recent creation date.


• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter
Value must be ConnectApi.FeedFilter.CommunityScoped. Filters the feed to include only feed elements that are
scoped to Experience Cloud sites. Feed elements that are always visible in all sites are filtered out. Currently, feed elements scoped
to sites have a User or a Group parent record. However, other parent record types could be scoped to sites in the future.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
filter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, filter,
threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getFeedElementsFromFeed method is called in a test context. Use the method with the same parameters or
you receive an exception.

API Version
44.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedFilter filter, Boolean threadedCommentsCollapsed,
ConnectApi.FeedElementPage result)

939
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
filter
Type: ConnectApi.FeedFilter

940
Apex Reference Guide ChatterFeeds Class

Value must be ConnectApi.FeedFilter.CommunityScoped. Filters the feed to include only feed elements that are
scoped to Experience Cloud sites. Feed elements that are always visible in all sites are filtered out. Currently, feed elements scoped
to sites have a User or a Group parent record. However, other parent record types could be scoped to sites in the future.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
Apex Developer Guide: Testing ConnectApi Code
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
filter, threadedCommentsCollapsed)

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, customFilter,
result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
40.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String
customFilter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.

941
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

942
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
customFilter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, ConnectApi.FeedElementPage
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.

943
Apex Reference Guide ChatterFeeds Class

density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

944
Apex Reference Guide ChatterFeeds Class

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam, showInternalOnly, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
32.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, ConnectApi.FeedFilter
filter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String

945
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.

946
Apex Reference Guide ChatterFeeds Class

• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam, showInternalOnly, filter, threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
44.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, ConnectApi.FeedFilter
filter, Boolean threadedCommentsCollapsed, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer

947
Apex Reference Guide ChatterFeeds Class

Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.

948
Apex Reference Guide ChatterFeeds Class

• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, filter, threadedCommentsCollapsed)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam, showInternalOnly, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsFromFeed is called with
matching parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
40.0

949
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, String customFilter,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:

950
Apex Reference Guide ChatterFeeds Class

• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFeed(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam, showInternalOnly, customFilter, threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getFeedElementsFromFeed method is called in a test context. Use the method with the same parameters or
you receive an exception.

API Version
44.0

Signature
public static Void setTestGetFeedElementsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,

951
Apex Reference Guide ChatterFeeds Class

ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly, String customFilter,


Boolean threadedCommentsCollapsed, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.

952
Apex Reference Guide ChatterFeeds Class

• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
Apex Developer Guide: Testing ConnectApi Code
getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam, showInternalOnly, customFilter, threadedCommentsCollapsed)

setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix,


result)
a ConnectApi.FeedElementPage object to be returned when the matching getFeedElementsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFilterFeed(String communityId, String
subjectId, String keyPrefix, ConnectApi.FeedElementPage result)

953
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix,


pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching getFeedElements
FromFilterFeed method is called in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFilterFeed(String communityId, String
subjectId, String keyPrefix, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

954
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

955
Apex Reference Guide ChatterFeeds Class

setTestGetFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching getFeedElements
FromFilterFeed method is called in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFilterFeed(String communityId, String
subjectId, String keyPrefix, Integer recentCommentCount, Integer elementsPerBundle,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String

956
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId,
keyPrefix, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, result)
Register a ConnectApi.FeedElementPage object to be returned when the
getFeedElementsFromFilterFeedUpdatedSince method is called in a test context.

API Version
31.0

Signature
public static Void setTestGetFeedElementsFromFilterFeedUpdatedSince(String communityId,
String subjectId, String keyPrefix, Integer recentCommentCount, Integer

957
Apex Reference Guide ChatterFeeds Class

elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,


String updatedSince, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
Opaque token defining the modification timestamp of the feed and the sort order.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

958
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, elementsPerBundle,
density, pageParam, pageSize, updatedSince)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, updatedSince, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, String updatedSince, ConnectApi.FeedElementPage
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.

959
Apex Reference Guide ChatterFeeds Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, updatedSince, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
32.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, String updatedSince, ConnectApi.FeedFilter filter,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String

960
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.

961
Apex Reference Guide ChatterFeeds Class

• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince, filter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, updatedSince, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of these values:
• Files

962
Apex Reference Guide ChatterFeeds Class

• Groups
• News
• People
• Record
subjectId
Type: String
If feedType is ConnectApi.Record, subjectId can be any record ID, including a group ID. Otherwise, it must be the
context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince)
Apex Developer Guide: Testing ConnectApi Code

963
Apex Reference Guide ChatterFeeds Class

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince,
Boolean showInternalOnly, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer

964
Apex Reference Guide ChatterFeeds Class

Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
35.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, ConnectApi.FeedFilter filter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

965
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
Opaque token defining the modification timestamp of the feed and the sort order.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
filter
Type: ConnectApi.FeedFilter
Value must be ConnectApi.FeedFilter.CommunityScoped. Filters the feed to include only feed elements that are
scoped to Experience Cloud sites. Feed elements that are always visible in all sites are filtered out. Currently, feed elements scoped
to sites have a User or a Group parent record. However, other parent record types could be scoped to sites in the future.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

966
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, filter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
40.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, String customFilter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity

967
Apex Reference Guide ChatterFeeds Class

Specify the amount of content in a feed.


• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
Opaque token defining the modification timestamp of the feed and the sort order.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, customFilter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
31.0

968
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, Boolean showInternalOnly, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.

969
Apex Reference Guide ChatterFeeds Class

showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, showInternalOnly, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
32.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, Boolean showInternalOnly, ConnectApi.FeedFilter filter,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String

970
Apex Reference Guide ChatterFeeds Class

Any record ID, including a group ID.


recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.

971
Apex Reference Guide ChatterFeeds Class

• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate


answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, showInternalOnly, filter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedElementsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize,
updatedSince, showInternalOnly, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when getFeedElementsUpdatedSince is called
with matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
40.0

Signature
public static Void setTestGetFeedElementsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount, Integer
elementsPerBundle, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
String updatedSince, Boolean showInternalOnly, String customFilter,
ConnectApi.FeedElementPage result)

972
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
elementsPerBundle
Type: Integer
Maximum number of feed elements to include in a bundle. The value must be an integer between 0 and 10. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedElementPage response body.
The updatedSince parameter doesn’t return feed elements that are created in the same second as the call.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
customFilter
Type: String

973
Apex Reference Guide ChatterFeeds Class

Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, elementsPerBundle, density, pageParam,
pageSize, updatedSince, showInternalOnly, customFilter)
Apex Developer Guide: Testing ConnectApi Code

setTestGetRelatedPosts(communityId, feedElementId, filter, maxResults, result)


Register a ConnectApi.RelatedFeedPosts object to be returned when the matching
ConnectApi.getRelatedPosts(communityId, feedElementId, filter, maxResults) method is called
in a test context. Use the method with the same parameters or you receive an exception.

API Version
37.0

Signature
public static Void setTestGetRelatedPosts(String communityId, String feedElementId,
ConnectApi.RelatedFeedPostType filter, Integer maxResults, ConnectApi.RelatedFeedPosts
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElementId
Type: String
ID of the feed element. The feed element must be a question.
filter
Type: ConnectApi.RelatedFeedPostType
Specifies the type of related feed post. Values are:
• Answered—Related questions that have at least one answer.
• BestAnswer—Related questions that have a best answer.
• Generic—All types of related questions, including answered, with a best answer, and unanswered.
• Unanswered—Related questions that don’t have answers.

974
Apex Reference Guide ChatterFeeds Class

Generic is the default value.


maxResults
Type: Integer
The maximum number of results to return. You can return up to 25 results; 5 is the default.
result
Type: ConnectApi.RelatedFeedPosts
Object containing test data.
In version 37.0 and later, related feed posts are questions.

Return Value
Type: Void

setTestGetTopUnansweredQuestions(communityId, result) (Pilot)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

Signature
public static Void setTestGetTopUnansweredQuestions(String communityId,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID of the Experience Cloud site.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getTopUnansweredQuestions(communityId) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

975
Apex Reference Guide ChatterFeeds Class

setTestGetTopUnansweredQuestions(communityId, filter, result) (Pilot)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

Signature
public static Void setTestGetTopUnansweredQuestions(String communityId,
ConnectApi.TopUnansweredQuestionsFilterType filter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID of the Experience Cloud site.
filter
Type: ConnectApi.FeedFilter
Specifies the filter for the feed. UnansweredQuestionsWithCandidateAnswers is the only valid value.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getTopUnansweredQuestions(communityId, filter) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

setTestGetTopUnansweredQuestions(communityId, pageSize, result) (Pilot)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

976
Apex Reference Guide ChatterFeeds Class

API Version
42.0

Signature
public static Void setTestGetTopUnansweredQuestions(String communityId, Integer pageSize,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID of the Experience Cloud site.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 0 through 10. If you pass in null, the default size is 5.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getTopUnansweredQuestions(communityId, pageSize) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

setTestGetTopUnansweredQuestions(communityId, filter, pageSize, result) (Pilot)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.getTopUnansweredQuestions method is called in a test context. Use the method with the same parameters
or you receive an exception.

Note: We provided top-five unanswered questions to selected customers through a pilot program that required agreement to
specific terms and conditions. This pilot program is closed and not accepting new participants.

API Version
42.0

Signature
public static Void setTestGetTopUnansweredQuestions(String communityId,
ConnectApi.FeedFilter filter, Integer pageSize, ConnectApi.FeedElementPage result)

977
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID of the Experience Cloud site.
filter
Type: ConnectApi.FeedFilter
Specifies the filter for the feed. UnansweredQuestionsWithCandidateAnswers is the only valid value.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 0 through 10. If you pass in null, the default size is 5.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getTopUnansweredQuestions(communityId, filter, pageSize) (Pilot)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String

978
Apex Reference Guide ChatterFeeds Class

Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, sortParam, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q,
ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.

979
Apex Reference Guide ChatterFeeds Class

• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, threadedCommentsCollapsed, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
44.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q, Boolean
threadedCommentsCollapsed, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
result
Type: ConnectApi.FeedElementPage

980
Apex Reference Guide ChatterFeeds Class

Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q, threadedCommentsCollapsed)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, pageParam, pageSize, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q, String
pageParam, Integer pageSize, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.D
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

981
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q, pageParam, pageSize)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, pageParam, pageSize, sortParam,


result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q, String
pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.

982
Apex Reference Guide ChatterFeeds Class

• CreatedDateDesc—Sorts by most recent creation date.


• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, pageParam, pageSize,


threadedCommentsCollapsed, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
44.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q, String
pageParam, Integer pageSize, Boolean threadedCommentsCollapsed,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String

983
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
threadedCommentsCollapsed
Type: Boolean
Specifies whether to return threaded comments in a collapsed style (true) or not (false). If you pass in null, the default is
false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q, pageParam, pageSize, threadedCommentsCollapsed)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElements(communityId, q, recentCommentCount, pageParam,


pageSize, sortParam, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElements method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElements(String communityId, String q, Integer
recentCommentCount, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String

984
Apex Reference Guide ChatterFeeds Class

Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElements(communityId, q, recentCommentCount, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, q, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

985
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String q, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, pageParam, pageSize,


sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedElementPage result)

986
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

987
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, Home, Isolated, Moderation, and
PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

988
Apex Reference Guide ChatterFeeds Class

sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, q, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
32.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q,
ConnectApi.FeedFilter filter, ConnectApi.FeedElementPage result)

989
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
The type of feed. The only valid value is Home.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
filter
Type: ConnectApi.FeedFilter

990
Apex Reference Guide ChatterFeeds Class

Specifies the feed filters.


• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q, filter)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, q, result)


Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

991
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String q, ConnectApi.FeedElementPage
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, Streams, and Topics.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feed type is UserProfile, subjectId
can be any user ID. If feedType is any other value, subjectId must be the ID of the context user or the alias me.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId, pageParam,


pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

992
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, Streams, and Topics.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is UserProfile,
subjectId can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the
alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Order of feed items in the feed.
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Search term. Searches keywords in the user or group name. A minimum of one character is required. This parameter doesn’t support
wildcards. This parameter is required.

993
Apex Reference Guide ChatterFeeds Class

result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, Streams, and Topics.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is UserProfile,
subjectId can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the
alias me.
recentCommentCount
Type: Integer

994
Apex Reference Guide ChatterFeeds Class

Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
q)
Apex Developer Guide: Testing ConnectApi Code

995
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q, filter,
result)
Register a ConnectApi.FeedElementPage object to be returned when searchFeedElementsInFeed is called with
matching parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
35.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedFilter filter,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.UserProfile.
subjectId
Type: String
ID of any user. To specify the context user, use the user ID or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
The amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.

996
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
One or more keywords to search for in the feed elements visible to the context user. The search string can contain wildcards and
must contain at least two characters that aren’t wildcards. See Wildcards.
filter
Type: ConnectApi.FeedFilter
Value must be ConnectApi.FeedFilter.CommunityScoped. Filters the feed to include only feed elements that are
scoped to Experience Cloud sites. Feed elements that are always visible in all sites are filtered out. Currently, feed elements scoped
to sites have a User or a Group parent record. However, other parent record types could be scoped to sites in the future.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
filter)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q, customFilter,
result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

997
Apex Reference Guide ChatterFeeds Class

API Version
40.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, String customFilter,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
The amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:

998
Apex Reference Guide ChatterFeeds Class

• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
One or more keywords to search for in the feed elements visible to the context user. The search string can contain wildcards and
must contain at least two characters that aren’t wildcards. See Wildcards.
customFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
customFilter)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,

999
Apex Reference Guide ChatterFeeds Class

ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly,


ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.

1000
Apex Reference Guide ChatterFeeds Class

q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, filter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
32.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly,
ConnectApi.FeedFilter filter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

1001
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean

1002
Apex Reference Guide ChatterFeeds Class

Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
filter
Type: ConnectApi.FeedFilter
Specifies the feed filters.
• AllQuestions—Feed elements that are questions.
• AuthoredBy—Feed elements authored by the user profile owner. This value is valid only for the UserProfile feed.
• CommunityScoped—Feed elements that are scoped to Experience Cloud sites. Currently, these feed elements have a User
or a Group parent record. However, other parent record types could be scoped to sites in the future. Feed elements that are
always visible in all sites are filtered out. This value is valid only for the UserProfile feed.
• QuestionsWithCandidateAnswers—Feed elements that are questions that have candidate answers associated with
them. This value is valid only for users with the Access Einstein-Generated Answers permission.
• QuestionsWithCandidateAnswersReviewedPublished—Feed elements that are questions that have candidate
answers that have been reviewed or published. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Read—Feed elements that are older than 30 days or are marked as read for the context user. Includes existing feed elements
when the context user joined the group. This value is valid only for the Record feed of a group.
• SolvedQuestions—Feed elements that are questions and that have a best answer.
• UnansweredQuestions—Feed elements that are questions and that don’t have any answers.
• UnansweredQuestionsWithCandidateAnswers—Feed elements that are questions that don’t have answers but
have candidate answers associated with them. This value is valid only for users with the Access Einstein-Generated Answers
permission.
• Unread—Feed elements that are created in the past 30 days and aren’t marked as read for the context user. This value is valid
only for the Record feed of a group.
• UnsolvedQuestions—Feed elements that are questions and that don’t have a best answer.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, filter)
Apex Developer Guide: Testing ConnectApi Code

1003
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, customFilter, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
40.0

Signature
public static Void setTestSearchFeedElementsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly, String
customFilter, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
The ID of a case.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.

1004
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean
Specifies whether to show only feed elements from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
cusotmFilter
Type: String
Custom filter that applies only to the case feed. See customFeedFilter in the Metadata API Developer Guide for supported values.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, customFilter)
Apex Developer Guide: Testing ConnectApi Code

1005
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q,


result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFilterFeed(String communityId, String
subjectId, String keyPrefix, String q, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q)
Apex Developer Guide: Testing ConnectApi Code

1006
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix,


pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFilterFeed(String communityId, String
subjectId, String keyPrefix, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, String q, ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.

1007
Apex Reference Guide ChatterFeeds Class

• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, density, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedElementPage object to be returned when the matching
ConnectApi.searchFeedElementsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.

API Version
31.0

Signature
public static Void setTestSearchFeedElementsInFilterFeed(String communityId, String
subjectId, String keyPrefix, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q,
ConnectApi.FeedElementPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String

1008
Apex Reference Guide ChatterFeeds Class

A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed element. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of feed elements per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
If you pass in null, the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedElementPage
Object containing test data.

1009
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam,
q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchStreams(communityId, q, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStream(communityId, q) method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
40.0

Signature
public static Void setTestSearchStreams(String communityId, String q,
ConnectApi.ChatterStreamPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.ChatterStreamPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchStreams(communityId, q)
Apex Developer Guide: Testing ConnectApi Code

1010
Apex Reference Guide ChatterFeeds Class

setTestSearchStreams(communityId, q, sortParam, result)


Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStream(communityId, q, sortParam) method is called in a test context. Use the method with
the same parameters or you receive an exception.

API Version
40.0

Signature
public static Void setTestSearchStreams(String communityId, String q,
ConnectApi.SortOrder sortParam, ConnectApi.ChatterStreamPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.
result
Type: ConnectApi.ChatterStreamPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchStreams(communityId, q, sortParam)
Apex Developer Guide: Testing ConnectApi Code

1011
Apex Reference Guide ChatterFeeds Class

setTestSearchStreams(communityId, q, pageParam, pageSize, result)


Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStreams(communityId, q, pageParam, pageSize) method is called in a test context. Use
the method with the same parameters or you receive an exception.

API Version
40.0

Signature
public static Void setTestSearchStreams(String communityId, String q, Integer pageParam,
Integer pageSize, ConnectApi.ChatterStreamPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
result
Type: ConnectApi.ChatterStreamPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchStreams(communityId, q, pageParam, pageSize)
Apex Developer Guide: Testing ConnectApi Code

1012
Apex Reference Guide ChatterFeeds Class

setTestSearchStreams(communityId, q, pageParam, pageSize, sortParam, result)


Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStreams(communityId, q, pageParam, pageSize, sortParam) method is called in
a test context. Use the method with the same parameters or you receive an exception.

API Version
40.0

Signature
public static Void setTestSearchStreams(String communityId, String q, Integer pageParam,
Integer pageSize, ConnectApi.SortOrder sortParam, ConnectApi.ChatterStreamPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).
• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.
result
Type: ConnectApi.ChatterStreamPage
Object containing test data.

1013
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
searchStreams(communityId, q, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchStreams(communityId, q, pageParam, pageSize, sortParam,


globalScope, result)
Register a ConnectApi.ChatterStreamPage object to be returned when the matching
ConnectApi.searchStreams(communityId, q, pageParam, pageSize, sortParam, globalScope)
method is called in a test context. Use the method with the same parameters or you receive an exception.

API Version
41.0

Signature
public static Void setTestSearchStreams(String communityId, String q, Integer pageParam,
Integer pageSize, ConnectApi.SortOrder sortParam, Boolean globalScope,
ConnectApi.ChatterStreamPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 to 250. The default size is 25.
sortParam
Type: ConnectApi.SortOrder
Specifies the sort order. Values are:
• Ascending—Items are in ascending alphabetical order (A-Z).
• Descending—Items are in descending alphabetical order (Z-A).

1014
Apex Reference Guide ChatterFeeds Class

• MostRecentlyViewed—Items are in descending chronological order by view. This sort order is valid only for Chatter feed
streams.
If not specified, default value is Ascending.
globalScope
Type: Boolean
Specifies whether to get streams from all the context user’s Experience Cloud sites, regardless of the communityId value.
result
Type: ConnectApi.ChatterStreamPage
Object containing test data.

Return Value
Type: Void

Retired ChatterFeeds Methods


These methods for ChatterFeeds are retired.

IN THIS SECTION:
deleteFeedItem(communityId, feedItemId)
Delete a feed item.
getCommentsForFeedItem(communityId, feedItemId)
Get comments for a feed item.
getCommentsForFeedItem(communityId, feedItemId, pageParam, pageSize)
Get a page of comments for a feed item.
getFeedItem(communityId, feedItemId)
Get a feed item.
getFeedItemBatch(communityId, feedItemIds)
Get a list of feed items.
getFeedItemsFromFeed(communityId, feedType)
Get feed items from the Company, Home, and Moderation feeds.
getFeedItemsFromFeed(communityId, feedType, pageParam, pageSize, sortParam)
Get a page of sorted feed items from the Company, Home, and Moderation feeds.
getFeedItemsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam)
Get a page of sorted feed items from the Company, Home, and Moderation feeds. Each feed item contains no more than the
specified number of comments.
getFeedItemsFromFeed(communityId, feedType, subjectId)
Get feed items from a feed for a user or record.
getFeedItemsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam)
Get a page of sorted feed items from a feed for a user or record.

1015
Apex Reference Guide ChatterFeeds Class

getFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam)


Get a page of sorted feed items from a feed for a user or record. Each feed item includes no more than the specified number of
comments.
getFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
showInternalOnly)
Get a page of sorted feed items from a record feed for a user or record. Each feed item includes no more than the specified number
of comments. Specify whether to return feed items posted by internal (non-Experience Cloud site) users only.
getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix)
Get feed items from a feed filtered by a key prefix for a user.
getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam)
Get a page of sorted feed items from a feed filtered by a key prefix for a user.
getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam)
Get a page of sorted feed items from a feed filtered by a key prefix for a user. Each feed item contains no more than the specified
number of comments.
getFeedItemsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize,
updatedSince)
Get a page of feed items from a feed filtered by a key prefix for a user. Include only feed items that have been updated since the
time specified in the updatedSince parameter.
getFeedItemsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince)
Get a page of feed items from the Company, Home, and Moderation feeds. Include only feed items that have been updated
since the time specified in the updatedSince parameter. Each feed item contains no more than the specified number of
comments.
getFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, updatedSince)
Get a page of feed items from the Files, Groups, News, People, and Record feeds. Include only feed items that have
been updated since the time specified in the updatedSince parameter. Each feed item contains no more than the specified
number of comments.
getFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly)
Get a page of feed items from a record feed. Include only feed items that have been updated since the time specified in the
updatedSince parameter. Specify whether to return feed items posted by internal (non-Experience Cloud site) users only.
getFeedPoll(communityId, feedItemId)
Get the poll associated with a feed item.
getLikesForFeedItem(communityId, feedItemId)
Get likes for a feed item.
getLikesForFeedItem(communityId, feedItemId, pageParam, pageSize)
Get a page of likes for a feed item.
likeFeedItem(communityId, feedItemId)
Like a feed item for the context user.
postComment(communityId, feedItemId, text)
Post a plain-text comment to a feed item.
postComment(communityId, feedItemId, comment, feedItemFileUpload)
Post a rich-text comment to a feed item. Use this method to include mentions and to attach a file to a comment.

1016
Apex Reference Guide ChatterFeeds Class

postFeedElement(communityId, feedElement, feedElementFileUpload)


Post a rich-text feed element. Include mentions and hashtag topics, attach a file to a feed element, and associate action link groups
with a feed element. You can also use this method to share a feed element and add a comment.
postFeedItem(communityId, feedType, subjectId, text)
Post a plain-text feed item.
postFeedItem(communityId, feedType, subjectId, feedItemInput, feedItemFileUpload)
Post a rich-text feed item to a feed. Use this method to include mentions and hashtag topics and to attach a file to a feed item. You
can also use this method to share a feed item and add a comment.
searchFeedItems(communityId, q)
Get the feed items that match the search criteria.
searchFeedItems(communityId, q, sortParam)
Get the sorted feed items that match the search criteria.
searchFeedItems(communityId, q, pageParam, pageSize)
Get a page of feed items that match the search criteria.
searchFeedItems(communityId, q, pageParam, pageSize, sortParam)
Get a page of sorted feed items that match the search criteria.
searchFeedItems(communityId, q, recentCommentCount, pageParam, pageSize, sortParam)
Get a page of sorted feed items that match the search criteria.
searchFeedItemsInFeed(communityId, feedType, q)
Get the feed items from the Company, Home, and Moderation feeds that match the search criteria.
searchFeedItemsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items from the Company, Home, and Moderation feeds that match the search criteria.
searchFeedItemsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items from the Company, Home, and Moderation feeds that match the search criteria. Each feed
item includes no more than the specified number of comments.
searchFeedItemsInFeed(communityId, feedType, subjectId, q)
Get the feed items from a feed that match the search criteria.
searchFeedItemsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items from a feed for a user or record that match the search criteria.
searchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items from a feed that match the search criteria. Each feed item includes no more than the specified
number of comments.
searchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly)
Get a page of sorted feed items from a feed for a user or record that match the search criteria. Each feed item includes no more than
the specified number of comments. Specify whether to return feed items posted by internal (non-Experience Cloud site) users only.
searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, q)
Get the feed items that match the search criteria from a feed filtered by a key prefix for a user.
searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items that match the search criteria from a feed filtered by a key prefix for a user.

1017
Apex Reference Guide ChatterFeeds Class

searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam,


q)
Get a page of sorted feed items that match the search criteria from a feed filtered by a key prefix for a user. Each feed item includes
no more than the specified number of comments.
shareFeedElement(communityId, subjectId, feedElementType, originalFeedElementId)
Share the originalFeedElementId as the context user.
shareFeedItem(communityId, feedType, subjectId, originalFeedItemId)
Share the originalFeedItemId to the feed specified by the feedType.
updateBookmark(communityId, feedItemId, isBookmarkedByCurrentUser)
Bookmark a feed item or remove a bookmark from a feed item.
voteOnFeedPoll(communityId, feedItemId, myChoiceId)
Vote or change your vote on a feed poll.
setTestGetFeedItemsFromFeed(communityId, feedType, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFeed(communityId, feedType, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
showInternalOnly, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching getFeedItemsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching getFeedItemsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.

1018
Apex Reference Guide ChatterFeeds Class

setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize,


sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching getFeedItemsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedItemsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam,
pageSize, sortParam, updatedSince, result)
Register a ConnectApi.FeedItemPage object to be returned when the
getFeedItemsFromFilterFeedUpdatedSince method is called in a test context.
setTestGetFeedItemsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince,
ConnectApi.FeedItemPage, results)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsUpdatedSince is called with
matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsUpdatedSince is called with
matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestGetFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, showInternalOnly, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsUpdatedSince is called with
matching parameters in a test context. Use the method with the same parameters or the code throws an exception.
setTestSearchFeedItems(communityId, q, result)
Register a test feed item page to be returned when searchFeedItems(communityId, q) is called during a test.
setTestSearchFeedItems(communityId, q, sortParam, result)
Register a test feed item page to be returned when searchFeedItems(String, String,
ConnectApi.FeedSortOrder) is called during a test.
setTestSearchFeedItems(communityId, q, pageParam, pageSize, result)
Register a test feed item page to be returned when searchFeedItems(String, String, String, Integer) is
called during a test.
setTestSearchFeedItems(communityId, q, pageParam, pageSize, sortParam, result)
Register a test feed item page to be returned when searchFeedItems(String, String, String, Integer,
ConnectApi.FeedSortOrder) is called during a test.
setTestSearchFeedItems(communityId, q, recentCommentCount, pageParam, pageSize, sortParam, result)
Register a test feed item page to be returned when searchFeedItems(communityId, q, recentCommentCount,
pageParam, pageSize, sortParam) is called during a test.
setTestSearchFeedItemsInFeed(communityId, feedType, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedItemsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

1019
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedItemsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q, result)


Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
q, showInternalOnly, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.
setTestSearchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.
setTestSearchFeedItemsInFilterFeed(communityId, feedType, subjectId, keyPrefix, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.
setTestSearchFeedItemsInFilterFeed(communityId, feedType, subjectId, keyPrefix, recentCommentCount, density, pageParam,
pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFilterFeed method is called in a test context. Use the method with the same
parameters or you receive an exception.

deleteFeedItem(communityId, feedItemId)
Delete a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use deleteFeedElement(communityId, feedElementId).

1020
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static Void deleteFeedItem(String communityId, String feedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.

Return Value
Type: Void

getCommentsForFeedItem(communityId, feedItemId)
Get comments for a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use getCommentsForFeedElement(communityId, feedElementId).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getCommentsForFeedItem(String communityId, String
feedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

1021
Apex Reference Guide ChatterFeeds Class

feedItemId
Type: String
ID for a feed item.

Return Value
Type: ConnectApi.CommentPage

getCommentsForFeedItem(communityId, feedItemId, pageParam, pageSize)


Get a page of comments for a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use getCommentsForFeedElement(communityId, feedElementId, pageParam, pageSize).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.CommentPage getCommentsForFeedItem(String communityId, String
feedItemId, String pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

1022
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.CommentPage

getFeedItem(communityId, feedItemId)
Get a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElement(communityId, feedElementId).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItem getFeedItem(String communityId, String feedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.

Return Value
Type: ConnectApi.FeedItem

Note: Triggers on FeedItem objects run before their attachment and capabilities information is saved, which means that
ConnectApi.FeedItem.attachment information and ConnectApi.FeedElement.capabilities information
may not be available in the trigger.

getFeedItemBatch(communityId, feedItemIds)
Get a list of feed items.

API Version
31.0–31.0

1023
Apex Reference Guide ChatterFeeds Class

Important: In version 32.0 and later, use getFeedElementBatch(communityId, feedElementIds).

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] getFeedItemBatch(String communityId, List<String>
feedItemIds)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemIds
Type: List<String>
A list of up to 500 feed item IDs.

Return Value
Type: ConnectApi.BatchResult[]
The ConnectApi.BatchResult.getResult() method returns a ConnectApi.FeedItem object and errors for feed
items that didn’t load.

Example
// Create a list of feed items.
ConnectApi.FeedItemPage feedItemPage = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null,
ConnectApi.FeedType.Company);
System.debug(feedItemPage);

// Create a list of feed item IDs.


List<String> feedItemIds = new List<String>();
for (ConnectApi.FeedItem aFeedItem : feedItemPage.items){
feedItemIds.add(aFeedItem.id);
}

// Get info about the feed items in the list.


ConnectApi.BatchResult[] batchResults = ConnectApi.ChatterFeeds.getFeedItemBatch(null,
feedItemIds);

for (ConnectApi.BatchResult batchResult : batchResults) {


if (batchResult.isSuccess()) {
// Operation was successful.
// Print the header for each feed item.
ConnectApi.FeedItem aFeedItem;
if(batchResult.getResult() instanceof ConnectApi.FeedItem) {
aFeedItem = (ConnectApi.FeedItem) batchResult.getResult();

1024
Apex Reference Guide ChatterFeeds Class

}
System.debug('SUCCESS');
System.debug(aFeedItem.header.text);
}
else {
// Operation failed. Print errors.
System.debug('FAILURE');
System.debug(batchResult.getErrorMessage());
}
}

getFeedItemsFromFeed(communityId, feedType)
Get feed items from the Company, Home, and Moderation feeds.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.

Return Value
Type: ConnectApi.FeedItemPage

1025
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFeed(communityId, feedType, pageParam, pageSize, sortParam)


Get a page of sorted feed items from the Company, Home, and Moderation feeds.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType, pageParam, pageSize, sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer

1026
Apex Reference Guide ChatterFeeds Class

Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam)
Get a page of sorted feed items from the Company, Home, and Moderation feeds. Each feed item contains no more than the
specified number of comments.

API Version
29.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType, recentCommentCount, density,
pageParam, pageSize, sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

1027
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.

1028
Apex Reference Guide ChatterFeeds Class

Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFeed(communityId, feedType, subjectId)


Get feed items from a feed for a user or record.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType, subjectId).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.

1029
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFeed(communityId, feedType, subjectId, pageParam, pageSize,


sortParam)
Get a page of sorted feed items from a feed for a user or record.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType, subjectId, pageParam, pageSize,
sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String

1030
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

1031
Apex Reference Guide ChatterFeeds Class

getFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam)
Get a page of sorted feed items from a feed for a user or record. Each feed item includes no more than the specified number of comments.

API Version
29.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,
density, pageParam, pageSize, sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.

1032
Apex Reference Guide ChatterFeeds Class

• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, showInternalOnly)
Get a page of sorted feed items from a record feed for a user or record. Each feed item includes no more than the specified number of
comments. Specify whether to return feed items posted by internal (non-Experience Cloud site) users only.

1033
Apex Reference Guide ChatterFeeds Class

API Version
30.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFeed(communityId, feedType, subjectId, recentCommentCount,
density, pageParam, pageSize, sortParam, showInternalOnly).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String

1034
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix)


Get feed items from a feed filtered by a key prefix for a user.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix).

1035
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFilterFeed(String communityId,
String subjectId, String keyPrefix)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam,


pageSize, sortParam)
Get a page of sorted feed items from a feed filtered by a key prefix for a user.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize,
sortParam).

1036
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFilterFeed(String communityId,
String subjectId, String keyPrefix, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

1037
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, density, pageParam, pageSize, sortParam)
Get a page of sorted feed items from a feed filtered by a key prefix for a user. Each feed item contains no more than the specified number
of comments.

API Version
29.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount,
elementsPerBundle, density, pageParam, pageSize, sortParam).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFilterFeed(String communityId,
String subjectId, String keyPrefix, Integer recentCommentCount, ConnectApi.FeedDensity
density, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.

1038
Apex Reference Guide ChatterFeeds Class

density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize,
sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

1039
Apex Reference Guide ChatterFeeds Class

getFeedItemsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix,


recentCommentCount, density, pageParam, pageSize, updatedSince)
Get a page of feed items from a feed filtered by a key prefix for a user. Include only feed items that have been updated since the time
specified in the updatedSince parameter.

API Version
30.0–31.0

Important: In version 32.0 and later, use getFeedElementsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix,


recentCommentCount, elementsPerBundle, density, pageParam, pageSize, updatedSince).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsFromFilterFeedUpdatedSince(String
communityId, String subjectId, String keyPrefix, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.

1040
Apex Reference Guide ChatterFeeds Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
Opaque token containing information about the last modified date of the feed. Do not construct this token. To retrieve this token,
call getFeedItemsFromFilterFeed and take the value from the updatesToken property of the
ConnectApi.FeedItemPage response body.

Return Value
Type: ConnectApi.FeedItemPage

Usage
This method returns only feed items that have been updated since the time specified in the updatedSince argument. A feed item
is considered to be updated if it was created since the last feed request, or if sort=LastModifiedDateDesc and a comment
was added to the feed item since the last feed request. Adding likes and topics doesn’t update a feed item.
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestGetFeedItemsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam,
pageSize, sortParam, updatedSince, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsUpdatedSince(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, updatedSince)
Get a page of feed items from the Company, Home, and Moderation feeds. Include only feed items that have been updated since
the time specified in the updatedSince parameter. Each feed item contains no more than the specified number of comments.

API Version
30.0–31.0

Important: In version 32.0 and later, use getFeedElementsUpdatedSince(communityId, feedType, recentCommentCount, density,
pageParam, pageSize, updatedSince).

Available to Guest Users


31.0 only

1041
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, String updatedSince)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedItemPage response body.

Return Value
Type: ConnectApi.FeedItemPage

1042
Apex Reference Guide ChatterFeeds Class

Usage
This method returns only feed items that have been updated since the time specified in the updatedSince argument. A feed item
is considered to be updated if it was created since the last feed request, or if sort=LastModifiedDateDesc and a comment
was added to the feed item since the last feed request. Adding likes and topics doesn’t update a feed item.
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

Example
This example gets the feed items in the company feed and grabs the updatesToken property from the returned object. It then
passes the value of updatesToken to the getFeedItemsUpdatedSince method to get the feed items updated since the
first call:
// Get the feed items in the company feed and return the updatesToken
String communityId = null;

// Get the feed and extract the update token


ConnectApi.FeedItemPage page = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(communityId,
ConnectApi.FeedType.Company);

// page.updatesToken is opaque and has a value like '2:1384549034000'

// Get the feed items that changed since the provided updatesToken
ConnectApi.FeedItemPage feedItems= ConnectApi.ChatterFeeds.getFeedItemsUpdatedSince
(communityId, ConnectApi.FeedType.Company, 1, ConnectApi.FeedDensity.AllUpdates, null,
1, page.updatesToken);

SEE ALSO:
setTestGetFeedItemsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince,
ConnectApi.FeedItemPage, results)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, updatedSince)
Get a page of feed items from the Files, Groups, News, People, and Record feeds. Include only feed items that have been
updated since the time specified in the updatedSince parameter. Each feed item contains no more than the specified number of
comments.

API Version
30.0–31.0

Important: In version 32.0 and later, use getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount,
density, pageParam, pageSize, updatedSince).

Available to Guest Users


31.0 only

1043
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of these values:
• Files
• Groups
• News
• People
• Record
subjectId
Type: String
If feedType is ConnectApi.Record, subjectId can be any record ID, including a group ID. Otherwise, it must be the
context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

1044
Apex Reference Guide ChatterFeeds Class

updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedItemPage response body.

Return Value
Type: ConnectApi.FeedItemPage

Usage
This method returns only feed items that have been updated since the time specified in the updatedSince argument. A feed item
is considered to be updated if it was created since the last feed request, or if sort=LastModifiedDateDesc and a comment
was added to the feed item since the last feed request. Adding likes and topics doesn’t update a feed item.
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

Example
This example gets the feed items in the news feed and grabs the updatesToken property from the returned object. It then passes
the value of updatesToken to the getFeedItemsUpdatedSince method to get the feed items updated since the first call:
// Get the feed items in the news feed and return the updatesToken
String communityId = null;
String subjectId = 'me';

// Get the feed and extract the update token


ConnectApi.FeedItemPage page = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(communityId,
ConnectApi.FeedType.News, subjectId);

// page.updatesToken is opaque and has a value like '2:1384549034000'

// Get the feed items that changed since the provided updatesToken
ConnectApi.FeedItemPage feedItems= ConnectApi.ChatterFeeds.getFeedItemsUpdatedSince
(communityId, ConnectApi.FeedType.News, subjectId, 1, ConnectApi.FeedDensity.AllUpdates,
null, 1, page.updatesToken);

SEE ALSO:
setTestGetFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, updatedSince, showInternalOnly)
Get a page of feed items from a record feed. Include only feed items that have been updated since the time specified in the
updatedSince parameter. Specify whether to return feed items posted by internal (non-Experience Cloud site) users only.

1045
Apex Reference Guide ChatterFeeds Class

API Version
30.0–31.0

Important: In version 32.0 and later, use getFeedElementsUpdatedSince(communityId, feedType, subjectId, recentCommentCount,
density, pageParam, pageSize, updatedSince, showInternalOnly).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage getFeedItemsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince,
Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String

1046
Apex Reference Guide ChatterFeeds Class

Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedItemPage response body.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

Return Value
Type: ConnectApi.FeedItemPage

Usage
This method returns only feed items that have been updated since the time specified in the updatedSince argument. A feed item
is considered to be updated if it was created since the last feed request, or if sort=LastModifiedDateDesc and a comment
was added to the feed item since the last feed request. Adding likes and topics doesn’t update a feed item.
If showInternalOnly is true and digital experiences is enabled, feed items from Experience Cloud sites are included. Otherwise,
only feed items from the internal site are included.
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

Example
This example gets the feed items in the news feed and grabs the updatesToken property from the returned object. It then passes
the value of updatesToken to the getFeedItemsUpdatedSince method to get the feed items updated since the first call:
// Get the feed items in the news feed and return the updatesToken
String communityId = null;
String subjectId = 'me';

// Get the feed and extract the update token


ConnectApi.FeedItemPage page = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(communityId,
ConnectApi.FeedType.News, subjectId);

// page.updatesToken is opaque and has a value like '2:1384549034000'

// Get the feed items that changed since the provided updatesToken
ConnectApi.FeedItemPage feedItems= ConnectApi.ChatterFeeds.getFeedItemsUpdatedSince

1047
Apex Reference Guide ChatterFeeds Class

(communityId, ConnectApi.FeedType.News, subjectId, 1, ConnectApi.FeedDensity.AllUpdates,


null, 1, page.updatesToken, true);

SEE ALSO:
setTestGetFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize,
updatedSince, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

getFeedPoll(communityId, feedItemId)
Get the poll associated with a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use getFeedElementPoll(communityId, feedElementId).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedPoll getFeedPoll(String communityId, String feedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.

Return Value
Type: ConnectApi.FeedPoll

Note: Triggers on FeedItem objects run before their attachment and capabilities information is saved, which means that
ConnectApi.FeedItem.attachment information and ConnectApi.FeedElement.capabilities information
may not be available in the trigger.

getLikesForFeedItem(communityId, feedItemId)
Get likes for a feed item.

1048
Apex Reference Guide ChatterFeeds Class

API Version
28.0–31.0

Important: In version 32.0 and later, use getLikesForFeedElement(communityId, feedElementId).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLikePage getLikesForFeedItem(String communityId, String
feedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.

Return Value
Type: ConnectApi.ChatterLikePage

getLikesForFeedItem(communityId, feedItemId, pageParam, pageSize)


Get a page of likes for a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use getLikesForFeedElement(communityId, feedElementId, pageParam, pageSize).

Available to Guest Users


31.0 only

Requires Chatter
Yes

1049
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.ChatterLikePage getLikesForFeedItem(String communityId, String
feedItemId, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterLikePage

likeFeedItem(communityId, feedItemId)
Like a feed item for the context user.

API Version
28.0–31.0

Important: In version 32.0 and later, use likeFeedElement(communityId, feedElementId).

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterLike likeFeedItem(String communityId, String feedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

1050
Apex Reference Guide ChatterFeeds Class

feedItemId
Type: String
ID for a feed item.

Return Value
Type: ConnectApi.ChatterLike
If the context user already liked the feed item, this method is a non-operation and returns the existing like.

postComment(communityId, feedItemId, text)


Post a plain-text comment to a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use postCommentToFeedElement(communityId, feedElementId, text).

Requires Chatter
Yes

Signature
public static ConnectApi.Comment postComment(String communityId, String feedItemId,
String text)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.
text
Type: String
The text of the comment. Mentions are downgraded to plain text. To include a mention that links to a user, call
postComment(communityId, feedItemId, comment, feedItemFileUpload) and pass the mention in a
ConnectApi.CommentInput object.

Return Value
Type: ConnectApi.Comment

1051
Apex Reference Guide ChatterFeeds Class

Usage
If hashtags or links are detected in text, they’re included in the comment as hashtag and link segments. Mentions aren’t detected in
text and aren’t separated out of the text.
Feed items and comments can contain up to 10,000 characters.

postComment(communityId, feedItemId, comment, feedItemFileUpload)


Post a rich-text comment to a feed item. Use this method to include mentions and to attach a file to a comment.

API Version
28.0–31.0

Important: In version 32.0 and later, use postCommentToFeedElement(communityId, feedElementId, comment,


feedElementFileUpload).

Requires Chatter
Yes

Signature
public static ConnectApi.Comment postComment(String communityId, String feedItemId,
ConnectApi.CommentInput comment, ConnectApi.BinaryInput feedItemFileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.
comment
Type: ConnectApi.CommentInput
In the CommentInput object, specify rich text, including @mentions. Optionally, in the CommentInput.attachment
property, specify an existing file or a new file
feedItemFileUpload
Type: ConnectApi.BinaryInput
If you specify a NewFileAttachmentInput object in the CommentInput.attachment property, specify the new
binary file to attach in this argument. Otherwise, do not specify a value.

Return Value
Type: ConnectApi.Comment

1052
Apex Reference Guide ChatterFeeds Class

Usage
Feed items and comments can contain up to 10,000 characters.

Sample: Posting a Comment with a New File Attachment


To post a comment and upload and attach a new file to the comment, create a ConnectApi.CommentInput object and a
ConnectApi.BinaryInput object to pass to the ConnectApi.ChatterFeeds.postComment method.

String communityId = null;


String feedItemId = '0D5D0000000Kcd1';

ConnectApi.CommentInput input = new ConnectApi.CommentInput();


ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegment;

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = 'Comment Text Body';

messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();


messageInput.messageSegments.add(textSegment);

input.body = messageInput;

ConnectApi.NewFileAttachmentInput attachmentInput = new ConnectApi.NewFileAttachmentInput();


attachmentInput.description = 'The description of the file';
attachmentInput.title = 'contentFile.txt';
input.attachment = attachmentInput;

String fileContents = 'This is the content of the file.';


Blob fileBlob = Blob.valueOf(fileContents);
ConnectApi.BinaryInput binaryInput = new ConnectApi.BinaryInput(fileBlob, 'text/plain',
'contentFile.txt');

ConnectApi.Comment commentRep = ConnectApi.ChatterFeeds.postComment(communityId, feedItemId,


input, binaryInput);

postFeedElement(communityId, feedElement, feedElementFileUpload)


Post a rich-text feed element. Include mentions and hashtag topics, attach a file to a feed element, and associate action link groups with
a feed element. You can also use this method to share a feed element and add a comment.

API Version
31.0–35.0

Important: In version 36.0 and later, this method is no longer available because you can’t create a feed post and upload a binary
file in the same call. Upload files to Salesforce first, and then use postFeedElement(communityId, feedElement)
to create the feed post and attach the files.

Requires Chatter
Yes

1053
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElement postFeedElement(String communityId,
ConnectApi.FeedElementInput feedElement, ConnectApi.BinaryInput feedElementFileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedElement
Type: ConnectApi.FeedElementInput
Specify rich text, including mentions. Optionally, specify a link, a poll, an existing file, or a new file.
feedElementFileUpload
Type: ConnectApi.BinaryInput
Specify the new binary file to attach to the post only if you also specify a NewFileAttachmentInput object in the
feedElement parameter. Otherwise, pass null.

Return Value
Type: ConnectApi.FeedElement

Example for Posting a Feed Element with a New (Binary) File


ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
input.subjectId = 'me';

ConnectApi.ContentCapabilityInput contentInput = new ConnectApi.ContentCapabilityInput();


contentInput.title = 'Title';

ConnectApi.FeedElementCapabilitiesInput capabilities = new


ConnectApi.FeedElementCapabilitiesInput();
capabilities.content = contentInput;

input.capabilities = capabilities;

String text = 'These are the contents of the new file.';


Blob myBlob = Blob.valueOf(text);
ConnectApi.BinaryInput binInput = new ConnectApi.BinaryInput(myBlob, 'text/plain',
'fileName');

ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), input, binInput);

postFeedItem(communityId, feedType, subjectId, text)


Post a plain-text feed item.

API Version
28.0–31.0

1054
Apex Reference Guide ChatterFeeds Class

Important: In version 32.0 and later, use postFeedElement(communityId, subjectId, feedElementType, text).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItem postFeedItem(String communityId, ConnectApi.FeedType
feedType, String subjectId, String text)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of the following:
• News
• Record
• UserProfile
Use Record to post to a group.
subjectId
Type: String
The value depends on the feedType:
• News—ID of the context user or the keyword me.
• Record—ID of any record with a feed, including groups.
• UserProfile—ID of any user.
text
Type: String
Text of the feed item. Mentions are downgraded to plain text. To include a mention that links to the user, call the
postFeedItem(communityId, feedType, subjectId, feedItemInput, feedItemFileUpload)
method and pass the mention in a ConnectApi.FeedItemInput object.

Return Value
Type: ConnectApi.FeedItem

Note: Triggers on FeedItem objects run before their attachment and capabilities information is saved, which means that
ConnectApi.FeedItem.attachment information and ConnectApi.FeedElement.capabilities information
may not be available in the trigger.

1055
Apex Reference Guide ChatterFeeds Class

Usage
Feed items and comments can contain up to 10,000 characters.
Posts to ConnectApi.FeedType.UserProfile in API versions 23.0 and 24.0 created user status updates, not feed items. For
posts to the User Profile Feed in those API versions, the character limit is 1,000 characters.

postFeedItem(communityId, feedType, subjectId, feedItemInput,


feedItemFileUpload)
Post a rich-text feed item to a feed. Use this method to include mentions and hashtag topics and to attach a file to a feed item. You can
also use this method to share a feed item and add a comment.

API Version
28.0–31.0

Important: In version 32.0 and later, use postFeedElement(communityId, feedElement, feedElementFileUpload).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItem postFeedItem(String communityId, ConnectApi.FeedType
feedType, String subjectId, ConnectApi.FeedItemInput feedItemInput,
ConnectApi.BinaryInput feedItemFileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of the following:
• News
• Record
• UserProfile
To post a feed item to a group, use Record and use a group ID as the subjectId.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
feedItemInput
Type: ConnectApi.FeedItemInput

1056
Apex Reference Guide ChatterFeeds Class

In the FeedItemInput object, specify rich text. Optionally, in the FeedItemInput.attachment property, specify a link,
a poll, an existing file, or a new file.
feedItemFileUpload
Type: ConnectApi.BinaryInput
If you specify a NewFileAttachmentInput object in the FeedItemInput.attachment property, specify the new
binary file to attach in this argument. Otherwise, do not specify a value.

Return Value
Type: ConnectApi.FeedItem

Note: Triggers on FeedItem objects run before their attachment and capabilities information is saved, which means that
ConnectApi.FeedItem.attachment information and ConnectApi.FeedElement.capabilities information
may not be available in the trigger.

Usage
Feed items and comments can contain up to 10,000 characters. Posts to ConnectApi.FeedType.UserProfile in API versions
23.0 and 24.0 created user status updates, not feed items. For posts to the User Profile Feed in those API versions, the character limit is
1,000 characters.

Example for Sharing a Feed Item and Adding a Comment


To share a feed item and add a comment, create a ConnectApi.FeedItemInput object containing the comment and the feed
item to share. Then pass the object to ConnectApi.ChatterFeeds.postFeeditem in the feedItemInput argument.
The message segments in the message body input are used as the comment.
ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
input.originalFeedItemId = '0D5D0000000JuAG';

ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();


List<ConnectApi.MessageSegmentInput> segmentList = new
List<ConnectApi.MessageSegmentInput>();
ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
textSegment.text = 'I hope you enjoy this post I found in another group.';
segmentList.add((ConnectApi.MessageSegmentInput)textSegment);
body.messageSegments = segmentList;
input.body = body;

ConnectApi.ChatterFeeds.postFeedItem(null, ConnectApi.FeedType.UserProfile, 'me', input,


null);

Example for Posting a Mention to a User Profile Feed


To post to a user profile feed and include an @mention, call the ConnectApi.ChatterFeeds.postFeedItem method.
String communityId = null;
ConnectApi.FeedType feedType = ConnectApi.FeedType.UserProfile;

ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();


ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegment;

1057
Apex Reference Guide ChatterFeeds Class

ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();

messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = 'Hey there ';
messageInput.messageSegments.add(textSegment);

mentionSegment.id = '005D0000001LLO1';
messageInput.messageSegments.add(mentionSegment);

textSegment = new ConnectApi.TextSegmentInput();


textSegment.text = '. How are you?';
messageInput.messageSegments.add(textSegment);

input.body = messageInput;

ConnectApi.FeedItem feedItemRep = ConnectApi.ChatterFeeds.postFeedItem(communityId, feedType,


'me', input, null);

searchFeedItems(communityId, q)
Get the feed items that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElements(communityId, q).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItems(String communityId, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

1058
Apex Reference Guide ChatterFeeds Class

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItems(communityId, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItems(communityId, q, sortParam)
Get the sorted feed items that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElements(communityId, q, sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItems(String communityId, String q,
ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:

1059
Apex Reference Guide ChatterFeeds Class

• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItems(communityId, q, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItems(communityId, q, pageParam, pageSize)


Get a page of feed items that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElements(communityId, q, pageParam, pageSize).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItems(String communityId, String q,
String pageParam, Integer pageSize)

1060
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItems(communityId, q, pageParam, pageSize, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItems(communityId, q, pageParam, pageSize, sortParam)


Get a page of sorted feed items that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElements(communityId, q, pageParam, pageSize, sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

1061
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedItemPage searchFeedItems(String communityId, String q,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

1062
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItems(communityId, q, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItems(communityId, q, recentCommentCount, pageParam, pageSize,


sortParam)
Get a page of sorted feed items that match the search criteria.

API Version
29.0–31.0

Important: In version 32.0 and later, use searchFeedElements(communityId, q, recentCommentCount, pageParam, pageSize,
sortParam).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItems(String communityId, String q,
Integer recentCommentCount, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.

1063
Apex Reference Guide ChatterFeeds Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItems(communityId, q, recentCommentCount, pageParam, pageSize, sortParam, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFeed(communityId, feedType, q)
Get the feed items from the Company, Home, and Moderation feeds that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, q).

1064
Apex Reference Guide ChatterFeeds Class

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFeed(communityId, feedType, pageParam, pageSize, sortParam,


q)
Get a page of sorted feed items from the Company, Home, and Moderation feeds that match the search criteria.

API Version
28.0–31.0

1065
Apex Reference Guide ChatterFeeds Class

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, pageParam, pageSize, sortParam,
q).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.

1066
Apex Reference Guide ChatterFeeds Class

q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFeed(communityId, feedType, recentCommentCount, density,


pageParam, pageSize, sortParam, q)
Get a page of sorted feed items from the Company, Home, and Moderation feeds that match the search criteria. Each feed item
includes no more than the specified number of comments.

API Version
29.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, recentCommentCount, density,
pageParam, pageSize, sortParam, q).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String

1067
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

1068
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFeed(communityId, feedType, subjectId, q)


Get the feed items from a feed that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, subjectId, q).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feed type is UserProfile, subjectId
can be any user ID. If feedType is any other value, subjectId must be the ID of the context user or the alias me.
q
Type: String

1069
Apex Reference Guide ChatterFeeds Class

Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFeed(communityId, feedType, subjectId, pageParam, pageSize,


sortParam, q)
Get a page of sorted feed items from a feed for a user or record that match the search criteria.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, subjectId, pageParam, pageSize,
sortParam, q).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType

1070
Apex Reference Guide ChatterFeeds Class

Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Order of feed items in the feed.
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Search term. Searches keywords in the user or group name. A minimum of one character is required. This parameter doesn’t support
wildcards. This parameter is required.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

1071
Apex Reference Guide ChatterFeeds Class

searchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items from a feed that match the search criteria. Each feed item includes no more than the specified number
of comments.

API Version
29.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,
density, pageParam, pageSize, sortParam, q).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.

1072
Apex Reference Guide ChatterFeeds Class

• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
q, result)
Apex Developer Guide: Testing ConnectApi Code

1073
Apex Reference Guide ChatterFeeds Class

searchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount,


density, pageParam, pageSize, sortParam, q, showInternalOnly)
Get a page of sorted feed items from a feed for a user or record that match the search criteria. Each feed item includes no more than the
specified number of comments. Specify whether to return feed items posted by internal (non-Experience Cloud site) users only.

API Version
30.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFeed(communityId, feedType, subjectId, recentCommentCount,
density, pageParam, pageSize, sortParam, q, showInternalOnly).

Available to Guest Users


31.0 only

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, Boolean showInternalOnly)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Value must be ConnectApi.FeedType.Record.
subjectId
Type: String
Any record ID, including a group ID.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.

1074
Apex Reference Guide ChatterFeeds Class

• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
q, showInternalOnly, result)
Apex Developer Guide: Testing ConnectApi Code

1075
Apex Reference Guide ChatterFeeds Class

searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, q)


Get the feed items that match the search criteria from a feed filtered by a key prefix for a user.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, q).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFilterFeed(String communityId,
String subjectId, String keyPrefix, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

1076
Apex Reference Guide ChatterFeeds Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, pageParam,


pageSize, sortParam, q)
Get a page of sorted feed items that match the search criteria from a feed filtered by a key prefix for a user.

API Version
28.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize,
sortParam, q).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFilterFeed(String communityId,
String subjectId, String keyPrefix, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.

1077
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFilterFeed(communityId, feedType, subjectId, keyPrefix, pageParam, pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, density, pageParam, pageSize, sortParam, q)
Get a page of sorted feed items that match the search criteria from a feed filtered by a key prefix for a user. Each feed item includes no
more than the specified number of comments.

API Version
29.0–31.0

Important: In version 32.0 and later, use searchFeedElementsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount,
density, pageParam, pageSize, sortParam, q).

1078
Apex Reference Guide ChatterFeeds Class

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItemPage searchFeedItemsInFilterFeed(String communityId,
String subjectId, String keyPrefix, Integer recentCommentCount, ConnectApi.FeedDensity
density, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String
q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:

1079
Apex Reference Guide ChatterFeeds Class

• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.FeedItemPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchFeedItemsInFilterFeed(communityId, feedType, subjectId, keyPrefix, recentCommentCount, density, pageParam,
pageSize, sortParam, q, result)
Apex Developer Guide: Testing ConnectApi Code

shareFeedElement(communityId, subjectId, feedElementType,


originalFeedElementId)
Share the originalFeedElementId as the context user.

API Version
31.0–38.0

Important: In version 39.0 and later, use postFeedElement(communityId, feedElement) or


updateFeedElement(communityId, feedElementId, feedElement) with the
ConnectApi.FeedEntityShareCapabilityInput to share a feed entity with a feed element.

Requires Chatter
Yes

1080
Apex Reference Guide ChatterFeeds Class

Signature
public static ConnectApi.FeedElement shareFeedElement(String communityId, String
subjectId, ConnectApi.FeedElementType feedElementType, String originalFeedElementId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
The ID of the user or group with whom to share the feed element.
feedElementType
Type: ConnectApi.FeedElementType
Values are:
• Bundle—A container of feed elements. A bundle also has a body made up of message segments that can always be gracefully
degraded to text-only values.
• FeedItem—A feed item has a single parent and is scoped to oneExperience Cloud site or across all Experience Cloud sites. A
feed item can have capabilities such as bookmarks, canvas, content, comment, link, poll. Feed items have a body made up of
message segments that can always be gracefully degraded to text-only values.
• Recommendation—A recommendation is a feed element with a recommendations capability. A recommendation suggests
records to follow, groups to join, or applications that are helpful to the context user.
originalFeedElementId
Type: String
The ID of the feed element to share.

Return Value
Type: ConnectApi.FeedElement

Example
ConnectApi.ChatterFeeds.shareFeedElement(null, '0F9RR0000004CPw',
ConnectApi.FeedElementType.FeedItem, '0D5RR0000004Gxc');

shareFeedItem(communityId, feedType, subjectId, originalFeedItemId)


Share the originalFeedItemId to the feed specified by the feedType.

API Version
28.0–31.0

Important:
• In version 32.0–38.0, use shareFeedElement(communityId, subjectId, feedElementType,
originalFeedElementId).

1081
Apex Reference Guide ChatterFeeds Class

• In version 39.0 and later, use postFeedElement(communityId, feedElement) or


updateFeedElement(communityId, feedElementId, feedElement) with the
ConnectApi.FeedEntityShareCapabilityInput.

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItem shareFeedItem(String communityId, ConnectApi.FeedType
feedType, String subjectId, String originalFeedItemId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of the following:
• News
• Record
• UserProfile
To share a feed item with a group, use Record and use a group ID as the subjectId.
subjectId
Type: String
The value depends on the value of feedType:
• News—subjectId must be the ID of the context user or the keyword me.
• Record—subjectId can be a group ID or the ID of the context user (or me).
• UserProfile—subjectId can be any user ID.
originalFeedItemId
Type: String
The ID of the feed item to share.

Return Value
Type: ConnectApi.FeedItem

1082
Apex Reference Guide ChatterFeeds Class

Example
To share a feed item with a group, pass in the Experience Cloud site ID (or null), the feed type Record, the group ID, and the ID of
the feed item to share.
ConnectApi.ChatterFeeds.shareFeedItem(null, ConnectApi.FeedType.Record, '0F9D00000000izf',
'0D5D0000000JuAG');

updateBookmark(communityId, feedItemId, isBookmarkedByCurrentUser)


Bookmark a feed item or remove a bookmark from a feed item.

API Version
28.0–31.0

Important: In version 32.0 and later, use updateFeedElementBookmarks(communityId, feedElementId, bookmarks) or


updateFeedElementBookmarks(communityId, feedElementId, isBookmarkedByCurrentUser).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedItem updateBookmark(String communityId, String feedItemId,
Boolean isBookmarkedByCurrentUser)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID for a feed item.
isBookmarkedByCurrentUser
Type: Boolean
—Specifying true adds the feed item to the list of bookmarks for the context user. Specify false to remove a bookmark.

Return Value
Type: ConnectApi.FeedItem

voteOnFeedPoll(communityId, feedItemId, myChoiceId)


Vote or change your vote on a feed poll.

1083
Apex Reference Guide ChatterFeeds Class

API Version
28.0–31.0

Important: In version 32.0 and later, use voteOnFeedElementPoll(communityId, feedElementId, myChoiceId).

Requires Chatter
Yes

Signature
public static ConnectApi.FeedPoll voteOnFeedPoll(String communityId, String feedItemId,
String myChoiceId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedItemId
Type: String
ID of the feed item that is associated with the poll.
myChoiceId
Type: String
ID of the item in the poll you’re voting for.

Return Value
Type: ConnectApi.FeedPoll

setTestGetFeedItemsFromFeed(communityId, feedType, result)


Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String

1084
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFeed(communityId, feedType, pageParam, pageSize,


sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.

1085
Apex Reference Guide ChatterFeeds Class

pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
29.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, Integer recentCommentCount, ConnectApi.FeedDensity density, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedItemPage result)

1086
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

1087
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, result)


Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

1088
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType, subjectId)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFeed(communityId, feedType, subjectId, pageParam,


pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

1089
Apex Reference Guide ChatterFeeds Class

sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
29.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String

1090
Apex Reference Guide ChatterFeeds Class

ID for an Experience Cloud site, internal, or null.


feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage

1091
Apex Reference Guide ChatterFeeds Class

Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, showInternalOnly,
result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsFromFeed is called with matching
parameters in a test context. Use the get feed method with the same parameters or the code throws an exception.

API Version
30.0–31.0

Signature
public static Void setTestGetFeedItemsFromFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, Boolean
showInternalOnly, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.

1092
Apex Reference Guide ChatterFeeds Class

density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam,
showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

1093
Apex Reference Guide ChatterFeeds Class

setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, result)


Register a ConnectApi.FeedItemPage object to be returned when the matching getFeedItemsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.

API Version
28.0–31.0

Signature
public static Void setTestGetFeedItemsFromFilterFeed(String communityId, String
subjectId, String keyPrefix, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix,


pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching getFeedItemsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.

API Version
28.0–31.0

1094
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestGetFeedItemsFromFilterFeed(String communityId, String
subjectId, String keyPrefix, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

1095
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix,


recentCommentCount, density, pageParam, pageSize, sortParam, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching getFeedItemsFromFilterFeed
method is called in a test context. Use the method with the same parameters or the code throws an exception.

API Version
29.0–31.0

Signature
public static Void setTestGetFeedItemsFromFilterFeed(String communityId, String
subjectId, String keyPrefix, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam,
ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.

1096
Apex Reference Guide ChatterFeeds Class

• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsFromFilterFeedUpdatedSince(communityId, subjectId,
keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam,
updatedSince, result)
Register a ConnectApi.FeedItemPage object to be returned when the getFeedItemsFromFilterFeedUpdatedSince
method is called in a test context.

API Version
30.0–31.0

1097
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestGetFeedItemsFromFilterFeedUpdatedSince(String communityId,
String subjectId, String keyPrefix, Integer recentCommentCount, ConnectApi.FeedDensity
density, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String
updatedSince, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.

1098
Apex Reference Guide ChatterFeeds Class

• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
updatedSince
Type: String
Opaque token containing information about the last modified date of the feed. Do not construct this token. To retrieve this token,
call getFeedItemsFromFilterFeed and take the value from the updatesToken property of the
ConnectApi.FeedItemPage response body.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsFromFilterFeedUpdatedSince(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize,
updatedSince)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsUpdatedSince(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, updatedSince, ConnectApi.FeedItemPage, results)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsUpdatedSince is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
30.0–31.0

Signature
public static Void setTestGetFeedItemsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, String updatedSince, ConnectApi.FeedItemPage results)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType

1099
Apex Reference Guide ChatterFeeds Class

Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedItemPage response body.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsUpdatedSince(communityId, feedType, recentCommentCount, density, pageParam, pageSize, updatedSince)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, updatedSince, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsUpdatedSince is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
30.0–31.0

1100
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestGetFeedItemsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince,
ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of these values:
• Files
• Groups
• News
• People
• Record
subjectId
Type: String
If feedType is ConnectApi.Record, subjectId can be any record ID, including a group ID. Otherwise, it must be the
context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String

1101
Apex Reference Guide ChatterFeeds Class

An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedItemPage response body.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, updatedSince)
Apex Developer Guide: Testing ConnectApi Code

setTestGetFeedItemsUpdatedSince(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly, result)
Register a ConnectApi.FeedItemPage object to be returned when getFeedItemsUpdatedSince is called with matching
parameters in a test context. Use the method with the same parameters or the code throws an exception.

API Version
30.0–31.0

Signature
public static Void setTestGetFeedItemsUpdatedSince(String communityId,
ConnectApi.FeedType feedType, String subjectId, Integer recentCommentCount,
ConnectApi.FeedDensity density, String pageParam, Integer pageSize, String updatedSince,
Boolean showInternalOnly, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
One of these values:
• Files
• Groups
• News
• People
• Record

1102
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
If feedType is ConnectApi.Record, subjectId can be any record ID, including a group ID. Otherwise, it must be the
context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
updatedSince
Type: String
An opaque token containing information about the last modified date of the feed. Do not construct this token. Retrieve this token
from the updatesToken property of the ConnectApi.FeedItemPage response body.
showInternalOnly
Type: Boolean
Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
getFeedItemsUpdatedSince(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, updatedSince,
showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

1103
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedItems(communityId, q, result)
Register a test feed item page to be returned when searchFeedItems(communityId, q) is called during a test.

API Version
28.0–31.0

Signature
public static Void searchFeedItems(String communityId, String q, ConnectApi.FeedItemPage
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedItems(communityId, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItems(communityId, q, sortParam, result)


Register a test feed item page to be returned when searchFeedItems(String, String,
ConnectApi.FeedSortOrder) is called during a test.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItems(String communityId, String q,
ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedItemPage result)

1104
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
The feed item test page.

Return Value
Type: Void

SEE ALSO:
searchFeedItems(communityId, q, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItems(communityId, q, pageParam, pageSize, result)


Register a test feed item page to be returned when searchFeedItems(String, String, String, Integer) is called
during a test.

API Version
28.0–31.0

1105
Apex Reference Guide ChatterFeeds Class

Signature
public static Void setTestSearchFeedItems(String communityId, String q, String pageParam,
Integer pageSize, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
result
Type: ConnectApi.FeedItemPage
The test feed item page.

Return Value
Type: Void

SEE ALSO:
searchFeedItems(communityId, q, pageParam, pageSize)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItems(communityId, q, pageParam, pageSize, sortParam, result)


Register a test feed item page to be returned when searchFeedItems(String, String, String, Integer,
ConnectApi.FeedSortOrder) is called during a test.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItems(String communityId, String q, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, ConnectApi.FeedItemPage result)

1106
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
The test feed item page.

Return Value
Type: Void

SEE ALSO:
searchFeedItems(communityId, q, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

1107
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedItems(communityId, q, recentCommentCount, pageParam,


pageSize, sortParam, result)
Register a test feed item page to be returned when searchFeedItems(communityId, q, recentCommentCount,
pageParam, pageSize, sortParam) is called during a test.

API Version
29.0–31.0

Signature
public static Void setTestSearchFeedItems(String communityId, String q, Integer
recentCommentCount, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.

1108
Apex Reference Guide ChatterFeeds Class

Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
result
Type: ConnectApi.FeedItemPage
The test feed item page.

Return Value
Type: Void

SEE ALSO:
searchFeedItems(communityId, q, recentCommentCount, pageParam, pageSize, sortParam)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, q, result)


Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, String q, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values are Company, DirectMessageModeration, DirectMessages, Home, Isolated,
Moderation, and PendingReview.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

1109
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, pageParam, pageSize,


sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String
q, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.

1110
Apex Reference Guide ChatterFeeds Class

• CreatedDateDesc—Sorts by most recent creation date.


• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, recentCommentCount,


density, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
29.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, Integer recentCommentCount, ConnectApi.FeedDensity density, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedItemPage
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

1111
Apex Reference Guide ChatterFeeds Class

feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

1112
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, recentCommentCount, density, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, q, result)


Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, String q, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

1113
Apex Reference Guide ChatterFeeds Class

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, subjectId, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, subjectId, pageParam,


pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, String pageParam, Integer pageSize, ConnectApi.FeedSortOrder
sortParam, String q, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

1114
Apex Reference Guide ChatterFeeds Class

sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, subjectId, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
29.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q,
ConnectApi.FeedItemPage result)

1115
Apex Reference Guide ChatterFeeds Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.
subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.

1116
Apex Reference Guide ChatterFeeds Class

Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFeed(communityId, feedType, subjectId,


recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFeed method is called in a test context. Use the method with the same parameters or you
receive an exception.

API Version
29.0–31.0

Signature
public static Void setTestSearchFeedItemsInFeed(String communityId, ConnectApi.FeedType
feedType, String subjectId, Integer recentCommentCount, ConnectApi.FeedDensity density,
String pageParam, Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q,
Boolean showInternalOnly, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessages, Filter,
Landing, and Streams.

1117
Apex Reference Guide ChatterFeeds Class

subjectId
Type: String
If feedType is Record, subjectId can be any record ID, including a group ID. If feedType is Streams, subjectId
must be a stream ID. If feedType is Topics, subjectId must be a topic ID. If feedType is UserProfile, subjectId
can be any user ID. If the feedType is any other value, subjectId must be the ID of the context user or the alias me.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
showInternalOnly
Type: Boolean

1118
Apex Reference Guide ChatterFeeds Class

Specifies whether to show only feed items from internal (non-Experience Cloud site) users (true), or not (false). The default
value is false.
result
Type: ConnectApi.FeedItemPage
Object containing test data.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFeed(communityId, feedType, subjectId, recentCommentCount, density, pageParam, pageSize, sortParam, q,
showInternalOnly)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, q,


result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFilterFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItemsInFilterFeed(String communityId, String
subjectId, String keyPrefix, String q, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
q
Type: String

1119
Apex Reference Guide ChatterFeeds Class

Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Specify the test feed item page.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchFeedItemsInFilterFeed(communityId, feedType, subjectId,


keyPrefix, pageParam, pageSize, sortParam, q, result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFilterFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
28.0–31.0

Signature
public static Void setTestSearchFeedItemsInFilterFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String keyPrefix, String pageParam,
Integer pageSize, ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedItemPage
result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String

1120
Apex Reference Guide ChatterFeeds Class

A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Specify the test feed item page.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, pageParam, pageSize, sortParam, q)
Apex Developer Guide: Testing ConnectApi Code

1121
Apex Reference Guide ChatterFeeds Class

setTestSearchFeedItemsInFilterFeed(communityId, feedType, subjectId,


keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam, q,
result)
Register a ConnectApi.FeedItemPage object to be returned when the matching
ConnectApi.searchFeedItemsInFilterFeed method is called in a test context. Use the method with the same parameters
or you receive an exception.

API Version
29.0–31.0

Signature
public static Void setTestSearchFeedItemsInFilterFeed(String communityId,
ConnectApi.FeedType feedType, String subjectId, String keyPrefix, Integer
recentCommentCount, ConnectApi.FeedDensity density, String pageParam, Integer pageSize,
ConnectApi.FeedSortOrder sortParam, String q, ConnectApi.FeedItemPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
feedType
Type: ConnectApi.FeedType
Type of feed. Valid values include every ConnectApi.FeedType except Company, DirectMessageModeration,
DirectMessages, Filter, Home, Isolated, Landing, Moderation, and PendingReview.
subjectId
Type: String
ID of the context user or the alias me.
keyPrefix
Type: String
A key prefix that specifies record type. A key prefix is the first three characters in the object ID, which specifies the object type. For
example, User objects have a prefix of 005 and Group objects have a prefix of 0F9.
recentCommentCount
Type: Integer
Maximum number of comments to return with each feed item. The default value is 3.
density
Type: ConnectApi.FeedDensity
Specify the amount of content in a feed.
• AllUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also displays
custom recommendations.
• FewerUpdates—Displays all updates from people and records the user follows and groups the user is a member of. Also
displays custom recommendations, but hides some system-generated updates from records.

1122
Apex Reference Guide ChatterGroups Class

pageParam
Type: String
Page token to use to view the page. Page tokens are returned as part of the response class, for example, currentPageToken
or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Number of feed items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
sortParam
Type: ConnectApi.FeedSortOrder
Values are:
• CreatedDateAsc—Sorts by oldest creation date. This sort order is available only for DirectMessageModeration,
Draft, Isolated, Moderation, and PendingReview feeds.
• CreatedDateDesc—Sorts by most recent creation date.
• LastModifiedDateDesc—Sorts by most recent activity.
• MostViewed—Sorts by most viewed content. This sort order is available only for Home feeds when the
ConnectApi.FeedFilter is UnansweredQuestions.
• Relevance—Sorts by most relevant content. This sort order is available only for Company, Home, and Topics feeds.
Sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. If you pass in null,
the default value CreatedDateDesc is used.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.
result
Type: ConnectApi.FeedItemPage
Specify the test feed item page.

Return Value
Type: Void

SEE ALSO:
searchFeedItemsInFilterFeed(communityId, subjectId, keyPrefix, recentCommentCount, density, pageParam, pageSize, sortParam,
q)
Apex Developer Guide: Testing ConnectApi Code

ChatterGroups Class
Information about groups, such as the group’s members, photo, and the groups the specified user is a member of. Add members to a
group, remove members, and change the group photo.

1123
Apex Reference Guide ChatterGroups Class

Namespace
ConnectApi

ChatterGroups Methods
These methods are for ChatterGroups. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

IN THIS SECTION:
addMember(communityId, groupId, userId)
Add a user to a group as a standard member.
addMemberWithRole(communityId, groupId, userId, role)
Add a user with a role to a group.
addRecord(communityId, groupId, recordId)
Associate a record with a group.
createGroup(communityId, groupInput)
Create a group.
deleteBannerPhoto(communityId, groupId)
Delete the group banner photo.
deleteGroup(communityId, groupId)
Delete a group.
deleteMember(communityId, membershipId)
Remove a member from a group.
deletePhoto(communityId, groupId)
Delete the group photo.
getAnnouncements(communityId, groupId)
Get the first page of announcements in a group.
getAnnouncements(communityId, groupId, pageParam, pageSize)
Get a page of announcements in a group.
getBannerPhoto(communityId, groupId)
Get the group banner photo.
getGroup(communityId, groupId)
Get information about a group.
getGroupBatch(communityId, groupIds)
Get information about a list of groups.
getGroupMembershipRequest(communityId, requestId)
Get information about a request to join a private group.
getGroupMembershipRequests(communityId, groupId)
Get information about every request to join a private group.

1124
Apex Reference Guide ChatterGroups Class

getGroupMembershipRequests(communityId, groupId, status)


Get information about every request to join a private group that has a specified status.
getGroups(communityId)
Get the first page of groups.
getGroups(communityId, pageParam, pageSize)
Get a page of groups.
getGroups(communityId, pageParam, pageSize, archiveStatus)
Get a page of groups with an archive status.
getMember(communityId, membershipId)
Get information about a group member.
getMembers(communityId, groupId)
Get the first page of information about the members of a group.
getMembers(communityId, groupId, pageParam, pageSize)
Get a page of information about the members of a group.
getMembershipBatch(communityId, membershipIds)
Get information about a list of group memberships.
getMyChatterSettings(communityId, groupId)
Get the context user’s Chatter settings for a group.
getPhoto(communityId, groupId)
Get the photo for a group.
getRecord(communityId, groupRecordId)
Get a record associated with a group.
getRecords(communityId, groupId)
Get the first page of records associated with a group.
getRecords(communityId, groupId, pageParam, pageSize)
Get a page of records associated with a group.
inviteUsers(groupId, invite)
Invite internal and external users to join a group.
postAnnouncement(communityId, groupId, announcement)
Post an announcement to a group.
removeRecord(communityId, groupRecordId)
Remove the association of a record with a group.
requestGroupMembership(communityId, groupId)
Request membership in a private group.
searchGroups(communityId, q)
Get the first page of groups that match the search criteria.
searchGroups(communityId, q, pageParam, pageSize)
Get a page of groups that match the search criteria.
searchGroups(communityId, q, archiveStatus, pageParam, pageSize)
Get a page of groups with the archive status that match the search criteria.

1125
Apex Reference Guide ChatterGroups Class

setBannerPhoto(communityId, groupId, fileId, versionNumber)


Set an uploaded file as the group banner photo.
setBannerPhoto(communityId, groupId, fileUpload)
Set a file that hasn’t been uploaded as the group banner photo.
setBannerPhotoWithAttributes(communityId, groupId, bannerPhoto)
Set and crop an uploaded file as the group banner photo.
setBannerPhotoWithAttributes(communityId, groupId, bannerPhoto, fileUpload)
Set and crop a file that hasn’t been uploaded as the group banner photo.
setPhoto(communityId, groupId, fileId, versionNumber)
Set an uploaded file as the group photo.
setPhoto(communityId, groupId, fileUpload)
Set a file that hasn’t been uploaded as the group photo.
setPhotoWithAttributes(communityId, groupId, photo)
Set and crop an uploaded file as the group photo.
setPhotoWithAttributes(communityId, groupId, photo, fileUpload)
Set and crop a file that hasn’t been uploaded as the group photo.
updateGroup(communityId, groupId, groupInput)
Update the settings of a group.
updateGroupMember(communityId, membershipId, role)
Update the role of a group member.
updateMyChatterSettings(communityId, groupId, emailFrequency)
Update the context user’s email frequency for a group.
updateRequestStatus(communityId, requestId, status)
Update a request to join a private group.
updateRequestStatus(communityId, requestId, status, responseMessage)
Update a request to join a private group and optionally provide a message when the request is denied.

addMember(communityId, groupId, userId)


Add a user to a group as a standard member.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMember addMember(String communityId, String groupId,
String userId)

1126
Apex Reference Guide ChatterGroups Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
userId
Type: String
ID for a user.

Return Value
Type: ConnectApi.GroupMember

Usage
To execute this method, the context user must be the group owner or moderator.

addMemberWithRole(communityId, groupId, userId, role)


Add a user with a role to a group.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMember addMemberWithRole(String communityId, String
groupId, String userId, ConnectApi.GroupMembershipType role)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
userId
Type: String

1127
Apex Reference Guide ChatterGroups Class

ID for a user.
role
Type: ConnectApi.GroupMembershipType
The group membership type. One of these values:
• GroupManager
• StandardMember

Return Value
Type: ConnectApi.GroupMember

Usage
To execute this method, the context user must be the group owner or moderator.

addRecord(communityId, groupId, recordId)


Associate a record with a group.

API Version
34.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupRecord addRecord(String communityId, String groupId,
String recordId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID of the group with which to associate the record.
recordId
Type: String
ID of the record to associate with the group.

Return Value
Type: ConnectApi.GroupRecord

1128
Apex Reference Guide ChatterGroups Class

createGroup(communityId, groupInput)
Create a group.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupDetail createGroup(String, communityId,
ConnectApi.ChatterGroupInput groupInput)

Parameters
communityId
Type: String,
ID for an Experience Cloud site, internal, or null.
groupInput
Type: ConnectApi.ChatterGroupInput
The properties of the group.

Return Value
Type: ConnectApi.ChatterGroupDetail

deleteBannerPhoto(communityId, groupId)
Delete the group banner photo.

API Version
36.0

Requires Chatter
Yes

Signature
public static Void deleteBannerPhoto(String communityId, String groupId)

Parameters
communityId
Type: String

1129
Apex Reference Guide ChatterGroups Class

ID for an Experience Cloud site, internal, or null.


groupId
Type: String
ID of the group.

Return Value
Type: Void

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

deleteGroup(communityId, groupId)
Delete a group.

API Version
29.0

Requires Chatter
Yes

Signature
public static Void deleteGroup(String communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: Void

deleteMember(communityId, membershipId)
Remove a member from a group.

API Version
28.0

1130
Apex Reference Guide ChatterGroups Class

Requires Chatter
Yes

Signature
public static Void deleteMember(String communityId, String membershipId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
membershipId
Type: String
ID for a membership.

Return Value
Type: Void

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

deletePhoto(communityId, groupId)
Delete the group photo.

API Version
28.0

Requires Chatter
Yes

Signature
public static Void deletePhoto(String communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

1131
Apex Reference Guide ChatterGroups Class

Return Value
Type: Void

Usage
This method is only successful when the context user is the group manager or owner, or has Modify All Data permission.

getAnnouncements(communityId, groupId)
Get the first page of announcements in a group.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.AnnouncementPage getAnnouncements(String communityId, String
groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.AnnouncementPage

Usage
To post an announcement, get information about an announcement, update the expiration date of an announcement, or delete an
announcement, use the methods of the ConnectApi.Announcements class.

getAnnouncements(communityId, groupId, pageParam, pageSize)


Get a page of announcements in a group.

API Version
31.0

1132
Apex Reference Guide ChatterGroups Class

Requires Chatter
Yes

Signature
public static ConnectApi.AnnouncementPage getAnnouncements(String communityId, String
groupId, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.AnnouncementPage

Usage
To post an announcement, get information about an announcement, update the expiration date of an announcement, or delete an
announcement, use the methods of the ConnectApi.Announcements class.

getBannerPhoto(communityId, groupId)
Get the group banner photo.

API Version
36.0

Requires Chatter
Yes

Signature
public static ConnectApi.BannerPhoto getBannerPhoto(String communityId, String groupId)

1133
Apex Reference Guide ChatterGroups Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
The ID of the group.

Return Value
Type: ConnectApi.BannerPhoto

getGroup(communityId, groupId)
Get information about a group.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupDetail getGroup(String communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.ChatterGroupDetail

getGroupBatch(communityId, groupIds)
Get information about a list of groups.

1134
Apex Reference Guide ChatterGroups Class

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] getGroupBatch(String communityId, List<String>
groupIds)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupIds
Type: List<String>
A list of up to 500 group IDs.

Return Value
Type: ConnectApi.BatchResult[]
The ConnectApi.BatchResult.getResult() method returns a ConnectApi.ChatterGroup object and errors
embedded in the results for groups that didn’t load.

Example
// Create a list of groups.
ConnectApi.ChatterGroupPage groupPage = ConnectApi.ChatterGroups.getGroups(null);

// Create a list of group IDs.


List<String> groupIds = new List<String>();
for (ConnectApi.ChatterGroup aGroup : groupPage.groups){
groupIds.add(aGroup.id);
}

// Get info about all the groups in the list.


ConnectApi.BatchResult[] batchResults = ConnectApi.ChatterGroups.getGroupBatch(null,
groupIds);

for (ConnectApi.BatchResult batchResult : batchResults) {


if (batchResult.isSuccess()) {
// Operation was successful.
// Print the number of members in each group.
ConnectApi.ChatterGroup aGroup;
if(batchResult.getResult() instanceof ConnectApi.ChatterGroup) {
aGroup = (ConnectApi.ChatterGroup) batchResult.getResult();
}

1135
Apex Reference Guide ChatterGroups Class

System.debug('SUCCESS');
System.debug(aGroup.memberCount);
}
else {
// Operation failed. Print errors.
System.debug('FAILURE');
System.debug(batchResult.getErrorMessage());
}
}

SEE ALSO:
getMembershipBatch(communityId, membershipIds)

getGroupMembershipRequest(communityId, requestId)
Get information about a request to join a private group.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMembershipRequest getGroupMembershipRequest(String
communityId, String requestId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
requestId
Type: String
The ID of a request to join a private group.

Return Value
Type: ConnectApi.GroupMembershipRequest

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

1136
Apex Reference Guide ChatterGroups Class

getGroupMembershipRequests(communityId, groupId)
Get information about every request to join a private group.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMembershipRequests getGroupMembershipRequests(String
communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.GroupMembershipRequests

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

getGroupMembershipRequests(communityId, groupId, status)


Get information about every request to join a private group that has a specified status.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMembershipRequests getGroupMembershipRequests(String
communityId, String groupId, ConnectApi.GroupMembershipRequestStatus status)

1137
Apex Reference Guide ChatterGroups Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
status
Type: ConnectApi.GroupMembershipRequestStatus
status—Status of a request to join a private group.
• Accepted
• Declined
• Pending

Return Value
Type: ConnectApi.GroupMembershipRequests

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

getGroups(communityId)
Get the first page of groups.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupPage getGroups(String communityId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

1138
Apex Reference Guide ChatterGroups Class

Return Value
Type: ConnectApi.ChatterGroupPage

getGroups(communityId, pageParam, pageSize)


Get a page of groups.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupPage getGroups(String communityId, Integer
pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterGroupPage

getGroups(communityId, pageParam, pageSize, archiveStatus)


Get a page of groups with an archive status.

API Version
29.0

1139
Apex Reference Guide ChatterGroups Class

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupPage getGroups(String communityId, Integer
pageParam, Integer pageSize, ConnectApi.GroupArchiveStatus archiveStatus)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
archiveStatus
Type: ConnectApi.GroupArchiveStatus
Archive status of groups.
• All—All groups, including groups that are archived and groups that aren’t archived.
• Archived—Groups that are archived.
• NotArchived—Groups that aren’t archived.
If you pass in null, the default value is All.

Return Value
Type: ConnectApi.ChatterGroupPage

getMember(communityId, membershipId)
Get information about a group member.

API Version
28.0

Requires Chatter
Yes

1140
Apex Reference Guide ChatterGroups Class

Signature
public static ConnectApi.GroupMember getMember(String communityId, String membershipId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
membershipId
Type: String
ID for a membership.

Return Value
Type: ConnectApi.GroupMember

getMembers(communityId, groupId)
Get the first page of information about the members of a group.

API Version
28.0

Available to Guest Users


36.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMemberPage getMembers(String communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.GroupMemberPage

1141
Apex Reference Guide ChatterGroups Class

getMembers(communityId, groupId, pageParam, pageSize)


Get a page of information about the members of a group.

API Version
28.0

Available to Guest Users


36.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMemberPage getMembers(String communityId, String groupId,
Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.GroupMemberPage

getMembershipBatch(communityId, membershipIds)
Get information about a list of group memberships.

API Version
31.0

1142
Apex Reference Guide ChatterGroups Class

Requires Chatter
Yes

Signature
public static ConnectApi.BatchResult[] getMembershipBatch(String communityId,
List<String> membershipIds)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
membershipIds
Type: List<String>
A list of up to 500 group membership IDs.

Return Value
Type: ConnectApi.BatchResult[]
The ConnectApi.BatchResult.getResult() method returns a ConnectApi.GroupMember object and errors
embedded in the results for group memberships that didn’t load.

Example
// Get members of a group.
ConnectApi.GroupMemberPage membersPage = ConnectApi.ChatterGroups.getMembers(null,
'0F9D00000000oOT');

// Create a list of membership IDs.


List<String> membersList = new List<String>();
for (ConnectApi.GroupMember groupMember : membersPage.members){
membersList.add(groupMember.id);
}

// Get info about all group memberships in the list.


ConnectApi.BatchResult[] batchResults = ConnectApi.ChatterGroups.getMembershipBatch(null,
membersList);

for (ConnectApi.BatchResult batchResult : batchResults) {


if (batchResult.isSuccess()) {
// Operation was successful.
// Print the first name of each member.
ConnectApi.GroupMember groupMember;
if(batchResult.getResult() instanceof ConnectApi.GroupMember) {
groupMember = (ConnectApi.GroupMember) batchResult.getResult();
}
System.debug('SUCCESS');
System.debug(groupMember.user.firstName);
}

1143
Apex Reference Guide ChatterGroups Class

else {
// Operation failed. Print errors.
System.debug('FAILURE');
System.debug(batchResult.getErrorMessage());
}
}

SEE ALSO:
getGroupBatch(communityId, groupIds)

getMyChatterSettings(communityId, groupId)
Get the context user’s Chatter settings for a group.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupChatterSettings getMyChatterSettings(String communityId,
String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.GroupChatterSettings

getPhoto(communityId, groupId)
Get the photo for a group.

API Version
28.0

1144
Apex Reference Guide ChatterGroups Class

Requires Chatter
Yes

Signature
public static ConnectApi.Photo getPhoto(String communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.Photo

getRecord(communityId, groupRecordId)
Get a record associated with a group.

API Version
34.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupRecord getRecord(String communityId, String groupRecordId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupRecordId
Type: String
ID of the group record.

Return Value
Type: ConnectApi.GroupRecord

1145
Apex Reference Guide ChatterGroups Class

getRecords(communityId, groupId)
Get the first page of records associated with a group.

API Version
33.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupRecordPage getRecords(String communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

Return Value
Type: ConnectApi.GroupRecordPage

getRecords(communityId, groupId, pageParam, pageSize)


Get a page of records associated with a group.

API Version
33.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupRecordPage getRecords(String communityId, String groupId,
Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String

1146
Apex Reference Guide ChatterGroups Class

ID for an Experience Cloud site, internal, or null.


groupId
Type: String
ID for a group.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.GroupRecordPage

inviteUsers(groupId, invite)
Invite internal and external users to join a group.

API Version
39.0

Requires Chatter
Yes

Signature
public static ConnectApi.Invitations inviteUsers(String groupId, ConnectApi.InviteInput
invite)

Parameters
groupId
Type: String
ID of the group.
invite
Type: ConnectApi.InviteInput
A ConnectApi.InviteInput body.

Return Value
Type: ConnectApi.Invitations

1147
Apex Reference Guide ChatterGroups Class

postAnnouncement(communityId, groupId, announcement)


Post an announcement to a group.

API Version
31.0

Requires Chatter
Yes

Signature
public static ConnectApi.Announcement postAnnouncement(String communityId, String
groupId, ConnectApi.AnnouncementInput announcement)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
announcement
Type: ConnectApi.AnnouncementInput
A ConnectApi.AnnouncementInput object.

Return Value
Type: ConnectApi.Announcement

Usage
Use an announcement to highlight information. Users can discuss, like, and post comments on announcements. Deleting the feed post
deletes the announcement.
To post an announcement, get information about an announcement, update the expiration date of an announcement, or delete an
announcement, use the methods of the ConnectApi.Announcements class.

removeRecord(communityId, groupRecordId)
Remove the association of a record with a group.

API Version
34.0

1148
Apex Reference Guide ChatterGroups Class

Requires Chatter
Yes

Signature
public static Void removeRecord(String communityId, String groupRecordId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupRecordId
Type: String
ID of the group record.

Return Value
Type: Void

requestGroupMembership(communityId, groupId)
Request membership in a private group.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMembershipRequest requestGroupMembership(String
communityId, String groupId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.

1149
Apex Reference Guide ChatterGroups Class

Return Value
Type: ConnectApi.GroupMembershipRequest

Sample: Requesting to Join a Private Group


This sample code calls ConnectApi.ChatterGroups.requestGroupMembership to request to join a private group.
String communityId = null;
ID groupId = '0F9x00000000hAZ';

ConnectApi.GroupMembershipRequest membershipRequest =
ConnectApi.ChatterGroups.requestGroupMembership(communityId, groupId);

searchGroups(communityId, q)
Get the first page of groups that match the search criteria.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupPage searchGroups(String communityId, String q)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Specifies the string to search. The search string must contain at least two characters, not including wildcards. See Wildcards. Can be
specified as null.

Return Value
Type: ConnectApi.ChatterGroupPage

1150
Apex Reference Guide ChatterGroups Class

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchGroups(communityId, q, result)
Apex Developer Guide: Testing ConnectApi Code

searchGroups(communityId, q, pageParam, pageSize)


Get a page of groups that match the search criteria.

API Version
28.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupPage searchGroups(String communityId, String q,
Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Specifies the string to search. The search string must contain at least two characters, not including wildcards. See Wildcards. Can be
specified as null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

1151
Apex Reference Guide ChatterGroups Class

Return Value
Type: ConnectApi.ChatterGroupPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchGroups(communityId, q, pageParam, pageSize, result)
Apex Developer Guide: Testing ConnectApi Code

searchGroups(communityId, q, archiveStatus, pageParam, pageSize)


Get a page of groups with the archive status that match the search criteria.

API Version
29.0

Available to Guest Users


31.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterGroupPage searchGroups(String communityId, String q,
ConnectApi.GroupArchiveStatus archiveStatus, Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Specifies the string to search. The search string must contain at least two characters, not including wildcards. See Wildcards. Can be
specified as null.
archiveStatus
Type: ConnectApi.GroupArchiveStatus
Archive status of groups.
• All—All groups, including groups that are archived and groups that aren’t archived.
• Archived—Groups that are archived.

1152
Apex Reference Guide ChatterGroups Class

• NotArchived—Groups that aren’t archived.


pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterGroupPage

Usage
To test code that uses this method, use the matching set test method (prefix the method name with setTest). Use the set test method
with the same parameters or the code throws an exception.

SEE ALSO:
setTestSearchGroups(communityId, q, archiveStatus, pageParam, pageSize, result)
Apex Developer Guide: Testing ConnectApi Code

setBannerPhoto(communityId, groupId, fileId, versionNumber)


Set an uploaded file as the group banner photo.

API Version
36.0

Requires Chatter
Yes

Signature
public static ConnectApi.BannerPhoto setBannerPhoto(String communityId, String groupId,
String fileId, Integer versionNumber)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
The ID of the group.

1153
Apex Reference Guide ChatterGroups Class

fileId
Type: String
The ID of the already uploaded file. The key prefix must be 069, and the image must be smaller than 8 MB.
versionNumber
Type: Integer
Version number of the existing file. Specify either an existing version number or, to get the latest version, specify null.

Return Value
Type: ConnectApi.BannerPhoto

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

setBannerPhoto(communityId, groupId, fileUpload)


Set a file that hasn’t been uploaded as the group banner photo.

API Version
36.0

Requires Chatter
Yes

Signature
public static ConnectApi.BannerPhoto setBannerPhoto(String communityId, String groupId,
ConnectApi.BinaryInput fileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
The ID of the group.
fileUpload
Type: ConnectApi.BinaryInput
File to use as the photo. The content type must be usable as an image.

1154
Apex Reference Guide ChatterGroups Class

Return Value
Type: ConnectApi.BannerPhoto

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

setBannerPhotoWithAttributes(communityId, groupId, bannerPhoto)


Set and crop an uploaded file as the group banner photo.

API Version
36.0

Requires Chatter
Yes

Signature
public static ConnectApi.BannerPhoto setBannerPhotoWithAttributes(String communityId,
String groupId, ConnectApi.BannerPhotoInput bannerPhoto)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
The ID of the group.
bannerPhoto
Type: ConnectApi.BannerPhotoInput
A ConnectApi.BannerPhotoInput object that specifies the ID and version of the file, and how to crop the file.

Return Value
Type: ConnectApi.BannerPhoto

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

1155
Apex Reference Guide ChatterGroups Class

setBannerPhotoWithAttributes(communityId, groupId, bannerPhoto, fileUpload)


Set and crop a file that hasn’t been uploaded as the group banner photo.

API Version
36.0

Requires Chatter
Yes

Signature
public static ConnectApi.BannerPhoto setBannerPhotoWithAttributes(String communityId,
String groupId, ConnectApi.BannerPhotoInput bannerPhoto, ConnectApi.BinaryInput
fileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
The ID of the group.
bannerPhoto
Type: ConnectApi.BannerPhotoInput
A ConnectApi.BannerPhotoInput object specifying the cropping parameters.
fileUpload
Type: ConnectApi.BinaryInput
File to use as the photo. The content type must be usable as an image.

Return Value
Type: ConnectApi.BannerPhoto

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

setPhoto(communityId, groupId, fileId, versionNumber)


Set an uploaded file as the group photo.

1156
Apex Reference Guide ChatterGroups Class

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.Photo setPhoto(String communityId, String groupId, String
fileId, Integer versionNumber)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
fileId
Type: String
ID of a file already uploaded. The key prefix must be 069, and the file must be an image that is smaller than 2 GB.
versionNumber
Type: Integer
Version number of the existing file. Specify either an existing version number or, to get the latest version, specify null.

Return Value
Type: ConnectApi.Photo

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

Sample: Updating a Group Photo with an Existing File


When a group is created, it doesn’t have a group photo. You can set an existing photo that has already been uploaded to Salesforce as
the group photo. The key prefix must be 069 and the file size must be less than 2 GB.
String communityId = null;
ID groupId = '0F9x00000000hAK';
ID fileId = '069x00000001Ion';

// Set photo
ConnectApi.Photo photo = ConnectApi.ChatterGroups.setPhoto(communityId, groupId, fileId,
null);

1157
Apex Reference Guide ChatterGroups Class

setPhoto(communityId, groupId, fileUpload)


Set a file that hasn’t been uploaded as the group photo.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.Photo setPhoto(String communityId, String groupId,
ConnectApi.BinaryInput fileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
fileUpload
Type: ConnectApi.BinaryInput
File to use as the photo. The content type must be usable as an image.

Return Value
Type: ConnectApi.Photo

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

Sample: Uploading a New File and Using It as a Group Photo


When a group is created, it doesn’t have a group photo. You can upload a photo and set it as the group photo.
String communityId = null;
ID groupId = '0F9x00000000hAP';
ID photoId = '069x00000001Ioo';

// Set photo
List<ContentVersion> groupPhoto = [Select c.VersionData From ContentVersion c where
ContentDocumentId=:photoId];
ConnectApi.BinaryInput binary = new ConnectApi.BinaryInput(groupPhoto.get(0).VersionData,

1158
Apex Reference Guide ChatterGroups Class

'image/png', 'image.png');
ConnectApi.Photo photo = ConnectApi.ChatterGroups.setPhoto(communityId, groupId, binary);

setPhotoWithAttributes(communityId, groupId, photo)


Set and crop an uploaded file as the group photo.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.Photo setPhotoWithAttributes(String communityId, String groupId,
ConnectApi.PhotoInput photo)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
photo
Type: ConnectApi.PhotoInput
A ConnectApi.PhotoInput object that specifies the ID and version of the file, and how to crop the file.

Return Value
Type: ConnectApi.Photo

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

setPhotoWithAttributes(communityId, groupId, photo, fileUpload)


Set and crop a file that hasn’t been uploaded as the group photo.

1159
Apex Reference Guide ChatterGroups Class

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.Photo setPhotoWithAttributes(String communityId, String groupId,
ConnectApi.PhotoInput photo, ConnectApi.BinaryInput fileUpload)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
photo
Type: ConnectApi.PhotoInput
A ConnectApi.PhotoInput object that specifies how to crop the file specified in fileUpload.
fileUpload
Type: ConnectApi.BinaryInput
File to use as the photo. The content type must be usable as an image.

Return Value
Type: ConnectApi.Photo

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.
Photos are processed asynchronously and might not be visible right away.

updateGroup(communityId, groupId, groupInput)


Update the settings of a group.

API Version
28.0

Requires Chatter
Yes

1160
Apex Reference Guide ChatterGroups Class

Signature
public static ConnectApi.ChatterGroup updateGroup(String communityId, String groupId,
ConnectApi.ChatterGroupInput groupInput)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
groupId
Type: String
ID for a group.
groupInput
Type: ConnectApi.ChatterGroupInput
A ConnectApi.ChatterGroupInput object.

Return Value
Type: ConnectApi.ChatterGroup

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission. Use this method
to update any settings in the ConnectApi.ChatterGroupInput class. These settings include the group title and text in the
“Information” section, whether the group is public or private, and whether the group is archived.

Example
This example archives a group.
String groupId = '0F9D00000000qSz';
String communityId = null;

ConnectApi.ChatterGroupInput groupInput = new ConnectApi.ChatterGroupInput();


groupInput.isArchived = true;

ConnectApi.ChatterGroups.updateGroup(communityId, groupId, groupInput);

updateGroupMember(communityId, membershipId, role)


Update the role of a group member.

API Version
29.0

Requires Chatter
Yes

1161
Apex Reference Guide ChatterGroups Class

Signature
public static ConnectApi.ChatterGroup updateGroupMember(String communityId, String
membershipId, ConnectApi.GroupMembershipType role)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
membershipId
Type: String
ID for a membership.
role
Type: ConnectApi.GroupMembershipType
The group membership type. One of these values:
• GroupManager
• StandardMember

Return Value
Type: ConnectApi.ChatterGroup

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

updateMyChatterSettings(communityId, groupId, emailFrequency)


Update the context user’s email frequency for a group.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupChatterSettings updateMyChatterSettings(String communityId,
String groupId, ConnectApi.GroupEmailFrequency emailFrequency)

Parameters
communityId
Type: String

1162
Apex Reference Guide ChatterGroups Class

ID for an Experience Cloud site, internal, or null.


groupId
Type: String
ID for a group.
emailFrequency
Type: ConnectApi.GroupEmailFrequency
Frequency with which a user receives email.
• EachPost
• DailyDigest
• WeeklyDigest
• Never
• UseDefault
The value UseDefault uses the value set in a call to updateChatterSettings(communityId, userId,
defaultGroupEmailFrequency).

Return Value
Type: ConnectApi.GroupChatterSettings

updateRequestStatus(communityId, requestId, status)


Update a request to join a private group.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMembershipRequest updateRequestStatus(String communityId,
String requestId, ConnectApi.GroupMembershipRequestStatus status)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
requestId
Type: String
ID for a request to join a private group.
status
Type: ConnectApi.GroupMembershipRequestStatus

1163
Apex Reference Guide ChatterGroups Class

Status of the request:


• Accepted
• Declined
The Pending value of the enum is not valid in this method.

Return Value
Type: ConnectApi.GroupMembershipRequest

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

Sample: Accepting or Declining a Request to Join a Private Group


This sample code calls ConnectApi.ChatterGroups.updateRequestStatus and passes it the membership request ID
and an ConnectApi.GroupMembershipRequestStatus.Accepted status. You can also pass
ConnectApi.GroupMembershipRequestStatus.Declined.

String communityId = null;


ID groupId = '0F9x00000000hAZ';
String requestId = '0I5x000000001snCAA';

ConnectApi.GroupMembershipRequest membershipRequestRep =
ConnectApi.ChatterGroups.updateRequestStatus(communityId, requestId,
ConnectApi.GroupMembershipRequestStatus.Accepted);

updateRequestStatus(communityId, requestId, status, responseMessage)


Update a request to join a private group and optionally provide a message when the request is denied.

API Version
35.0

Requires Chatter
Yes

Signature
public static ConnectApi.GroupMembershipRequest updateRequestStatus(String communityId,
String requestId, ConnectApi.GroupMembershipRequestStatus status, String responseMessage)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.

1164
Apex Reference Guide ChatterGroups Class

requestId
Type: String
ID for a request to join a private group.
status
Type: ConnectApi.GroupMembershipRequestStatus
Status of the request:
• Accepted
• Declined
The Pending value of the enum is not valid in this method.
responseMessage
Type: String
Provide a message to the user if their membership request is declined. The value of this property is used only when the value of the
status property is Declined.
The maximum length is 756 characters.

Return Value
Type: ConnectApi.GroupMembershipRequest

Usage
This method is successful only when the context user is the group manager or owner, or has Modify All Data permission.

ChatterGroups Test Methods


These test methods are for ChatterGroups. All methods are static.
For information about using these methods to test your ConnectApi code, see Testing ConnectApi Code.

setTestSearchGroups(communityId, q, result)
Register a ConnectApi.ChatterGroupPage object to be returned when the matching ConnectApi.searchGroups
method is called in a test context. Use the test method with the same parameters or you receive an exception.

API Version
29.0

Signature
public static Void setTestSearchGroups(String communityId, String q,
ConnectApi.ChatterGroupPage result)

Parameters
communityId
Type: String

1165
Apex Reference Guide ChatterGroups Class

ID for an Experience Cloud site, internal, or null.


q
Type: String
Specifies the string to search. The search string must contain at least two characters, not including wildcards. See Wildcards. Can be
specified as null.
result
Type: ConnectApi.ChatterGroupPage
Test ConnectApi.ChatterGroupPage object.

Return Value
Type: Void

SEE ALSO:
searchGroups(communityId, q)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchGroups(communityId, q, pageParam, pageSize, result)


Register a ConnectApi.ChatterGroupPage object to be returned when the matching ConnectApi.searchGroups
method is called in a test context. Use the test method with the same parameters or you receive an exception.

API Version
28.0

Signature
public static Void setTestSearchGroups(String communityId, String q, Integer pageParam,
Integer pageSize, ConnectApi.ChatterGroupPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Specifies the string to search. The search string must contain at least two characters, not including wildcards. See Wildcards. Can be
specified as null.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer

1166
Apex Reference Guide ChatterGroups Class

Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
result
Type: ConnectApi.ChatterGroupPage
Test ConnectApi.ChatterGroupPage object.

Return Value
Type: Void

SEE ALSO:
searchGroups(communityId, q, pageParam, pageSize)
Apex Developer Guide: Testing ConnectApi Code

setTestSearchGroups(communityId, q, archiveStatus, pageParam, pageSize,


result)
Register a ConnectApi.ChatterGroupPage object to be returned when the matching ConnectApi.searchGroups
method is called in a test context. Use the test method with the same parameters or you receive an exception.

API Version
29.0

Signature
public static Void setTestSearchGroups(String communityId, String q,
ConnectApi.GroupArchiveStatus, archiveStatus, Integer pageParam, Integer pageSize,
ConnectApi.ChatterGroupPage result)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Specifies the string to search. The search string must contain at least two characters, not including wildcards. See Wildcards. Can be
specified as null.
archiveStatus
Type: ConnectApi.GroupArchiveStatus
Archive status of groups.
• All—All groups, including groups that are archived and groups that aren’t archived.
• Archived—Groups that are archived.
• NotArchived—Groups that aren’t archived.

1167
Apex Reference Guide ChatterMessages Class

pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
result
Type: ConnectApi.ChatterGroupPage
Test ConnectApi.ChatterGroupPage object.

Return Value
Type: Void

SEE ALSO:
searchGroups(communityId, q, archiveStatus, pageParam, pageSize)
Apex Developer Guide: Testing ConnectApi Code

ChatterMessages Class
Get, send, search, and reply to private messages. You can also get and search private conversations, mark conversations as read, and get
a count of unread private messages.

Namespace
ConnectApi

Usage
Private messages and direct messages are different features. Direct messages are newer and offer a richer feature set for private
communication in Experience Cloud sites. Direct messages are a capability within Chatter feeds. To work with direct messages, use the
ChatterFeeds Class.

ChatterMessages Methods
These methods are for ChatterMessages. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

IN THIS SECTION:
getConversation(conversationId)
Get a conversation.
getConversation(conversationId, pageParam, pageSize)
Get a page of a conversation.

1168
Apex Reference Guide ChatterMessages Class

getConversation(communityId, conversationId)
Get a conversation from an Experience Cloud site.
getConversation(communityId, conversationId, pageParam, pageSize)
Get a page of a conversation from an Experience Cloud site.
getConversations()
Get the most recent conversations.
getConversations(pageParam, pageSize)
Get a page of conversations.
getConversations(communityId)
Get the most recent conversations from an Experience Cloud site.
getConversations(communityId, pageParam, pageSize)
Get a page of conversations from an Experience Cloud site.
getMessage(messageId)
Get a message.
getMessage(communityId, messageId)
Get a message from an Experience Cloud site.
getMessages()
Get the most recent messages.
getMessages(pageParam, pageSize)
Get a page of messages.
getMessages(communityId)
Get the most recent messages from an Experience Cloud site.
getMessages(communityId, pageParam, pageSize)
Get a page of messages from an Experience Cloud site.
getUnreadCount()
Get the number of conversations that are marked unread.
getUnreadCount(communityId)
Get the number of conversations that are marked unread in an Experience Cloud site.
markConversationRead(conversationId, read)
Mark a conversation as read or unread.
markConversationRead(communityId, conversationID, read)
Mark a conversation as read or unread in an Experience Cloud site.
replyToMessage(text, inReplyTo)
Reply to a message.
replyToMessage(communityId, text, inReplyTo)
Reply to a message in an Experience Cloud site.
searchConversation(conversationId, q)
Get a conversation that matches the search criteria.
searchConversation(conversationId, pageParam, pageSize, q)
Get a conversation with a page of messages that match the search criteria.

1169
Apex Reference Guide ChatterMessages Class

searchConversation(communityId, conversationId, q)
Get a conversation with messages that match the search criteria in an Experience Cloud site.
searchConversation(communityId, conversationId, pageParam, pageSize, q)
Get a conversation with a page of messages that match the search criteria in an Experience Cloud site.
searchConversations(q)
Get conversations in which member names and messages match the search criteria.
searchConversations(pageParam, pageSize, q)
Get a page of conversations in which member names and messages match the search criteria.
searchConversations(communityId, q)
Get conversations in which member names and messages match the search criteria in an Experience Cloud site.
searchConversations(communityId, pageParam, pageSize, q)
Get a page of conversations in which member names and messages match the search criteria in an Experience Cloud site.
searchMessages(q)
Get messages that match the search criteria.
searchMessages(pageParam, pageSize, q)
Get a page of messages that match the search criteria.
searchMessages(communityId, q)
Get messages that match the search criteria in an Experience Cloud site.
searchMessages(communityId, pageParam, pageSize, q)
Get a page of messages that match the search criteria in an Experience Cloud site.
sendMessage(text, recipients)
Send a message to a list of recipients.
sendMessage(communityId, text, recipients)
Send a message to a list of recipients in an Experience Cloud site.

getConversation(conversationId)
Get a conversation.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation getConversation(String conversationId)

Parameters
conversationId
Type: String

1170
Apex Reference Guide ChatterMessages Class

ID for the conversation.

Return Value
Type: ConnectApi.ChatterConversation

getConversation(conversationId, pageParam, pageSize)


Get a page of a conversation.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation getConversation(String conversationId,
String pageParam, Integer pageSize)

Parameters
conversationId
Type: String
ID for the conversation.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterConversation

getConversation(communityId, conversationId)
Get a conversation from an Experience Cloud site.

API Version
30.0

1171
Apex Reference Guide ChatterMessages Class

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation getConversation(String communityId, String
conversationId)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
conversationId
Type: String
ID for the conversation.

Return Value
Type: ConnectApi.ChatterConversation

getConversation(communityId, conversationId, pageParam, pageSize)


Get a page of a conversation from an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation getConversation(String communityId, String
conversationId, String pageParam, String pageSize)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
conversationId
Type: String
ID for the conversation.
pageParam
Type:String

1172
Apex Reference Guide ChatterMessages Class

Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterConversation

getConversations()
Get the most recent conversations.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage getConversations()

Return Value
Type: ConnectApi.ChatterConversationPage

getConversations(pageParam, pageSize)
Get a page of conversations.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage getConversations(String pageParam,
Integer pageSize)

1173
Apex Reference Guide ChatterMessages Class

Parameters
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterConversationPage

getConversations(communityId)
Get the most recent conversations from an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage getConversations(String communityId)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.

Return Value
Type: ConnectApi.ChatterConversationPage

getConversations(communityId, pageParam, pageSize)


Get a page of conversations from an Experience Cloud site.

API Version
30.0

1174
Apex Reference Guide ChatterMessages Class

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage getConversations(String communityId,
String pageParam, Integer pageSize)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
pageParam
Type:String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterConversationPage

getMessage(messageId)
Get a message.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessage getMessage(String messageId)

Parameters
messageId
Type: String
ID for the message.

1175
Apex Reference Guide ChatterMessages Class

Return Value
Type: ConnectApi.ChatterMessage

getMessage(communityId, messageId)
Get a message from an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessage getMessage(String communityId, String messageId)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
messageId
Type: String
ID for the message.

Return Value
Type:ConnectApi.ChatterMessage

getMessages()
Get the most recent messages.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage getMessages()

1176
Apex Reference Guide ChatterMessages Class

Return Value
Type: ConnectApi.ChatterMessagePage

getMessages(pageParam, pageSize)
Get a page of messages.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage getMessages(String pageParam, Integer
pageSize)

Parameters
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterMessagePage

getMessages(communityId)
Get the most recent messages from an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage getMessages(String communityId)

1177
Apex Reference Guide ChatterMessages Class

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.

Return Value
Type: ConnectApi.ChatterMessagePage

getMessages(communityId, pageParam, pageSize)


Get a page of messages from an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage getMessages(String communityId, String
pageParam, Integer pageSize)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.ChatterMessagePage

getUnreadCount()
Get the number of conversations that are marked unread.

1178
Apex Reference Guide ChatterMessages Class

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.UnreadConversationCount getUnreadCount()

Return Value
Type: ConnectApi.UnreadConversationCount
If there are fewer than 50 unread conversations, ConnectApi.UreadConversationCount returns the exact number of unread
conversations and the hasMore property is false. If there are more than 50 unread conversations,
ConnectApi.UreadConversationCount returns 50 unread conversations and the hasMore property is true.

Example
ConnectApi.UnreadConversationCount unread = ConnectApi.ChatterMessages.getUnreadCount();

getUnreadCount(communityId)
Get the number of conversations that are marked unread in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.UnreadConversationCount getUnreadCount(String communityId)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.

Return Value
Type: ConnectApi.UnreadConversationCount

1179
Apex Reference Guide ChatterMessages Class

If there are fewer than 50 unread conversations, ConnectApi.UreadConversationCount returns the exact number of unread
conversations and the hasMore property is false. If there are more than 50 unread conversations,
ConnectApi.UreadConversationCount returns 50 unread conversations and the hasMore property is true.

markConversationRead(conversationId, read)
Mark a conversation as read or unread.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationSummary markConversationRead(String
conversationId, Boolean read)

Parameters
conversationId
Type: String
ID for the conversation.
read
Type: Boolean
Specify whether the conversation is read (true) or not (false).

Return Value
Type: ConnectApi.ChatterConversationSummary

markConversationRead(communityId, conversationID, read)


Mark a conversation as read or unread in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationSummary markConversationRead(String
communityId, String conversationID, Boolean read)

1180
Apex Reference Guide ChatterMessages Class

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
conversationId
Type: String
ID for the conversation.
read
Type: Boolean
Specify whether the conversation is read (true) or not (false).

Return Value
Type: ConnectApi.ChatterConversationSummary

replyToMessage(text, inReplyTo)
Reply to a message.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessage replyToMessage(String text, String inReplyTo)

Parameters
text
Type: String
Text of the message. Can’t be empty or over 10,000 characters.
inReplyTo
Type: String
ID of the message that is being responded to.

Return Value
Type: ConnectApi.ChatterMessage

replyToMessage(communityId, text, inReplyTo)


Reply to a message in an Experience Cloud site.

1181
Apex Reference Guide ChatterMessages Class

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessage replyToMessage(String communityId, String text,
String inReplyTo)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
text
Type: String
Text of the message. Can’t be empty or over 10,000 characters.
inReplyTo
Type: String
ID of the message that is being responded to.

Return Value
Type: ConnectApi.ChatterMessage

searchConversation(conversationId, q)
Get a conversation that matches the search criteria.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation searchConversation(String conversationId,
String q)

1182
Apex Reference Guide ChatterMessages Class

Parameters
conversationId
Type: String
ID for the conversation.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversation

searchConversation(conversationId, pageParam, pageSize, q)


Get a conversation with a page of messages that match the search criteria.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation searchConversation(String conversationId,
String pageParam, Integer pageSize, String q)

Parameters
conversationId
Type: String
ID for the conversation.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

1183
Apex Reference Guide ChatterMessages Class

Return Value
Type: ConnectApi.ChatterConversation

searchConversation(communityId, conversationId, q)
Get a conversation with messages that match the search criteria in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversation searchConversation(String communityId,
String conversationId, String q)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
conversationId
Type: String
ID for the conversation.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversation

searchConversation(communityId, conversationId, pageParam, pageSize, q)


Get a conversation with a page of messages that match the search criteria in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

1184
Apex Reference Guide ChatterMessages Class

Signature
public static ConnectApi.ChatterConversation searchConversation(String communityId,
String conversationId, String pageParam, Integer pageSize, String q)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
conversationId
Type: String
ID for the conversation.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversation

searchConversations(q)
Get conversations in which member names and messages match the search criteria.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage searchConversations(String q)

1185
Apex Reference Guide ChatterMessages Class

Parameters
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversationPage

searchConversations(pageParam, pageSize, q)
Get a page of conversations in which member names and messages match the search criteria.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage searchConversations(String pageParam,
Integer pageSize, String q)

Parameters
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversationPage

searchConversations(communityId, q)
Get conversations in which member names and messages match the search criteria in an Experience Cloud site.

1186
Apex Reference Guide ChatterMessages Class

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage searchConversations(String communityId,
String q)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversationPage

searchConversations(communityId, pageParam, pageSize, q)


Get a page of conversations in which member names and messages match the search criteria in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterConversationPage searchConversations(String communityId,
String pageParam, Integer pageSize, String q)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.

1187
Apex Reference Guide ChatterMessages Class

pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterConversationPage

searchMessages(q)
Get messages that match the search criteria.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage searchMessages(String q)

Parameters
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterMessagePage

searchMessages(pageParam, pageSize, q)
Get a page of messages that match the search criteria.

1188
Apex Reference Guide ChatterMessages Class

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage searchMessages(String pageParam, Integer
pageSize, String q)

Parameters
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterMessagePage

searchMessages(communityId, q)
Get messages that match the search criteria in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage searchMessages(String communityId, String
q)

1189
Apex Reference Guide ChatterMessages Class

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

Return Value
Type: ConnectApi.ChatterMessagePage

searchMessages(communityId, pageParam, pageSize, q)


Get a page of messages that match the search criteria in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessagePage searchMessages(String communityId, String
pageParam, Integer pageSize, String q)

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
pageParam
Type: String
Specifies the page token to use to view a page of information. Page tokens are returned as part of the response class, such as
currentPageToken or nextPageToken. If you pass in null, the first page is returned.
pageSize
Type: Integer
Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.
q
Type: String
Required and can’t be null. Specifies the string to search. The search string must contain at least two characters, not including
wildcards. See Wildcards.

1190
Apex Reference Guide ChatterMessages Class

Return Value
Type: ConnectApi.ChatterMessagePage

sendMessage(text, recipients)
Send a message to a list of recipients.

API Version
29.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessage sendMessage(String text, String recipients)

Parameters
text
Type: String
Text of the message. Can’t be empty or over 10,000 characters.
recipients
Type: String
Up to nine comma-separated IDs of the users receiving the message.

Return Value
Type: ConnectApi.ChatterMessage

sendMessage(communityId, text, recipients)


Send a message to a list of recipients in an Experience Cloud site.

API Version
30.0

Requires Chatter
Yes

Signature
public static ConnectApi.ChatterMessage sendMessage(String communityId, String text,
String recipients)

1191
Apex Reference Guide ChatterUsers Class

Parameters
communityId
Type:String
ID for an Experience Cloud site, internal, or null.
text
Type: String
Text of the message. Can’t be empty or over 10,000 characters.
recipients
Type: String
Up to nine comma-separated IDs of users to receive the message.

Return Value
Type: ConnectApi.ChatterMessage

ChatterUsers Class
Access information about users, such as activity, followers, subscriptions, files, and groups.

Namespace
ConnectApi

ChatterUsers Methods
These methods are for ChatterUsers. All methods are static.
All methods in this class require Chatter and are subject to the per user, per namespace, per hour rate limit.

IN THIS SECTION:
exportUserActivities(communityId, userId)
Export Chatter-related user activity, such as bookmarks, topic endorsements, and votes.
follow(communityId, userId, subjectId)
Follow a user or record.
getChatterSettings(communityId, userId)
Get the default Chatter settings for a user.
getFollowers(communityId, userId)
Get the first page of followers for a user.
getFollowers(communityId, userId, pageParam, pageSize)
Get a page of followers for a user.
getFollowings(communityId, userId)
Get the first page of users and records that a user follows.
getFollowings(communityId, userId, pageParam)
Get a page of users and records that a user follows.

1192
Apex Reference Guide ChatterUsers Class

getFollowings(communityId, userId, pageParam, pageSize)


Get a page with the specified number of users and records that a user follows.
getFollowings(communityId, userId, filterType)
Get the first page of records, filtered by key prefix, that a user follows.
getFollowings(communityId, userId, filterType, pageParam)
Get a page of records, filtered by key prefix, that a user follows.
getFollowings(communityId, userId, filterType, pageParam, pageSize)
Get a page with the specified number of records, filtered by key prefix, that a user follows.
getReputation(communityId, userId)
Get a user’s reputation.
getUser(communityId, userId)
Get information about a user.
getUserBatch(communityId, userIds)
Get information about a list of users.
getUserGroups(communityId, userId)
Get a user’s groups.
getUserGroups(communityId, userId, pageParam, pageSize)
Get a page of a user’s groups.
getUsers(communityId)
Get the first page of users.
getUsers(communityId, pageParam, pageSize)
Get a page of users.
purgeUserActivities(communityId, userId)
Start a job to purge Chatter-related user activity, such as bookmarks, topic endorsements, and votes.
searchUserGroupDetails(communityId, userId, q)
Get the user’s groups that match the search criteria.
searchUserGroupDetails(communityId, userId, q, pageParam, pageSize)
Get a page of a user’s groups that match the search criteria.
searchUsers(communityId, q)
Get the first page of users that match the search criteria.
searchUsers(communityId, q, pageParam, pageSize)
Get a page of users that match the search criteria.
searchUsers(communityId, q, searchContextId, pageParam, pageSize)
Get a page of users that match the search criteria.
updateChatterSettings(communityId, userId, defaultGroupEmailFrequency)
Update the default Chatter settings for a user.
updateUser(communityId, userId, userInput)
Update the About Me section for a user.

1193
Apex Reference Guide ChatterUsers Class

exportUserActivities(communityId, userId)
Export Chatter-related user activity, such as bookmarks, topic endorsements, and votes.

API Version
42.0

Requires Chatter
Yes

Signature
public static ConnectApi.UserActivitiesJob exportUserActivities(String communityId,
String userId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
userId
Type: String
ID of the user.

Return Value
Type: ConnectApi.UserActivitiesJob

Usage
The following activities can be exported.
• Bookmark—User bookmarked a post.
• ChatterActivity—Total counts of posts and comments made and likes and comments received for a user.
• ChatterLike—User liked a post or comment.
• Comment—User commented on a post.
• CompanyVerify—User verified comment.
• DownVote—User downvoted a post or comment.
• FeedEntityRead—User read a post.
• FeedRead—User read a feed.
• Mute—User muted a post.
• Post—User made a post.
• TopicEndorsement—User endorsed another user on a topic or received endorsement on a topic.
• UpVote—User upvoted a post or comment.

1194
Apex Reference Guide ChatterUsers Class

follow(communityId, userId, subjectId)


Follow a user or record.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.Subscription follow(String communityId, String userId, String
subjectId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
userId
Type: String
ID for the context user or the keyword me.
subjectId
Type: String
ID of the user or record to follow.

Return Value
Type: ConnectApi.Subscription

Example
ChatterUsers.ConnectApi.Subscription subscriptionToRecord =
ConnectApi.ChatterUsers.follow(null, 'me', '001RR000002G4Y0');

Usage
This method creates an EntitySubscription record, which requires certain permissions. See the Usage section of the EntitySubscription
object for more information.

SEE ALSO:
Unfollow a Record

1195
Apex Reference Guide ChatterUsers Class

getChatterSettings(communityId, userId)
Get the default Chatter settings for a user.

API Version
28.0

Requires Chatter
Yes

Signature
public static ConnectApi.UserChatterSettings getChatterSettings(String communityId,
String userId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
userId
Type: String
ID for the context user or the keyword me.

Return Value
Type: ConnectApi.UserChatterSettings

getFollowers(communityId, userId)
Get the first page of followers for a user.

API Version
28.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FollowerPage getFollowers(String communityId, String userId)

1196
Apex Reference Guide ChatterUsers Class

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
userId
Type: String
ID for a user.

Return Value
Type: ConnectApi.FollowerPage

getFollowers(communityId, userId, pageParam, pageSize)


Get a page of followers for a user.

API Version
28.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FollowerPage getFollowers(String communityId, String userId,
Integer pageParam, Integer pageSize)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
userId
Type: String
ID for a user.
pageParam
Type: Integer
Number of the page you want returned. Starts at 0. If you pass in null or 0, the first page is returned.
pageSize
Type: Integer

1197
Apex Reference Guide ChatterUsers Class

Specifies the number of items per page. Valid values are from 1 through 100. If you pass in null, the default size is 25.

Return Value
Type: ConnectApi.FollowerPage

getFollowings(communityId, userId)
Get the first page of users and records that a user follows.

API Version
28.0

Available to Guest Users


32.0

Requires Chatter
Yes

Signature
public static ConnectApi.FollowingPage getFollowings(String communityId, String userId)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or null.
userId
Type: String
ID for a user.

Return Value
Type: ConnectApi.FollowingPage

getFollowings(communityId, userId, pageParam)


Get a page of users and records that a user follows.

API Version
28.0

Available to Guest Users


32.0

1198
Apex Reference Guide ChatterUsers Class

Requires Chatter
Yes

Signature
public static ConnectApi.FollowingPage getFollowings(String communityId, String userId,
Integer pageParam)

Parameters
communityId
Type: String
ID for an Experience Cloud site, internal, or nu