Process Automation and Logic (38%) Flashcards
Enforcing Object and Field Permissions in Apex
- Sharing rules are not always bypassed just because Apex is run in system context. Use WITH SHARING or WITHOUT SHARING keywords to explicitly enforce or not enforce sharing on Apex classes
- Enforce field and object permission in SOQL queries using keyword WITH SECURITY_ENFORCED.
- Use methods Schema.DescribeSObjectResult and Schema.DescribeFieldResult to check user’s access permission levels to objects and fields
- Use instance methods IsAccessible, IsUpdateable, IsCreatable, IsDeletable with above mentioned to check specific
getGlobalDescribe()
- Returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization
- EX: Map gd = Schema.getGlobalDescribe();
Database.query(string) method
- Use to create a dynamic SOQL query at runtime using input from an end user
- sObject s = Database.query(string);
DescribeSObjectResult Methods
- fields - follow with a field member variable name or the getMap method
- fieldSets - follow with a field set name or the getMap method
- getChildRelationships() returns a list of child relationships
- getKeyPrefix() Returns the 3-character prefix code for the object
- getLabel() Returns the object’s label
- getLabelPlural() Returns the object’s plural label
- getLocalName() Returns the name of the object with namespace omitted if object is part of current namespace
- getName() Returns the name of the object
- getRecordTypeInfos() Returns a list of the record types supported by the object
- getRecordTypeInfosByDeveloperName() Returns a map that matches developer names to their associated record type
- getRecordTypeInfosById() Returns a map that matches the record IDs to their associated record type
- getRecordTypeInfosByName() Returns a map that matches records labels to their associated record type
- getSObjectDescribeOption() Returns the effective describe options used by the system for the SObject
- getSObjectType() Returns the Schema.SObjectType object for the sObject. You can use this to create a similar sObject.
- isAccessible() Returns true if the current user can see this object, false otherwise
- isCreateable() Returns true if the object can be created by the current user, false otherwise
- isCustom() Returns true if the object is a custom object, false if it is a standard object
- isCustomSetting() Returns true if the object is a custom setting, false otherwise
- isDeletable() Returns true if the object can be deleted by the current user, false otherwise
- isFeedEnabled() Returns true if Chatter feeds are enabled for the object, false otherwise
- isMergeable Returns true if the object can be merged with other objects of its type by the current user, false otherwise. True is returned for leads, contacts, and accounts
- isMruEnabled() Returns true if Most Recently Used list functionality is enabled for the object, false otherwise
- isQueryable() Returns true if the object can be queried by the current user, false otherwise
- isSearchable() Returns true if the object can be searched by the current user, false otherwise
- isUndeletable() Returns true if the object can be undeleted by the current user, false otherwise
- isUpdateable() Returns true if the object can be updated by the current user, false otherwise
Cross-object formula fields can pull field values from objects that are up to X relationships away.
10
True or False: Cross-object formula fields can pull data from a record even if the user does not have access to it
True
Reasons a roll-up summary field would not be able to calculate the value of a formula field
- The formula field contains cross-object field references
- The formula field contains functions that derive values dynamically, such as NOW or TODAY
- The formula field is a type other than Number, Currency, Percent, Date, or Date/Time
Roll-up summary functions and supported field types
SUM:
- Number
- Currency
- Percent
MIN or MAX:
- Number
- Currency
- Percent
- Date
- Date/Time
Valid ways to declare a String variable
- Correct: String str1;
- Correct: String str1 = ‘Hello World’;
- Incorrect: String str1 = new String();
- Does not need to be instantiated with a new() command because it is a primitive data type. Can be declared with or without an initial value.
Valid syntax for declaring collection variables
- Can be sObject, Apex object, List, Set, or Map
- new Map()
- new Account[]{}
- new List()
- new Set()
Apex Expression
- A construct made up of variables, operators, and method invocations that evaluates to a single value.
- Can be a literal expression, a new sObject, Apex object, list, set, map, SOQL or SOSL query in square brakcets, or a static or instance method invocation.
Examples:
- 3+4 (literal)
- new List()
- myClass.myMethod()
- new Account[]{}
- Account[] aa= [SELECT Id, Name FROM Account WHERE Name = ‘Acme’]
Lists, Sets, and Maps
- List is an ordered collection of elements distinguished by their indices. Can be of any data type.
- Set is an unordered collection of elements that do not contain any duplicates. Can be of any data type.
- Map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type.
Parameterized Typing
- The concept that Apex is a statically-typed programming language, which means users must specify the data type for a variable before that variable can be used
Characteristics of static, instance, and local
STATIC:
- Associated with a class
- Allowed only in outer classes
- Initialized only when a class is loaded
- Not transmitted as part of the view state for a VF page
INSTANCE:
- Associated with a particular object
- No definition modifier
- Created with every object instantiated from the class in which declared
LOCAL:
- Associated with the block of code in which used
- Must be initialized before being used
Enumerations (enums)
- Abstract data type with values that each take on exactly one of a finite set of identifiers that you specify.
- Define an enum using the enum keyword in declaration and curly braces to demarcate the list of possible values.
- Ex: public enum Season {WINTER, SPRING, SUMMER, FALL}
- By creating an enum, you create a data type. Season can now be used as its own data type to define variables.
- Ex: Season myFavoriteSeason = Season.FALL;
Do-While Loops
do {
statement
} while (Boolean_condition);
- code block/statement must be in curly braces
- Boolean condition statement is not checked until after the first loop, so the do statement is always executed at least once.
Constructor
- Code that is invoked when an object is created from the class blueprint
- Has the same name as the class name
- Should not return a value
- Ex: (second line is the constructor)
public class sampleClass(){ public sampleClass(){ //logic here } public void sampleMethod(){ //logic here } }
Common use cases for Apex
- Web services
- Email services
- Complex validation over multiple objects
- Complex business processes that are not supported by workflow
- Custom transactional logic
Apex sharing settings
- “without sharing” is the default setting for Apex classes.
- Inner classes do not inherit the sharing setting from their container class.
WITH SHARING - Allows you to specify that the sharing rules for the current user are considered for the class. You have to explicitly set this keyword for the class because Apex code runs in system context, where it has access to all objects and fields. - Syntax: public with sharing class sharingClass{ //code here }
WITHOUT SHARING - Used to ensure that the sharing rules for the current user are NOT enforced. For example, you can explicitly turn off sharing rule enforcement when a class is called from another class that is declared using WITH SHARING. - Syntax: public without sharing class noSharing{ //code here }
INHERITED SHARING
- Helps to avoid ambiguity from an accidentally omitted sharing setting
- Inherited sharing runs as with sharing when used as:
- An Aura Component controller
- A Visualforce controller
- An Apex REST service
- Any other entry point to an Apex transaction
- Inherited sharing runs as without sharing only when explicitly called from an already established without sharing context.
Apex access modifiers
- It is required to specify an access modifier when declaring a top-level class
- It is not mandatory when declaring inner classes
- The default for inner classes is private unless explicitly defined otherwise
PRIVATE:
- Default
- Method or variable is accessible only within the Apex class in which it is defined.
PROTECTED:
- Method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class.
PUBLIC:
- Method or variable can be used by any Apex in this application or namespace.
GLOBAL:
- Method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application.
Use cases for Static variable/method
- To store information that is shared across instances of a class
- To create a utility method in a class
- To use a method or variable without instantiating its class
Since all instances of the same class share a single copy of a static variable, it can be used to store information within the context of an Apex transaction.
PageReference Class
- Reference to an instantiation of a page
- Consists of a URL and a set of query parameter names and values (among other attributes)
Ways to instantiate a PageReference:
- Page.existingPageName
Refers to a PageReference for a Visualforce page that has already been saved in your organization. By referring to a page in this way, the platform recognizes that this controller or controller extension is dependent on the existence of the specified page and will prevent the page from being deleted while the controller or extension exists.
- PageReference pageRef = new PageReference( 'partialURL' ); Creates a PageReference to any page that is hosted on the Lightning platform. For example, setting 'partialURL' to '/apex/HelloWorld' refers to the Visualforce page located at http://mySalesforceInstance/apex/HelloWorld. Likewise, setting 'partialURL' to '/' + 'recordID' refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than Page.existingPageName because the PageReference is constructed at runtime, rather than referenced at compile time. Runtime references are not available to the referential integrity system. Consequently, the platform doesn’t recognize that this controller or controller extension is dependent on the existence of the specified page and won’t issue an error message to prevent user deletion of the page.
- PageReference pageRef = new PageReference ( ‘fullURL’ );
Creates a PageReference for an external URL. - PageReference pageref = ApexPages.currentPage();
Location-based SOQL queries
- Append __s to the end of a geolocation or address field name to retrieve the latitude/longitude value in a SOQL query, instead of the normal __c for a custom field.
- Ex: SELECT Name, Location__latitude__s, Location__longitude__s FROM Warehouse__c
Quoted string escape sequences
- Escape character is the backslash () and using a backslash in any other context will result in an error
- \n or \N = new line
- \r or \R = carriage return
- \t or \T = tab
- \b or \B = bell
- \f or \F = form feed
- \ “ = one double-quote character
- \ ‘ = one single-quote character
- \ = backslash
- LIKE expression only: _ = matches a single underscore character (_)
- LIKE expression only: \% = matches a single percent sign character (%)
Examples:
- SELECT Id FROM Account WHERE Name LIKE ‘Ter%’
(Selects all accounts whose name begins with the three character sequence ‘Ter’)
- SELECT Id from Account WHERE Name LIKE ‘Ter\%’
(Selects all accounts whose name exactly matches the four character sequence ‘Ter%’) - SELECT Id FROM Account WHERE Name LIKE ‘Ter\%%’
(Selects all accounts whose name begins with the four character sequence ‘Ter%’)
SOSL query limits
- If a limit is set on the entire query, results are evenly distributed among the objects returned
Ex: Set an overall query limit of 20 and don’t define any limits on individual objects. If 19 of the results are accounts and 35 are contacts, then only 10 accounts and 10 contacts are returned.
- FIND {test} RETURNING Account(id), Contact LIMIT 20
- Limits can also be set per individual object
Ex: FIND {test} RETURNING Account(id LIMIT 20), Contact LIMIT 100 - If unspecified, the maximum is 2,000 results
Wildcard characters in SOQL and SOSL
= % and _ are wildcards supported by the LIKE operator
- % matches zero or more characters
- _ matches exactly one character
EXAMPLES:
- SELECT Id, LastName FROM Contact WHERE LastName LIKE ‘Ab%’
(This will retrieve Contact records with a last name that starts with ‘Ab’)
- SELECT Id, LastName FROM Contact WHERE LastName LIKE ‘_Ab’
(This will retrieve Contact records with a 3-letter last name ending in ‘Ab’)
Database.insert method
- DML operation with an unnamed Boolean paramater that when set to false, if a record in the insert list fails, the remaining records in the list can still succeed (partial processing).
- The Boolean paramater is “all or nothing” in the sense that if set to true, it will not allow any inserts if a single insert fails.
- Use this operation instead of a DML statement in code when you want to specify whether or not to allow for partial record processing if errors are encountered.
EXAMPLE:
- Database.insert(sObjectsToCreate,true) will prevent inserts if a single insert fails
- Database.insert(sObjectsToCreate,false) will allow inserts even if some failures occur
sObjects that don’t support DML operations
- AccountTerritoryAssignmentRule
- AccountTerritoryAssignmentRuleItem
- ApexComponent
- ApexPage
- BusinessHours
- BusinessProcess
- CategoryNode
- CurrencyType
- DatedConversionRate
- NetworkMember (allows update only)
- ProcessInstance
- Profile
- RecordType
- SelfServiceUser
- StaticResource
- Territory2
- UserAccountTeamMember
- UserPreference
- UserTerritory
- WebLink
Order of execution
- System validation rules
- Before triggers
- All validation rules
- Duplicate rules
- After triggers
- Assignment rules
- Auto-response rules
- Workflow rules (if a field is updated, before update and after update triggers will run again only once more)
- Processes, flows launched by process, flows launched by workflow rules
- Escalation rules
- Entitlement rules
- Record-triggered flows (after save context)
- Formula/roll-up calculations
- Commit to database
- Post-commit logic happens after all DML operations are committed to the database
isExecuting context variable
- Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
- This means that a particular trigger can be tested whether it is executing or not with the help of this variable.
Standard Controller Actions
- Quicksave
- Cancel
- Delete
- Edit
- List
- creates a button that calls an action
- creates a link that calls an action
- periodically calls an action
- makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
- defines a new JavaScript function that calls an action
- calls an action when the page is loaded
Getter & Setter Methods
- The ‘set’ method is used to pass data from Visualforce page to Apex controller.
- The ‘get’ method is used to pass data from Apex controller to the Visualforce page.
- The name of the getter method without the ‘get’ prefix should be used to display results from a getter method.
- Every value that is calculated by a controller and displayed in a page must have a corresponding getter method, including any Boolean variables.
- Setter methods must always be named in the standard convention of setVariable