Logic and Process Automation Flashcards
- Describe how to programmatically access and utilize the object schema.
- How can you check a user’s access permissions?
- In Apex?
- In Visualforce?
Apex provides two data structures and a method for sObject and field describe information:
- Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time. This is used for token describes.
- The describeSObjects method—a method in the Schema class that performs describes on one or more sObject types.
- Describe result—an object of type Schema.DescribeSObjectResult that contains all the describe properties for the sObject or field. Describe result objects are not serializable, and are validated at runtime. This result object is returned when performing the describe, using either the sObject token or the describeSObjects method.
The following algorithm shows how you can work with describe information in Apex:
- Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects.)
- Determine the sObject you need to access.
- Generate the describe result for the sObject.
- If necessary, generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject.)
- Generate the describe result for the field the code needs to access.
Some standard sObjects have a field called sObjectType, for example, AssignmentRule, QueueSObject, and RecordType. For these types of sObjects, always use the getSObjectType method for retrieving the token. If you use the property, for example, RecordType.sObjectType, the field is returned.
Access Checks
- In Apex:
- You can check a users access to an object via Schema.DescribeSObjectResult.(isUpdateable||isAccessible||isCreateable||isDeletable)
- and similarly for FLS via Schema.DescribeFieldResult (except for isDeleteable)
- Automatic CRUD and FLS Enforcement in VisualForce
- When rendering VisualForce pages, the platform will automatically enforce CRUD and FLS when the developer references SObjects and SObject fields directly in the VisualForce page.
*
- When rendering VisualForce pages, the platform will automatically enforce CRUD and FLS when the developer references SObjects and SObject fields directly in the VisualForce page.
Describe the capabilities and use cases for formula fields. When do formula’s get executed? Cross object formulas?
- Capability: A formula is an algorithm that derives its value from other fields, expressions, or values. Formulas can help you automatically calculate the value of a field based on other fields.
- Use Cases: Approval Processes & Steps, Assignment Rules, Auto-Response Rules, Escalation Rules, Custom Buttons and Links, Custom Fields, Custom Summary Formulas, Data Validations, Default Field Values, Reports, S-Controls, V. Rules, Workflow Rules & Field updates, VF pages
- Execution Time:
- Default Field Values: Record Create
- Formula Fields: Record Display
- V. Rules: Save
- W/F Rules: Save
- Approval Processes: Submit
- Field Updates: W/F or App. Process
- Custom Summary on Report: Report Runtime
- Cross Object Formulas:
- Cross-object formulas are formulas that span two related objects and reference merge fields on those objects.
- Cross-object formulas can reference merge fields from a master (“parent”) object if an object is on the detail side of a master-detail relationship.
- Cross-object formulas also work with lookup relationships.
- You can reference fields from objects that are up to 10 relationships away. Cross-object formulas are available anywhere formulas are used except when creating default values.
- Currency References convert the value to the currency of the record that contains the formula unless the ref is a custom setting.
- SFDC allows a maximum of 10 unique relationships per object, cumulative on all lookups, formulas and rules.
- Can’t use in rollup summary fields due to when formula’s run
- you can’t reference merge fields on objects related to activities
Describe the capabilities and use cases for roll-up summary fields.
- Remember roll-up summary field only works with Master-detail relation so as soon as you read look up relation it can’t be roll-up summary field)
- A roll-up summary field calculates values from related records, such as those in a related list.
- You can create a roll-up summary field to display a value in a master record based on the values of fields in a detail record.
- The detail record must be related to the master through a master-detail relationship.
- Count, Sum(Num,Curr,%), Min, Max(Num,Curr,%,Date,Date/Time) recalc. is not done when child records are deleted unless you set “Force mass recalc on this field” boolean to true.
- you cannot use cross object formula fields in field column of a R.U.S.
Describe the differences between formula, rollup summary fields and triggers.
The question around this section might try to trick you between formula, rollup summary fields and trigger. Remember cross object formula always works from child to parent means you can create formula on child to reference parent only and if parent has to refer children then it might be roll up summary field (Must be master-detail relation) or trigger for complex logic. Workflow rules also can only can refer parent fields for an update.
Describe the capabilities of the declarative process automation features .
- If there is scenario to choose between workflow or process builder then you should just mark process builder as appropriate solutions as it supersedes workflows.
- Workflow can only update parent fields in cross object update where process builder can update either parent or children.
- The only thing you can do with workflow that you can’t do with processes is send outbound messages without code. However, you can work around this limitation by calling Apex code from a process.
- What tool to use?
- What to do when a record has certain values
- Workflow, PB, VW
- Get information from users or customers and do something
- VW
- Approve a record
- approval processes
- What to do when a record has certain values
Describe when to use declarative automation features vs. Apex classes and triggers
When should I use Apex?
- Create web services
- create email services
- perform complex validation across multiple objects
- create complex business processes not supported by workflow
- create custom transactional logic (occurs over an entire transaction not just with a single record)
- attach custom logic to another operation regardless of where it originates
Triggers vs. Workflow/PB
- Triggers:
- Perform complex validations.
- before/after logic on update/insert/delete/undelete operations.
- update/retrieve/insert any object or related records
- PB
- Can update child records
- can update all related objects without apex
- when apex is required, use @invocable to call code without a Trigger invoke.
- no outbound message
- WF
- updates parents only
- one if/then logic statement
- outbound message ok
*
Describe how to declare variables and constants in Apex and how to assign values using expressions.
Declare apex variables with:
accessModifier dataType uniqueName;
ex: public String dogCat;
Constants have “final” modifier (and should be capitalized)
Assign Values to Variables and constants with = sign
docCat = “Harry”;
- use [] notation for lists (0 is index 1st pos)
- assignment is alwasy done by reference
- two lists can point to the same value in memory
Describe the primitive and complex Apex data types and when to use them
- Primitive Data types are:
- Blob, Boolean, Date, Datetime, Decimal, Double, Id, Integer, Long, Object, String, Time
- Else the are composite
- sObject
- Collection (list, set, map)
- enum
- user defined
- system defined
- Null
- Composite Data types must be declared using the “new” keyword + method of the same name as the datatype.
- List<account> aL = new List<account></account></account>
Describe how to use and apply Apex control flow statements.
- Loops
- For
- List For: for(interationVariableDatatype iterVariable:listName){};
- SOQL For: for(Variable_List|Variable:[SOQL query]){}. Use this when SOQL stmnt has over 200 records, this will batch 200 at a time if you use variable_list
- nest for loops to process efficiently
- DONT USE WITH SOQL: Aggregate function
- reg: for(Integer i = 0, Ii > j, i++){}
- While/Do-While
- while a condition is true, execute code (may never fire)
- Do-While (execute first time, then eval)
- For
- If/Then/Else:
- execute code block if statement evals to TRUE
- else do the the next statement
*
Describe how to write and when to use Apex classes and interfaces.
Apex Classes are declared:
accessModifier optionalDefinitionMod classKeyword className {
\code block, contains attributes and methods
class innerClass{}
public String name;
public void sit()
}
}
- a class can not have a more restrictive access modifier than one of its methods, attributes or inner classes
- An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.
Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the declaration for that method. This way you can have different implementations of a method based on your specific application.
Describe how to use basic SOSL, SOQL, and DML statements.
- SOQL:
-
Regular: Contact c = new Contact(Account = [SELECT Name FROM Account
WHERE NumberOfEmployees > 10 LIMIT 1]); - Child to Parent: SELECT Id, Account.Name from Contact Where…
-
Parent to child: for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
WHERE Name = ‘Acme’]) {
Contact[] cons = a.Contacts;
}- parent to child query
-
Regular: Contact c = new Contact(Account = [SELECT Name FROM Account
- SOSL:
- FIND ‘map*’ IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead
- DML
- DML Statements
- (insert, update, delete) keywords
- Key considerations:
- no partial record processing (entire transaction rolled back on failure)
- No SaveResult for error handling
- WILL throw an Apex exception and stop control flow
- Database Class:
- Database.insert…etc.
- Allow partial success with result for inspection and retry
- Possible to write code that never throws an exception but you don’t have to, exc. can be thrown.
- can set savepoint and rollback DB calls
- DML Statements
Describe the basic patterns used in triggers and classes to process data efficiently.
- Trigger best practices
- One Trigger per object, use all contexts required.
- Move logic to handler classes, trigger becomes orchestration layer.
- use context specific handler methods.
- Bulkify your triggers
- no DML or SOQL within a for loop (using SOQL For is not inside)
- perform DML on collections (up to 10k)
- preprocess records to minimize soql statements by generating sets and using the IN clause.
Describe when to use and how to write triggers.
- triggers invoke apex
- before/after: insert, update, delete, merge, upsert, undelete
- before triggers update data prior to database writes
- after triggers access values set by the system
- records that fire after-trigger are read only
- upsert triggers fire both before and after insert or before and after update triggers as appropriate.
- Field history is not recorded until the end of a trigger.
- Field history tracking honors the permissions of the current user.
- merge triggers fire both before and after delete triggers for the losing records and before update triggers for the winning record only.
- Callouts must be made asynchronously from a trigger so that the trigger process isn’t blocked while waiting for the external service’s response
Describe the implications of governor limits on Apex transactions.
- These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execute method.
- SOQL relationship queries count as an extra query
- Database.countquery|getquerylocator|query all count as well
- DML Statements (these all count)
- Approval.process
- Database.convertLead
- Database.emptyRecycleBin
- Database.rollback
- Database.setSavePoint
- delete and Database.delete
- insert and Database.insert
- merge and Database.merge
- undelete and Database.undelete
- update and Database.update
- upsert and Database.upsert
- System.runAs
- Recursive Apex that does not fire a trigger is still one apex transaction. If it does fire, each trigger has separate execution context.
Describe the relationship between Apex transactions , the save execution order, and the potential for recursion and/or cascading.
Relation between apex transactions:
- Transactions: Keep data consistent across related operations (think debits/credits)
- Allow a set of operations to either complete fully or be completely rolled back.
Execution Order - On the server, Salesforce:
- Loads the original record from the database or initializes the record for an upsert statement.
- Loads the new record field values from the request and overwrites the old values.
- If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:
- Compliance with layout-specific rules
- Required values at the layout level and field-definition level
- Valid field formats
- Maximum field length
- When the request comes from other sources, such as an Apex application or a SOAP API call, Salesforce validates only the foreign keys. Prior to executing a trigger, Salesforce verifies that any custom foreign keys do not refer to the object itself.
- Salesforce runs user-defined validation rules if multiline items were created, such as quote line items and opportunity line items.
- Executes all before triggers.
- Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn’t run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
- Executes duplicate rules. If the duplicate rule identifies the record as a duplicate and uses the block action, the record is not saved and no further steps, such as after triggers and workflow rules, are taken.
- Saves the record to the database, but doesn’t commit yet.
- Executes all after triggers.
- Executes assignment rules.
- Executes auto-response rules.
- Executes workflow rules.
- If there are workflow field updates, updates the record again.
- If the record was updated with workflow field updates, fires before update triggers and after update triggers one more time (and only one more time), in addition to standard validations. Custom validation rules, duplicate rules, and escalation rules are not run again.
- Executes processes.
- If there are workflow flow triggers, executes the flows.The pilot program for flow trigger workflow actions is closed. If you’ve already enabled the pilot in your org, you can continue to create and edit flow trigger workflow actions. If you didn’t enable the pilot in your org, use the Flows action in Process Builder instead.
- Executes escalation rules.
- Executes entitlement rules.
- If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
- If the parent record is updated, and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the grandparent record. Grandparent record goes through save procedure.
- Executes Criteria Based Sharing evaluation.
- Commits all DML operations to the database.
- Executes post-commit logic, such as sending email.
- During a recursive save, Salesforce skips steps 8 (assignment rules) through 17 (roll-up summary field in the grandparent record).
- You must remember execution order by heart and there are definitely one to two questions on it. If you understand execution order you will understand when it can be recursive behavior like workflow which gets executed after trigger if updates record in transaction it might result in re-running after triggers