SF - BestCheet
SF - BestCheet
------------------------------------------------
User Interface
Visualforce (Standard and Custom Controller, Web Content)
The Lightning Component Framework
Resources in a Lightning Component
Resources in Lightning Web Component
Decorators (LWC)
1
Lightning Message Service
With/without Sharing:
Lightning Locker Service (security)
LWC – Shadow DOM
Testing
Testing Requirement and Framework
Unit Test
Test Data
Invoking Apex in Execute Anonymous vs. Unit Tests
Asynchronous Apex (Future, Batch, Queueable)
OTHER QUESTIONS
Business processes (SFDC configuration)
Record types
Integration with SF (REST and SOAP API)
Integration with 3rd party (ANYPOINT)
Outbound messaging
Query() and Queryall()
Roles and Profiles and Permission Sets
Custom settings vs Custom Metadata
Large volumes of data - best practices
Lazy notes
Authentication while integration – Single Sign-on (SSO)
2
SF DEVELOPER
4
Core CRM Objects (Lead, Account, Contact, Opportunity)
Standard Functionalities in SF
We need to be able to: SF offers the following standard functionalities:
Sell to prospects and customers Leads, Accounts, Contacts and Opportunities to manage the sales process
Help customers after the sale Cases and Communities to engage with customers
Work on the go SF1 Mobile app to power your mobile strategy
Collaborate Chatter and Communities for employees, customers, and partners
Market to our audience Marketing Cloud to manage our Customer’s journey
Lead Person Accounts. They have human details, don’t have
People and companies that we’ve identified as potential contacts or account hierarchy. Person accounts are forever.
customers. Lead features: After they're turned on, we can't turn them off. If our
Web-to-Lead: Generates HTML that we can use in any organization uses both business and person accounts, we’ll
webpage. This HTML contains code by SF. When a person have to select which type of account we’re creating whenever
fills this form, the code lets it open a Lead in SF. Assignment we add an account.
Rules will be applied here
Auto-Response: Automatically determine which email Contacts to Multiple Accounts: each contact has a primary
templates to use when sending auto-response messages to Account (lookup field) on his Record. But a contact may
new leads from our website. belong to more than 1 Account, a VP can also be member of
Assignment Rule: Specify how Records are assigned to board for another Account by allowing it: Account Settings:
Users or Queues based on certain criteria. Like 1 or more select Allow users to relate a contact to multiple accounts.
filters, or entries: each a Lead comes from the web, so the Add the Related Contacts related list to the account page
Assignment Rule is checked, specifically the first entry or layout (Because the Related Contacts related list
filter. If matches, ok, if not, go to the next. If all no, go to the automatically includes all direct contacts, we can remove the
default. Only 1 active Rule at a time for each Object! It can Contacts related list on our account page layouts.)
have many Entries Account Hierarchies: Each Account can have a Parent
Lead Queue: Queues are location where records await Account. This way, Accounts are linked through the
processing by assigned members. It is like a Hierarchy.
bucket/Collection of Records. Unlike Groups which is a Account Teams: It is related with the permission. Sales team
collection of Users. has permission for something, and we can add another person
o It can contain public groups, Roles and Subordinates can look at the account. He has access to that account. Both
and Users – Queue members Account and Opportunity teams extend record-level
o When Queue created, a View also created for it. privileges to team members. Provide a clear way to document
Member of the queue can accept any Records in it the roles of multiple users in the management of a single
Lead Conversion: Use the leads object to store lower quality account. Opportunity teams (AKA team selling) does the
or unverified data. Only leads that are qualified and of high same for opportunities. Account Team disabled by default.
data quality should be converted to: Account, Opportunity, To enable it: Customize | Accounts | Account Teams
Contact. Conversion Process:
o Lead has done its job when Status is closed and Contact
The people who work at our accounts are called Contacts. Each
converted. If only closed, then we didn’t get business
account has at least one contact person, and each contact is related
o Takes the info from the Lead, and generate a new
to an account. Contacts are people in these accounts who matter to
Account, Contact and Opportunity and optional Follow-
our business. Ex: decision makers, influencers, and partners.
up task from the info in it. It maps fields in the Lead
Features:
Object to fields in these 3 Objects:
Business Contacts: a contact belonging to an Account
The Contact is Mandatory (no option to omit it)
Private Contact: Contacts without accounts—orphan or
The Account is Optional (can choose existing one, or
Private contacts are like a forgotten boat adrift at sea. Better
create new one)
to always associate contacts with an account. To enable
The Opportunity is also Optional (you can check the
Private Contacts, we should make the Account Lookup field
box “Do not create a new opportunity upon
NOT mandatory on the contact Object.
conversion”)
! ! ! They’re hidden from all users except their owner and
Can also map custom fields from lead to custom fields on
system administrators.
Account, Contact or Opportunity
Validation rules should also be passed before the creation of Opportunity
Account, Contact or Opportunity Deal with potential revenue that sales reps track through the Sales
The lead is then flagged as converted which removes the Cycle until the deal is closed. Sales reps use opportunities to track
record from search results, and the lead can no longer be deals, generate pipeline, forecast revenue and determine that’s
viewed. needed to keep the sales cycle moving. Opportunity Features:
Account Opportunity Teams: Enabled by default. To disable it:
An organization or person involved with our business (such as Customize | Opportunities | Opportunity Teams | Opportunity
customers, competitors, and partners). Account Features: Teams Settings. A user can define his own team: Default
Business Accounts: When we open the account record, we Opportunity Team and Default Account Team on “My
see the information collected on the company as a list of Settings”
records related to it, such people who work there, deals in the o Used in collaborative selling. Opportunity owner, their
works, service requests, uploaded documents, and more. manager in hierarchy and Admin can: Manually
Person Accounts: If we have customers who are individuals, add/remove users on an Opportunity. Create personal
not companies, our SF organization can be set up to use default Sales team which can be added automatically
TOP
5
Packages - AppExchange • Experience:
• AppExchange is the Business AppStore and it is the official dataloader.io, the #1 Data Loader for SF: It is easy to
SF app store. Short on time and don’t want to build a solution login to use our existing SF credentials into
from scratch? There’s probably an app that meets your needs. dataloader.io without the hassle of downloading an
And because it’s SF’s official app store, everything is secure application. Data mapping made easy: Auto-mapping,
and trustworthy. keyboard shortcuts and search filters help you find and
o App: A group of tabs that work together to provide map fields quickly. Avoid redundant work: Pull related
standalone functionality objects such as Account ID’s through a single pull,
o Component: A building block for a Lightning app, removing the need to pull multiple datasets and re-
page, or community associate them in Excel.
o Consulting Service: A team of SF experts who deliver DocuSign: DocuSign gives you the ability for us and
specialized solutions for one or more clouds or our clients to sign contracts, purchase orders and any
industries other legal document, digitally, we also use it in over
• AppExchange Strategy: Offering type: Are you looking for release signoff process.
an app, component, or consulting service? Functionality, Conga Composer: With this app, users can easily
Budget, Stakeholder needs, Testing: always recommended create and deliver fully customizable Word, PowerPoint,
testing in a Developer Edition org or a sandbox, Technical Excel, HTML email, and PDF form output. This is often
considerations used to make proposals, account plans, invoices, quotes,
• When to use an App from AppExchange? Always revert to contracts, etc. from SF data. I have used Conga
the AppExchange when required to implement a new Composer for so many different projects—from
functionality within SF. The Application that you are mailings to formatted reports—and in every case, it has
looking for may be already in the AppExchange, and may reduced a process that used to take hours down to a
also be Free. For example, if you are required to implement single button click.
an Advanced Quoting Tool
Packages
• A Package is bundle of metadata components that make up an App or piece of functionality
• Typically, a package would contain Objects, Fields, Apex Code, Page Layouts, Reports, email template, etc...
• Packages can contain one component (e.g. an Apex Class) or hundreds of components
• Packages are primarily used for distributing across SF Orgs
6
Formula fields are calculated using generated SOQL(must not exceed 5000 but it is treated as Master-Detail relationship. From Account,
characters) on the backend. This includes other referenced formula fields. we can create a Rollup Summary Field that is used to
Cross-Object formula can reference fields from objects that are up to 10
relationships away summarize all child Opportunity records
• Cross Object Formula: A formula calculates fields from within the same • When creating the Master Detail Field, we can use filters to
Object record, however; we can create a formula on an Object child to only pull value from specific Records. For example, only
reference parent Object field. It is all about getting information of Parent include information from Opportunities that are Closed/Won
object into Child object. Fetching child Object information in parent record
is not done by Formula, it is done by Rollup Summary Fields in the case of Validation Rules
Master Detail relationship only. • Used to enforce field requirements based on Business Logic before save
• Example: on Opportunity Object, that uses fields from the Account Object (create or update a Record). In other words, it is used to create conditional
to calculate against display the Account Rating Field on the Opportunity Requirements on Fields to ensure clean and accurate data entry.
Record. (Note that Opportunity is child of Account. Account Rating field is Validation Rules is not used to replace the Required Field option in Field
on the Account object (it is based on many criteria). Use the Text function: Level Security or page Layout, but for specific scenarios based on values
TEXT(Parent_Formula_MD__r.Picklist_1__c) ) from other fields.
• Defined using a formula that returns true or false. If the formula returns
Rollup Summary Field true, the defined Error message is displayed, and record cannot be saved.
The formula can reference more than 1 field at a time. The error message
• A type of field that is available only on the Master object in a should clearly indicate the error. Error message can be displayed at the
Master-Detail relationship top of the page or next to the field that failed the validation rule. Note:
• Used to summarize numeric value from a selected field in VR ARE case sensitive. VR will impact API usage (ex. Data Loader),
child Object records. Rollup Summary Field will get web-to-lead, and web-to-case submissions. Make sure to structure your
validation rules so that they will not unintentionally interfere with these
information from the related child Object Records. operations (such as rejecting a web-to-lead submission or Data Loader).
• Information types: Count, SUM, MIN, MAX So, in some scenarios, we may need to disable validation rules when
• Example: Opportunity Object is child of Account Object. importing or updating data, and reinstate them afterwards
Opportunity Object uses a Lookup relationship to Account, TOP
Data Modeling and Management think of, but they'd have no way of linking to one another. With
relationships, we can display data about other related object records
Data Modeling (SF Objects, Object Fields)
on a particular record's detail page.
In a standard relational database: • Models:
o Data is stored in tables. Each Table is composed of a o One to One: Husband / Wife (A Wife can have one husband
number of Columns of a particular data type, such as only; A Husband can have one Wife only)
text, number, or date and information is stored in Rows o One to Many: Team / Player (A Player can have one Team only;
of the table. Tables can be related to other tables, using A Team can have many Players)
primary and foreign keys. Apps manage information o Many to One: Player / Team (A Team can have many Players; A
by creating, reading, updating, and deleting rows in a Player can have one Team only)
table. o Many to Many: Subject / Student (A Student can attend many
Subjects, A Subject can be attended by many Students)
Data Modeling in SF This allows each record of one object to be linked to multiple
The database in Force.com uses Objects to store data. records for another object and vice versa
• Objects contain all the functionality we expect in a standard To create it, we can link Objects using a Junction Object. A
database Table, with additional enhancements that make them more junction object is a custom object that is Child to both
powerful and versatile. Objects via 2 Master-Detail relationships
• Each object comprises a number of Fields, which correspond to SF Relationship Fields
Columns in a database. In SF, we don’t deal with primary keys and foreign keys to define
• Data is stored in Records of the object, which correspond to Rows in relationships between data, but the Force.com platform uses
a database. Relationship Fields. There are 2 types:
• Tab: Just like a tab in spreadsheet tabs give access to objects in SF Lookup Relationship
UI o It creates a relationship that links one object to another
object
o Lookup field created on the Child Object
SF Objects
o Related List created on the Parent Object
• Standard Objects: default objects which used to store data o The 2 Objects are loosely related
in standard tabs such as Accounts, Contacts, or o Ownership and sharing is independent
Opportunities. o Record Deletion is independent
• Custom Objects: These are new objects we create to store o Lookup fields can be optionally required on child records.
information unique to our organization. Master-Detail Relationships
o Custom objects extend the functionality that standard o It creates a relationship that links one object to another
objects provide. object
o We can also create any custom App using Standard and o Master-Detail field created on the Child Object (Detail)
Custom Objects o Related List created on the Parent Object (Master)
o The 2 Objects are tightly related
Object Fields
o Ownership and sharing of detail records are determined by
Each standard or custom object consists of a set of fields. There
the master record
are several different types of fields, as described below. o When we delete the master record, all of its detail records
• Identity Fields: Force.com automatically assigns an identity (called are automatically deleted along with it
ID) to every object o Fields are always required on detail records.
• System Fields: All objects have a number of read-only system fields
o Cross-object workflow and Rollup summary is possible here
automatically associated with them
o CreatedDate—the Date and time when the object was TOP
created Other types of Relationships
o CreatedById—the ID of the User who created the object • Hierarchical: A special lookup relationship available for only the
o LastModifiedById—the ID of the User who last modified User object. It lets users use a lookup field to associate one user with
the object another that does not directly or indirectly refer to itself
o LastModifiedDate—the date and time when the object was • External Lookup: Links a child standard, custom, or external object
last modified by a user to a parent external object. The standard External ID field on the
• Name Field: required field is intended as a human-readable parent external object is matched against the values of the child’s
identifier for a record. A name can be one of two types: a text string external lookup relationship field.
or an auto-number field • Indirect Lookup: links a child external object to a parent standard or
• Custom Fields: We can define custom fields, either to extend the custom object
functionality of a standard object, or when creating new custom TOP
objects Schema and Schema Builder
• Relationship Fields: Instead of having to deal with primary keys and • Schema Design: As we learned, through the UI, we can define our
foreign keys, to define relationships between data, Force.com uses schema, like: Create Objects, Create Fields, Create relationships
relationship fields. There are 2 types of Relationship Field: Lookup between Objects
and Master-Detail • Schema Design impact on Apex: When we define our schema using
Relationship Types (Lookup and Master-Detail) the UI, it becomes available to be used in our code. All defined
• Relationship is a two-way association between two objects. Without Objects, Fields and Relations can be used programmatically with
relationships, we could build out as many custom objects as we can Apex and SOQL
8
• Schema Modification impact on Apex: When you modify your • It automatically implements the changes and saves the layout of our
schema using the User Interface, all modifications will be reflected schema any time we move an object. This eliminates the need to
when used in our code. Note: we can't delete or edit a field when that click from page to page to find the details of a relationship or to add
field is referenced by custom Apex that has been deployed to our a new custom field to an object in our schema.
org. • We can view the fields and relationships for both standard and
Schema Builder custom objects
• It is a tool to View and Modify our SF org data model visually. It • Note: Any field we add through Schema Builder isn’t automatically
simplifies the task of designing, implementing, and modifying our added to the page layout!!
data model, or schema. We can view our existing schema and • Note: By default, the Field Level Security for custom fields is set to
interactively add new custom objects, custom fields, and visible and editable for internal profiles.
relationships, simply by dragging and dropping • Fields that are not normally editable, such as formulas and roll-up
• Schema Builder is enabled by default and lets us: Jump directly to summary fields, are visible and read-only.
Object page and Layout page that are in Setup, Create Custom • To manage permissions of a custom field, click the element name or
objects, Delete Custom objects, Edit Custom Object properties, label and select Manage Field Permissions
create any custom field except: Geolocation (including Lookup and TOP
Master-Detail), Delete Custom field
Logic and Process Automation • The Declarative solution should always be the first option,
then we use Programmatic tools, Apex Triggers and Classes
APEX Best Practices (or Declarative) - compare APEX over declarative tools?
JAVA • Suppose we have a situation whenever make a change on the
opportunity and that change will also have to be reflect in the
Rule of Thumb: account related event. That is not possible through any
• Anytime we can build a Process Automation using a workflow or process. That will take advantage of triggers.
Declarative feature, choose that Point and Click Feature! Use Apex Classes and Triggers for:
9
Apex Data Types
• Greater Flexibility, control and more complex logic String, Integer, Long, Decimal, Double, Date, Datetime, Time, Boolean, ID, sObject (Specific (Account a = new
• Harder to maintain and needs Developers Account()) and Generic (sObject s = new Account() ), Object, Collection: List (Ordered/Indexed collection of non-
Unique elements), Set (Unordered Collection of Unique elements), Map (Collection of Unique Key-Value pairs)
NOTE:
o Value and reference types work the same, but in Apex, all variables are initialized to null by default.
o One thing to be aware of is that .NET strings are actually references even though they behave like
value types, because they’re immutable.
o But in Apex, strings are always treated as a primitive value type.\
In Apex, you can use enums with numbers, but you can’t define what these number values are. Also, the
ordinal assignment starts at zero. For example, if you had an enum like the following. public enum
myEnums {}
Apex Control Flow Statements
In a program, statements are generally executed line by line, in the order they appear. Apex provides
statements that control the flow of code execution: control flow statements
With control flow statements, we can: Cause Apex code to execute based on a certain condition and Have a
block of code execute repeatedly.
This chapter describes these control flow statements: if-else statements and loops.
Apex Control Flow Statements – If statement
• The most basic of all the control statements. An if statement consists of a boolean expression
Best Practices •
followed by one or more statements. If the Boolean condition is True, the statements are executed
Format: If (boolean-condition) { Statements; }
1. There will be NO DML inside the Loop. Apex Control Flow Statements – Loop
While - Executes a statement If the Boolean test returns True. Execution will stop when the value of condition
2. While designing a Query, fetch only those records that becomes False. The test takes place before each iteration. Format: while (Boolean_condition) { statement; }
Do While - A do-while loop is similar to the while loop, except that a do-while loop is guaranteed to execute at
are needed to fetch. least one time. The do-while loop checks the condition at the bottom of the loop. Format: do
{ statement;} while (boolean_);
3. Use collection (list, set or Map) for the Queries. For, For Each, SOQL For Loop; Format: For (variable : [soql query] ) { statements; }
4. SOQL query for loop, when working on the large dataset Apex Control Flow Statements – Branching
Break statement: It terminates the loop and goes out of it immediately when it appears. Available for For
of records. loops, While loop, Do-While loop. will not allow to continue iterating
Continue Statement: It skips the current iteration and goes to the next.
5. Use where and Limit clause, in order to avoid hitting of TOP
the governor limit. OOP, Class, Object, State, Behavior, Variables, Methods, Static, Constructor, Access
6. Avoid Hardcoding IDs, because Ids are different in Modifiers, Construction (Virtual, Extends, Override, Abstract)
7. Writing Test Methods to verify the operation or logic of • Historically, a program is a set of procedures that takes input data, processes it, and produces output data.
Object-Oriented programming (OOP) is a programming language model organized around Classes and
the apex class. Objects. OOP consists of modeling real world components into programmer-defined Classes: the building-
blocks of an Object-Oriented Program is the Class. In an OOP, a Class is responsible to achieve certain things,
8. Design the logic in such a way that it will handle the and you don’t need to know the details of how this Class achieves its output
• Apex is an Object-Oriented Programming language!
BULK of records. • Class and Object: A Class is a template, or a blueprint from which Objects can be created/ instantiated. In
other words, an Object is an instance of a Class. For example, the Pen Class is the blueprint that describes a
Pen, and all the operations possible on a Pen. An instance of the Pen Class is a specific Pen that you can use. It
is called a Pen Object. A Class may contain other classes (Inner Classes). Inner classes may be nested only
Compared with Java
one level deep! To create inner class Objects: myClass.myInnerClass myInnerClassObject = new
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and
myClass.myInnerClass();
transaction control statements on the Lightning platform server in conjunction with calls to the Lightning
State and Behavior: All Objects have State and Behavior: things that an object knows about itself, and things
Platform API. Using syntax that looks like Java and acts like database stored procedures, Apex enables
that an object can do. The State of a Pen object: what it knows - includes the brand, color, price... etc. The
developers to add business logic to most system events, including button clicks, related record updates, and
Behavior of a Pen object: what it can do - includes write, refill... etc. State is named Variables and Behavior
Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects.
and is named Methods.
Apex classes and Java classes work in similar ways, but there are some significant differences.
Variables: A Variable can be assigned to: The Class itself (Static Variable) using dot notation. The Object
These are the major differences between Apex classes and Java classes:
created from the Class using dot notation.No parenthesis is used with Variables.
● An inner class behaves like a static Java inner class but doesn’t require the static keyword. An inner
• Methods: A Method can be called on: The Class itself (Static Method) without the need of a Class instance,
class can have instance member variables like an outer class, but there is no implicit pointer to an
using dot notation. A Class instance (Object) using dot notation. Methods always use parenthesis when called.
instance of the outer class (using this keyword).
A Method can have 1 or more parameters, or no parameters at all. In this case, the parenthesis don’t have
● The public access modifier means the method or variable can be used by any Apex in this
anything inside them. A Method can either return a data type, or not return anything (Void)
application or namespace.
• Static Variables are variables that belong to the Class itself, not to the instances of the class (Objects). To
● Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.
store information that is shared across instances of a class. For example, it can be used as a counter
TOP
• Static Methods can be called directly from the Class, not from an instance of the Class (Object). This way,
Variables, Constants and Expressions, Data Types, Control Flow Statements there is no need to instantiate a Class to a Class Instance (Object) to call a static Method. A Static Method
Variables cannot be called from a Class Instance (Object), it can only be called from the Class itself
• A program in general, accepts input data, manipulates it, and generates output data. Data in any Programming • Constructors: are special Methods that are used to instantiate a Class. By default every Apex Class has a
Language can be numbers, characters, or other values default Constructor that has no parameters. You can add any custom Constructor, with or without parameters.
• Variable: a place in your computer memory that is given a name and that is used to store data to be used in a Custom Constructors should have the same name as the Class. Custom Constructors do not have a return type.
program Whenever you add a custom Constructor, the default Constructor is gone!
• Why we use variables: Make code easier to read and more effective – use variable as a simple easy-to-read • Access Modifiers:
word o Global: Classes can be seen by all classes in all namespaces everywhere. A global method can only
• Declaration: Apex is case insensitive. Apex is Strongly Typed Language – meaning: while declaring variable be contained in a global class. Use Case: Batch Apex, Inbound Email Service, Web Service.
you have to declare it with its data type. Variable declaration statement: an Apex statement that creates a new Scheduled apex. Accessible classes in managed packages (AppExchange vendors make Global
Variable: of a given type or with a given name classes and share them in AppExchange. In that way, the customer can access this global class. If they
• Variable names cannot have: White Space, Special characters (+, -, &, *...), Cannot be reserved words, like make it public, customers cannot see this class)
string, integer... o Private: The default one if you don’t specify anything. Cannot be accessible from any other Class,
• Best-practice to declare variable names using Camel Case annotation (start with lower case, and capitalize even from within the same Namespace. Use Case: Inner class to only be accessible within the
each consequent word): containing outer class and Test class
• The = sign is the assignment. Declaring a Variable sets aside a chunk of memory that is used to store the data o Public: Classes can only be seen by other classes within in their own Application or Namespace.
during program execution only. If we declare a variable and don't initialize it with a value, the value will be Namespaces are ONLY used in AppExchange packages. Use Case: Used for anything other than the 5
null. Null means the absence of a value, or data. we can also assign null to any variable declared with a use cases of the Global and 2 cases for the Private
primitive type Syntax
• Types: Class variables: Instance variable (is their body will offer the object which is an instance of a class),
Static variables (is a body of the class itself). Local variables: Inside methods (as parameters or in method),
inside any code block like for loop, if, etc...
• Scope: Variables can be defined at any point in a block and take on scope from that point forward. Child will
have access to the variable and can’t define another variable with the same name that has already been used in
a parent block. Parallel blocks don’t have access to the variable, and they can reuse a variable name
Construction (Virtual, Extends, Override, Abstract)
Apex Constants 1. Virtual / Extends / Override: A Virtual Class CAN be extended (inherited). It does not contain
• A constant is a variable whose value does not change after being initialized once. Constants can be defined ANY Abstract Methods – a Method that only has a Signature. Its Methods can be used in the Class
using the final keyword. Final keyword means that the variable can be assigned at most once: In the that extends it. Virtual Methods CAN be overridden in the Class that extends it
declaration itself. With a static initializer method if the constant is defined in a class 2. Abstract / Extends / Override: An Abstract Class MUST be extended. An Abstract Class contains
Apex Expressions at least 1 Abstract Method – a Method that only has a Signature Its Methods can be used in the
• An Expression is an essential building block of any program. An expression is a construct made up of: Class that extends it. Virtual Methods CAN be overridden in the Class that extends it. EACH
Variables, Operators, Method invocations that evaluate to a value. In Apex, an expression is always one of the Abstract Method MUST be overridden in the Class that implements the Interface
following types: A literal expression: 1 + 1 3. Interface / Implements: An Interface does NOT get extended, but it gets Implemented. An
o A new sObject, Apex object, list, set, or map: List <Account> myAcc = New List<Account>(); Interface contains ONLY Method Signatures. EACH Method MUST be defined (not overridden)
o Any value that can act as the left-hand of an assignment operator (L-values); Integer I, myList[3], in the Class that implements the Interface
myContact.name TOP
SOQL VS SOSL
SF Object Query Language used to search our organization’s SF data for specific information.
SF Object Search Language that provides an ability to search across multiple objects in one query. We can search text, email, and
phone fields for multiple objects, including custom objects, that we have access to in a single query in the following environments.
SOSL SOQL
We don’t know which object the data is in We know which exact object the data is in
Many objects can be searched at a time Only one object can be searched at a time.
10
Can query only on email, text or phone Can query any type of field
Can be used in classes, but not triggers Can be used in classes and triggers
DML Operation cannot be performed on search result DML Operation can be performed on query results
Returns fields Returns records
Return types: sObject, List, integer Return types: List of List of sObjects
Wildcards: * and ? Wildcards: % and _
TOP
SOQL • SOQL Relationships – sObject: Note that for Custom relationships both
• SF Object Query Language. SOQL has NO such thing as SELECT * (This directions are appended with __r. To get the Relationship Name, go to
could severely impact other tenants in our shared environments). Workbench and explore the Object
• SOQL has NO equivalent INSERT, UPDATE, or DELETE statements. Only • Selecting Parents fields from Child in SELECT: To reach a Parent field
available is the SELECT statement Just like Apex, SOQL is case insensitive. from a Child Object, the relationship query uses "dot notation": a period
• SOQL can used within our Apex code (Classes, Triggers) and Web Services separates the relationship name from the name of the field being queried
API • Selecting Child fields from Parent in SELECT: To reach Child Object fields
Syntax: SELECT one or more fields FROM one object name WHERE from a Parent Object, the relationship query uses a Subquery, to Query the
optional filter with other optional order and Limit results Child Object Relationship
Note: The field names are the API names (I am using chrome extension for it), • Filtering Parents fields from Child in WHERE: To filter against a Parent
not the label name! The fields should exist on the mentioned Object. The field field from a Child Object, the relationship query uses "dot notation”: a period
order in the SELECT statement defines the ordering separates the relationship name from the name of the field being queried
Where to write SOQL queries? Data Loader! And we can bypass the UI • Filtering using Semi-Joins with IN and Anti-Joins with NOT IN: We can
and simply type our query in the box! SF Developer Console: Can be used as use IN and NOT IN can be used for semi-joins and anti-joins when querying
your default coding editor, where we write our Apex code!, Can also be used on: ID (primary object), Reference (related object) fields
to invoke SOQL and SOSL queries. Workbench: Cloud-based tool that
accesses your SF Org, Simple and clean UI, Can also do Data Manipulation
SOSL
• In your Apex code: the real power of SOQL comes when we mix it in with • SF Object Search Language: is SF version of a text search engine, like Google
Apex! search engine. SOSL is a highly optimized way of searching records in SF
o Using Workflow Rules, we could access only the Base Record, and the across multiple sObjects that are specified in the query. Just like Apex and
Parent Record via Master-Detail only SOQL, SOSL is case insensitive
o Using Process Builder, we could access only the Base Record, and the • Returns a list of list of sObjects and it can be performed on multiple objects at
Parent and Child Records the same time
o SOQL, when included in our Apex code lets us access ANY Record in • When to use SOSL queries? Use SOSL when you don’t know which objects
SF. the data resides in, and you: Want to retrieve data or from multiple unrelated
o This includes any unrelated Record, and Organization-Level settings. objects. Don’t need to count the number of records that meet specified criteria.
Like Currency conversion, sharing, permissions, etc... Need to retrieve data only from Text, Phone or email fields
Use SOQL when we know which objects the data resides in, and we want to: • Syntax
o Retrieve data from this object or from other objects that are related to FIND string (between { } outside Apex, between ‘ ‘ in Apex)
it. [ IN NAME FIELDS | PHONE FIELDS | EMAIL FIELDS ]
o Count the number of records that meet specified criteria. [ RETURNING object ]
• WHERE Clause: comparison operators: =, !=, <, >, LIKE (% and _ (for one [ LIMIT number ]
character)), and IN / NOT IN, backslash character (\) for searching strings optional Limit and other statements
• WHERE Clause – Date and Datetime Wildcards: * (Star): List<List<sObject>> results = [FIND 'Univ*'....];
Matches zero or more characters at the middle or end of your search term.
• WHERE Clause – Logical Operators (AND, OR, NOT)
? (Question Mark): List<List<sObject>> results = [FIND ’Jo?n'....]; Matches only
• Order By: There is no control of the order of results unless you use an
one character in the middle or end of your search term
ORDER BY clause in a query. ORDER BY controls the order of the query
results by a selected field. ORDER BY is added at the end of the SOQL TOP
Query. If records are null, you can use NULLS to display the empty records
first or last. The syntax is: ORDER BY fieldOrderByList ASC | DESC NULLS
FIRST | LAST
DML (Standalone and Database Methods)
• Group By: is a way to group the returned result by a field. Useful when you • Data Manipulation Language; As we saw earlier, SOQL is used only
want to know the unique and distinct field values only, as opposed to all the to perform queries with the SELECT statement, and has no
field values. Just like Grouping by in Reports. GROUP BY can be used: equivalent insert, update, and delete statements. In the SF world, data
o Without an aggregated function to query all the distinct values (of the manipulation is handled using a set of methods known as DML.
GROUP BY field) • DML is the mechanism where we can manipulate records within the
o With an aggregated function to determine how many fields are SF database. It can do the below:
associated with another field (the GROUP BY field)
o Insert: a new record WITHOUT Id. After insertion, the Record
o GROUP BY can also be used on Parent Object fields
• Aggregate Functions: allow us to roll up and summarize the data. They show Id is automatically assigned to new records by SF
calculated results from the query. Aggregate functions are mainly used along a o Update: Updates an existing record – can only work on records
GROUP BY clause in SOQL queries: Better to include the GROUP BY field WITH Id
in the SELECT fields You can also use aggregate functions without using a o Upsert: special operation that creates new records&updates
GROUP BY. MIN, MAX, SUM and AVG; Returns the minimum, maximum records within a single statement. It uses a specified field to
value or average or sum of the values of a field specified between the () determine the presence of existing objects, or the ID field if no
o SELECT COUNT(): Must be the only element in the SELECT list.
field is specified.
The query result size field returns the number of rows. The records
field returns null. o Delete: Deletes an existing record
o SELECT COUNT(fieldname): You can include multiple o Undelete: Restores one/more existing records from the recycle
COUNT(fieldName) items in a SELECT clause bin.
The AggregateResult object in the records field returns the number of o Merge: This is another special operation that can merge up to
rows. The size field does not reflect the count three records of the same object type into one of the records. It
will then delete the other records and re-parent any related
• Return Type in Apex: List of concrete sObjects OR Single concrete sObject:
when the query returns 1 record only (a QueryException is thrown if exactly 1 records.
record is NOT returned) OR Integer: when using the count() Aggregate • We can supply a single sObject or a list of sObject to a DML
Function statement. DML follows the same rules as manipulating data using
• Variable binding in Apex: We can use any Variable in our SOQL query in the GUI: Mandatory Fields should be defined. Validation Rules
our Apex code. The only condition is to precede the variable with a semi- should be respected. A single DML statement can either have ALL
column; the records succeeded, or NONE
Integer myAmm = 100000;
List<Opportunity> opp = [SELECT Name, Amount, • Database Method: Standalone DML statement: Insert sObject or
Account.Name FROM Opportunity WHERE Amount >:myAmm Insert sObject List
];
11
DML supports Using Database class methods to manipulate
Records in SF.
The advantage of using the Database class method is that you
have access to the optional allOrNone parameter to specify
whether the operation can partially succeed. When this
parameter is set to false, if an error occurs on a partial set of
records, the successful records are committed. Errors for the
failed records are returned. Also, no exceptions are thrown with
the partial success option.
Database.insert(), Database.update(), Database.upsert(),
Database.delete(), Database.undelete(), Database.merge()
• Database Methods return type: Because some records might fail,
there should be a return. Database.SaveResult is the return of
Database.Insert and Database.Update. Database.UpsertResult… A
Database.saveResult object has 3 methods:
o getId() – returns ID of sObject trying to insert, getErrors() –
returns List<Database.Error>, isSuccess() – returns Boolean
TOP
12
Triggers Account if it has at least 1 related opportunity, and display error
• Apex Triggers are blocks of Apex code that are executed under message on the page.
certain conditions. Just like a Workflow Rule, or a Process, an Apex • Process Builder (Why not): It cannot handle before DML. It cannot
Trigger is tied to 1 Object and it waits for an event to happen before handle delete and undelete DML. An error reported In Process
it executes its code. For example, the events are like before record Builder is more generic which makes it difficult to find the origin of
insertion, after record update, after record deletion...etc. the error. It cannot update unrelated records.
• Triggers can be defined for top-level standard objects, such as TOP
Account or Contact, custom objects, and some standard child objects. Real Time Example:
• Triggers are active by default when created – no need to Activate We have an object, I have to do roll-up summary on the account, number
them of contacts are available. There is no standard way to do that. We can’t
• When to use Apex Triggers? Use triggers to perform tasks that achieve this by workflow or process builder. At that moment, we have to
can’t be done by using the point-and-click tools in the SF UI. use the Trigger solution.
If our requirement cannot be done through Workflow Rules, I have to roll-up two objects which they don’t have a master-detail
Process Builder, Approval Process, Flows...etc, use Triggers! relationship, I have to go to Trigger and Trigger will handle this situation
With Triggers, we can combine Apex code, with: SOQL to by counting the records and updating the parent record.
retrieve ANY sObject in our SF Org and DML to manipulate Why do you use the Trigger, you can also use the flow?
these sObjects Previously we used the flow, when the record is inserted or updated;
• Syntax of a trigger definition is different from a class definition’s flow worked perfectly but when the record is deleted, then none of the
syntax. A trigger definition starts with the trigger keyword. It is then tools are working. Means none of the automation tools are working. Count
followed by the name of the trigger, the on keyword, the SF object is still same when we delete the record, when we use the automation tool.
that the trigger is associated with, and finally the condition(s) under So, we should use the Trigger to handle it.
which it fires. A trigger example has the following syntax: TOP
Avoidance (Best – Practices)
• DO NOT! Assume that only 1 record will be affected
• Events: The Trigger event specifies under which circumstances this • A common development pitfall is the assumption that only 1 Record
Trigger will run. We can have 1 or more events on each Trigger will enter a Trigger • Trigger.new can have as many as 200 Records at
definition in a comma-separated list. The events can be; before once! • Up to 200 records can enter your trigger at once • Your
insert/update/delete, after insert/update/delete/undelete trigger should be designed to handle this number of Records, not just 1
o Before Trigger: Can modify Records before it is saved to database. Record
• No need for explicit DML here. • Cannot access field values that • DO NOT! Run SOQL inside For Loop
are set automatically by the system (such as ID and LastModified • One of the Governor Limits imposed of SF is the number of times you
Fields). • Can be used to update and validate the same record that can issue a SOQL query within a transaction • The max times set by
initiated the trigger before it is saved to the database. • Set "Max SF is 100 • If you exceed these 100 SOQL queries, you will get an
Salary' Position field to certain value if empty when "Position" exception: “Too many SOQL queries” • Solution: run SOQL outside
record is created; throw an error if "Max Salary" exceeds specified the for Loop, and save it in a List, then iterate through this List using
amount. a For Each Loop
o After Trigger: Executed after record is saved to database • Needs • DO NOT! Run DML inside For Loop
explicit DML to manipulate Records • Can access field values that • Another Governor Limit imposed of SF is the # of DML statements
are set automatically by the system (such as ID and LastModified (max 150) we can issue at a time within a transaction
• If we exceed these 150 DML transactions, we will get an exception •
Fields) • They are best if you want to effect changes in other related
Solution: save your result records in a List, then use DML on this list
object's records that need these system fields. • Insert an
"Interviewer" record and assign this interviewer to a "Position" as • BE AWARE of Cascading Triggers
soon as the "Position" record is inserted. Used when: • Change • When Triggers modify records, this may cause other Triggers to
execute • For example, with Rollup Summary Fields, if the child
some other object • Obtain the record's SF ID and other system
record is modified, then this will cause the Rollup Summary • Field
fields
to modify, which may run another trigger, and so on... • So, Triggers
• Context Variables: Triggers can fire when one record is inserted, or are NOT run all alone by themselves, they can cause other Triggers
when many records are inserted in bulk via the API or Apex to run based on the changes they make • The Triggers that execute
To access the record(s) that caused the trigger to fire, SF has are considered as part of the same 1 execution context for Governor
many Trigger Context Variables like limits
o Trigger.New contains the List of all the records that were inserted
in insert or update triggers. Trigger Design Best-practice
o Trigger.Old provides the old version of records before they were • DO! Logic-less Triggers and Handler Class
updated in update triggers, or a list of deleted records • The role of the Trigger is just to delegate the logic responsibilities to
o Trigger.newMap, Trigger.size (returns the total # of records in a some other Handler Class. Why? • Testing a Trigger is difficult if all
trigger invocation, both old and new). Also some variables like; of the application logic is in the trigger itself • We also can’t expose
isExecuting, isInsert, isUpdate, isDelete, isUndelete, isBefore, logic to be re-used anywhere else in our org • Writing all of our
isAfter code logic into a Trigger is going to make for a mess one day
• Using SOQL in Apex Triggers: SOQL can return: Single concrete • To sort it out, just need to create 1 Handler Class and let our 1 Trigger
delegate to it. Trigger name example: AccountTrigger,
sObject, List of concrete sObjects, Integer, Single AggregateResult,
• Handler Class name example: AccountTriggerHandler (Creating a
List <AggregateResult>. We can run SOQL in our Apex Classes and
class defined as MyObjectTriggerHandler can help to design a
Triggers to retrieve any record! SOQL code should be enclosed modular set of reusable objects which manage all the operations to be
between [ ] done by a trigger.)
• SOQL Variable Binding: We can bind variables from Apex code or • DO! One Trigger Per Object
execute Apex from our Apex code into a SOQL query that we are • With multiple Triggers for a single object, you have no way of
writing in the Apex class / Trigger. But for the variable to work, controlling their order of execution • A single Apex Trigger is all
make sure that we precede the variable with ‘:’. you need for one particular object • A single Trigger can handle all
• Trigger Exceptions are used to add restrictions on certain database possible combinations
operations, for example, preventing saving a record when a condition • DO! Context-Specific Handler Class Methods
is met. To prevent saving records in a trigger, call the addError() • Create context-specific handler methods in the Trigger Handler Class
method on the sObject in question. The addError() method throws a • In the Handler Class, create different Methods for different
fatal error inside a trigger, and prevents DML statement from Contexts • In the Trigger, call these different Methods based on the
completing. The error message is specified by the coder, is displayed Context
in the user interface and is logged. Example: prevent deletion of an • DO! Use Maps instead of Lists
13
• A Map Constructor accepts a List as an Input. • We can either • Avoid use of @future(callout) in the triggers, because if we
construct a Map from scratch or transform an existing List to a Map
use it then might be there will be chances of hitting governor
• In case of UPDATE TRIGGER, we do check Old and New limits, instead of @future, use Batch class.
Values for the field on basis of which we need to perform the • Trigger is designed to handle the bulk of record.
calculations or making changes in the database. TOP
Governor Limits
• SF runs in a multitenant shared environment, where thousands of orgs. Share the same SF Instance. Resources like CPU power,
RAM and bandwidth are all shared in the same Instance. As a result, and to protect the Instance resources, SF has implemented
Resource Usage Limits. These are called Governor Limits.
Description Synchronous Limit Asynchronous Limit
Total number of SOQL queries issued 100 200
Total number of records retrieved by SOQL queries 50,000
Total number of records retrieved by Database.getQueryLocator 10,000
Total number of SOSL queries issued 20
Total number of records retrieved by a single SOSL query 2,000
Total number of DML statements issued 150
• Force.com Platform Apex Limits. Some limits aren’t specific to an Apex transaction and are enforced by the Force.com platform like; Max # of Apex classes
scheduled concurrently (100). Max # of batch Apex jobs queued or active concurrently (5). Max # of batch Apex job start method concurrent executions (1).
Max # of batch jobs that can be submitted in a running test (5)
Best practices to avoid Governor Limits
One Trigger Per Object: A single Apex Trigger is all we need for one particular object. If we develop multiple Triggers for a single object, we have no way of
controlling the order of execution if those Triggers can run in the same contexts
Logic-less Triggers: If we write methods in our Triggers, those can’t be exposed for test purposes. We also can’t expose logic to be re-used anywhere else in
our org.
Context-Specific Handler Methods: Create context-specific handler methods in Trigger handlers
Bulkify your Code: Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.
Avoid SOQL Queries or DML statements inside FOR Loops: An individual Apex request gets a maximum of 100 SOQL queries before exceeding that
governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception
Using Collections, Streamlining Queries, and Efficient For Loops: It is important to use Apex Collections to efficiently query data and store the data in
memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits
Querying Large Data Sets - The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes
you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to
query and queryMore
Use @future Appropriately: It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex
methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found
Avoid Hardcoding IDs: When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is
essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper
data to operate against and not fail
TOP
Order of Execution
• There is a particular order in which events execute whenever a record is inserted or modified
• A set of rules that describe the path a record takes through all automations and the events that happen from Save to Commit
If the After Trigger modifies or create other records; • The whole Order of Execution steps run for this record • Commit and Post Commit don't run for this
record until after the initial record commit and after commit steps run
If the Workflow Rule steps update a field in the record, then Before Update Trigger> System Validation Rules>Save operation>After Update Trigger
If the Process updates a field in the same record, then Most of the Order of Execution steps run from Before Trigger to Processes and Auto-Launched Flows
If the Process and Autolaunched Flow update a field in a different record, or create a record then whole Order of Execution
steps run for this record > Commit and Post Commit don't run for this record until after the initial record commit and after commit steps run
14
If the parent record contains roll-up summary fields that are updated > whole Order of Execution steps run for this parent record > Commit and Post
Commit don't run for this record until after the initial record commit and after commit steps run
If the parent record is updated, and a grandparent record contains a roll-up summary field: The whole Order of Execution steps run for this grandparent
record > Commit and Post Commit don't run for this record until after the initial record commit and after commit steps run
TOP
Exception Handling Note: Any statements in the try block occurring after the exception are
Exceptions skipped and aren’t executed.
• In SF, a compile error is a Syntax error that won’t let you save your
code. An Exception is a non-syntax error and can be anything which • System Defined Exceptions: The exception class defines standard
interrupts the normal flow of the execution AKA Bug. An Exception exceptions and contains methods for interrogating exceptions.
is more of a Logical error, or an error that occurs when using certain DMLException (when DML operations fail), ListException,
data as opposed to others NullPointer (when we try to reference a null variable) or
• When an Exception can occur: For example, when trying to generic Exception
reference a null variable or when trying to insert a record without • Exception Methods: The Exception Class has many Methods that can
defining the mandatory fields be used with the Exception variable; getCause, getLineNumber,
• Unhandled exceptions are exceptions that the code doesn’t catch and getMessage, setMessage
this is the default in SF, They cause your whole code execution to stop • Catch Different Exception Types: We use more than 1 catch block
and exit. Any DML operations that were processed before the top catch different exceptions to give different debug messages for
exception are rolled back and not committed to the database. Get each exception type. When an Exception type is used and a Catch
logged in debug logs. End user sees an error message in the SF user block is accessed, the code will then exit the whole block, so no other
interface Catch block will run.
• Handled exceptions are exceptions that the code does catch with • Best practice is to use several catch blocks: A catch block for each
writing extra code. They are handled in a way that will NOT stop the exception type and, A final catch block that catches the generic
whole code. Instead of throwing the exception and stopping the code, Exception type and Always start from the most specific exception
handled expectation can display a code that you type. Any DML type, to the general
operations that were processed before the exception handling are • Throw statement will throw an Exception and stop the execution.
committed to the database. Any code after the exception handling Similar to the addError() Method that we saw in Trigger, but
block is processed addError() method can only be used in triggers. We can use
addError() method for only records that are available in Trigger
Context.
Try-Catch-Finally statement
• Custom Exception Class: We cannot throw the System exceptions.
• Can be used together to capture an exception and handle it gracefully
Trying to do so will result in error: “Type cannot be constructed:
without stopping the code. A Try block encloses the code where
Exception”. To create our custom exception class, extend the built-in
exception may occur. A Catch block comes immediately after the try
Exception class and make sure our class name ends with the word
block and handles the exception and takes an argument of an
Exception, such as “MyException” or “PurchaseException”. All
Exception Type variable. Can have 0 or more Catch blocks, each
exception classes extend the system-defined base class Exception, and
handling an exception type, and it will run based on the Exception
therefore, inherits all common Exception methods. Once you create
type
the custom Exception class, you can construct exceptions from it, and
Can have 0 or more Finally blocks, that is always executed at the end,
use them in Throw
that allows to clean the code. At least 1 Catch or Finally block must
be present after Try
TOP
• With Sharing; In Apex Class definition, User mode is
Implemented using the with sharing keyword before the
Security in Apex (System/User Mode,
keyword class in class declaration. Class declared as with
With/Without Sharing, Access)
sharing can call code that operates as without sharing. Using
System Mode vs. User Mode with sharing keyword: SOQL and SOSL queries may return
In SF, the Org. data in the database is accessed in one of 2 modes: fewer rows and DML operation may fail due to insufficient
• System Mode: Allows the code to access all records in the privileges for the current user.
database, even if the user executing the code doesn’t have Classes inherit this setting from a parent class when one class
access to. Ignores the sharing model. System record access extends or implements another. Inner classes do not inherit
(Triggers, Custom Web Services, Test Classes). In the sharing setting from their container class.
conclusion, all Apex code run in system mode, ignoring
user's permissions.
• User Mode: Limits code access to only records that the user
executing the code has access to, just like when the user Apex Class Access
• We can specify which users can execute methods in a particular top-
access records using the UI. Respects the sharing model.
level class based on their user profile or permission sets.
User record access (Anonymous Block). In conclusion, Only • We can only set security on Apex classes, not on triggers.
exception that run in User Mode: Execute Anonymous Block Set Apex class security from the Class List page: Setup - Apex
and Standard controllers. Classes – next to class name, click security – add/remove allowed
Profiles
Set Apex class security from the Class Detail page: Setup - Apex
With Sharing vs. Without Sharing Classes – select class – security – add/remove allowed Profiles
• Use the With or Without Sharing keywords on a class to Set Apex class security from a Permission Set: select a Permission
specify whether or not to enforce sharing rules when the Set, Click Apex Class Access, Edit, Select the Apex classes that you
Class executes. want to enable from the Available Apex Classes list and click Add,
• If with or without sharing are not mentioned with class, then or remove classes that you want to disable.
Set Apex class security from a Profile: select a Profile, In the Apex
the default is "Without sharing".
Class Access page or related list, click Edit, Select the Apex classes
• Without Sharing; In Apex Class definition, System mode is that you want to enable from the Available Apex Classes list and
implemented using the without sharing keyword before the click Add, or remove classes that you want to disable
keyword class in class declaration
Roles are one of the ways we can control access to records.
15
● We can assign permission on the role with (organizational wide default, OWD). ● A profile controls “Object permissions, Field permissions, User permissions, Tab
Record-level access (sharing) , hierarchy of the company who works under which settings, App settings, Apex class access, Visualforce page access, Page layouts,
role. Based on the hierarchy, access of the records transferred, like manager can give Record Types, Login hours & Login IP ranges.
some access to the teammates. Roles are designed to increase data visibility, to open ● Object-level security: Create, Read, Edit, Delete. System administrators will have
up access to SF records. You will have a baseline visibility set for each object in ‘View all’ and ‘Modify all’ ability on objects also.
your org, known as the ‘org wide default’. Golden rule: the ‘org wide default’ All metadata permissions are managed inside the profile. In addition to objects,
should be set to the most restrictive level. SF permissions work by opening up profiles also control: Field-level security (which fields are visible or editable), page
access, not by locking them down. So, start with the strictest in mind. It is not layouts, record types.
mandatory that a user should have a role Permission set: Only for enhance not decrease the permission. Permission sets could be
considered for particular profiles. They offer flexibility in how you add certain permissions
Profiles help determine record privileges. Assuming the User can see the record, Profiles determine (objects, field-level security, page layouts, record types, apps, tabs) to certain users – almost like
what the User can do, view or edit on that record. Profiles control other system privileges as well you are tagging an individual user. In order to grant a very specific ability to a user, you obviously
(mass email, export data, etc). Defining profile for a user is mandatory don’t want to create a whole new profile.
TOP
Security vulnerabilities
TOP
Invocable Methods, Variables, APEX from a • Variables: Used for Variable and not Methods. Used in user-
Process, from a Flow defined custom classes that are used by Invocable methods.
• Invocable Methods: Not any method can be called by a The @InvocableVariable annotation is used to identify
Process or a Flow. Use the @InvocableMethod annotation variables used by invocable methods in custom classes. It is
to identify methods that can be run as invocable actions. If a used to identify a variable that is used as an input or output
flow invokes Apex, the running user must have the parameter for an InvocableMethod method’s invocable
corresponding Apex class security set in their user profile or action.. This way, we make these variables available in the
permission set. Flow or the Process
Considerations: An Invocable Method is tagged by the
@InvocableMethod annotation. An invocable method
must be static and public or global, and its class must Considerations: Other annotations can’t be used with the
be an outer class. Only one method in a class can have InvocableVariable annotation. Only global and
the @InvocableMethod annotation. Other annotations public variables can be invocable variables. The data
can’t be used with the @InvocableMethod annotation type of the invocable variable must be A primitive,
Parameter and Return: There can be at most one input An sObject, either the generic sObject or a specific
parameter and and if the return type is not Null, the data sObject, A list or a list of lists of primitives, sObjects,
type returned by the method must be one of the objects created from Apex classes, or collections
following: Modifiers: All modifiers are optional. The
A list or a list of lists of a primitive data type: InvocableVariable annotation supports the modifiers
List<Id> / List<List<Id>> shown in this example.
A list or a list of lists of a specific sObject type: @InvocableVariable(label='yourLabel'
List<Account> / (List<List< Account >> description='yourDescription' required=(true | false))
A list or a list of lists of the generic sObject type:
List<sObject> / (List<List<sObject>> • Invoking Apex from a Process: Apex code can be invoked
A list of a user-defined type, containing variables of from a Process Builder to add advanced functionality to a
the supported types above or user-defined Apex types Process. Invocable methods must be used to invoke the
Modifiers: All modifiers are optional. The methods in an Apex class. When configuring the process, an
InvocableMethod annotation supports the Apex action can be created and added to the process to
modifiers shown in this example. invoke Apex code. The user whose action triggers the
@InvocableMethod(label='yourLabel' process also executes the Apex class
description='yourDescription’
category=‘Uncategorized’) • Invoking Apex from a Flow: Flows use the Action element
The label which appears as the action name in Flow Builder
to call Apex. 2 options to make an Apex class available as an
and in Process Builder.
The description which appears as the action description in Action element for a flow: Invocable Method or
Flow Builder Process.Plugin interface. @InvocableMethod annotation
The category appears as the action category in Flow provides more functionality.
Builder.
16
SF recommends using the @InvocableMethod method, a Flow interview should be initiated with the
annotation instead of the Process.Plugin interface parameter. The getVariableValue method can be used to
because bulk operations are not supported and also return the value of the specified flow variable. The start
Collection, sObject and time are not supported. method does not have a return type while the
getVariableValue method has the return type of Object. A
• Invoking a Flow from Apex: The start method of the flow needs to be active to allow users to invoke it from Apex.
‘Flow.Interview’ class can be used to launch an autolaunched
flow or user provisioning flow from Apex. Before the start
TOP
Platform Events Platform Event: It looks just like a Custom Object. It can be
• Point to point integration presents lots of challenges. Tight created from Setup – Custom Events. Standard fields with the ReplayId
coupled environment because every system is talking to other field instead of Id. We can add Custom Fields and we can attach Triggers,
Processes and Flows to each Event
system independently
Platform Event considerations: A Platform Event API name ends
with "__e" rather than the "__c" for Custom Objects. We can control a
Platform Event permission on Profile and Permission Sets just like any
custom object. We can’t query Platform Events through SOQL or SOSL.
We can’t use Platform Events in reports, list views, and search. Platform
events don’t have an associated tab. Only after insert Triggers are
supported with Platform Events. Custom Events are immutable: once an
event has been published you can’t update, delete or query it. Platform
events are executed under the “Automated Process entity”, so you have set
Automated Process in debug log. We can see all the Subscriptions and
Triggers of a Platform Event under the “Subscription” and “Triggers” lists
on the Platform Event page
How does Platform Event Work?
- The first step is to create the Platform Event with its custom
Event-Driven Architecture fields > Go to Setup – Platform Events – New Platform Event > Create the Platform
Event > Create 5 custom fields > With Platform Events, you are limited to: Checbox,
Date, Date/Time, Number, Text, Text Area > Standard field Replay ID is created and
used to identify and replay the Event if needed
- The second step is to Publish it by creating a Process or a Trigger from
the source Object. - An Event can be published with: Process Builder, Flow, Trigger,
REST / SOAP API
- Finally, Subscribe to the Platform Events. Any service that subscribes to this
Platform Event will be notified with the field values of the Event An Event can be
Subscribed to with: Process Builder, Flow, Trigger, CometD
TOP
------------------------------------------------
User Interface
Visualforce (Standard and Custom Controller, <apex:selectCheckboxes> or <apex:selectList> and also
Web Content) <support:clickToDial number=”” entityId=”” params=””>
When we have to design VF pages: If the Standard SF UI cannot • To display SF Data values into VF: A Controller must be
fulfill the Business Requirements need. In the same UI, user wants used by the VF page. The controller will be responsible of
to enter account and contact record, it means we have to work on pulling Data from the Database and pushing Data into the
multiple objects at the same time and that is not possible any of Database. The controller can contain the logic to be executed
the standard solution. We have to use VF solution with custom when a button is clicked.
UI. The solution might be the aura development also. Display
more than 2 columns in the UI or Display data from different Standard Controller
unrelated objects. • For example, if we are designing VF page for the particular
VF page is similar to a standard Web page, but includes object like Account, Account is a Standard Controller for the
powerful features to access, display, and update your VF page. Account inherits the functions. Suppose that I want
organization's data. to inherit the Save and Delete functionality, I want to use the
VF is a framework that allows developers to build VF page inside on it. <apex:page
sophisticated, custom UI that can be hosted natively on the standardardController=“Account”> Then adding following
Lightning platform. markup Name: {! Account.name }
VF consists of a tag-based markup lang. that gives developers a • Standard controllers are same things as the object name,
powerful way of building applications and customizing whichever we are designing VF page, that object will become
the SF UI. the standard controller for that object. Standard controllers run
With VF we can: Build wizards and other multistep processes. in User mode (With Sharing) by default, so the user who runs
Create our own custom flow control through an application. a Visualforce page with a Standard Controller can only have
• Syntax: VF is a markup language based on tags. VF tags all access to the Records he is allowed to
begin with “apex:” prefix. All VF pages are enclosed within • Standard Behavior: All button actions are already defined in
<apex:page> opening and </apex:page> closing tags. VF the Standard Controller like Edit, Save, Cancel
supports HTML and VF tags. VF tags have attributes that • Standard Data: with a single record, or multiple records of
define specific tag characteristics. the same Object
• Components: <apex:pageBlock> Renders as a section; <apex:
pageBlockSection> Renders as a collapsible section, Data from a Single Record
17
• When the page is loaded, and the <apex:page> component is activated, it o In the below example, the variable userinput in your
activates a standard controller for the account object. - The standard Apex class will store the value entered by the user
controller sees that there’s an ID parameter in the URL, and searches for and
retrieves the matching account record.
• The standard controller takes the record and puts it in a variable that it makes
available to the page. The variable has the same name as the standard
controller’s sObject: Account. It’s an object variable and contains all of the
fields available on the Account sObject.
• The four Visualforce expressions all reference the Account variable. They TOP
use “dot notation” to access individual fields within the Account variable. So,
{! Account.Name } gets the name of the account, and so on.
Controller Extension
• To reach the parent record we use dot annotation Account owner: {! • For a page using Standard or Custom Controller, but
Account.Owner.Name } <br/> requires some extra Data access, or Behaviors, we use
• To display full record; <apex:detail> Controller Extension:
• <apex:outputField> to display individual fields Value from a record. o Custom Data: we can fetch any data other than the ones in
<apex:outputField> only outputs the field’s value. But when you wrap it in
the Main Controller extending the Extension
<apex:pageBlock> and <apex:pageBlockSection> components, its behavior
changes quite a bit: the field label is now also displayed! o Custom behavior: we can create any action button other
than the ones in the Main Controller extending the
Extension
o Multiple controller extensions can be defined for a single
page through a comma-separated list.
How to create them? Create new Apex Class containing a
constructor that takes a single argument of type
Data from Standard List Controller ApexPages.StandardController or CustornControllerName, where
• <apex:pageBlockTable> is an iteration component that generates a table CustomControllerName is the name of a custom controller you
of data, complete with platform styling. Here’s what’s going on in the want to extend.
table markup.
How to reference them? The extension is associated with the
• The value attribute of <apex:pageBlockTable> is set to the variable
loaded by the standard list controller, {! contacts }. This is the list of
page using the extensions attribute of the <apexpage>component
records that <apex:pageBlockTable> will work with. Needs you to Apex? A little yes. We need to code all the extra
Custom Controller things we require in an Extension
• A custom controller is a class written in Apex that implements Button action defined? Depends on the Main Controller
all of a page’s logic, without leveraging a standard controller. Standard/Custom Objects? Custom Controllers are Unrelated to
If we use a custom controller, we can define new navigation an Object
elements or behaviors, but we must also reimplement any
functionality that was already provided in a standard When to use Controller Extension? If we want to keep the use
controller. Like other Apex classes, custom controllers execute of a specific Controller, but extend it to provide additional
entirely in system mode, in which the object and field-level functionality, like access extra data and perform extra behavior.
permissions of the current user are ignored. We can specify Controller extension can be used with a Standard Controller, or a
whether a user can execute methods in a custom controller Custom Controller. We can use multiple Controller Extension on a
based on the user’s profile. Custom controllers can be used to: single Standard or Custom Controller. Note that Controller
Retrieve a list of items from more than 1 Object to be Extensions Security depends on the extending Controller (Main
displayed * Make a callout to an external web service or Controller) *If Main Controller is Standard – Controller Extension
*Validate and insert data With Custom Controller, we can runs in User Mode (User Permission and Visibility imposed)
choose the Sharing Model: with sharing or without sharing *If Main Controller is Custom – Controller Extension runs in
(default) System Mode (No user Permission and Visibility imposed)
Example: Records from both Account and Opportunity objects *You can change this by specifying with sharing keywords in the
• Methods: Getter Methods: Getter methods pull data out of class definition
your controller onto your page. We should prefix our getters
with “get”: getMethodName(). Variable will be referenced in Remote actions:
the Visualforce page using the {!MethodName} notation
Setter Methods: Setter methods let us submit values from the Security: Like other Apex classes, controller extensions run in
page(view) back up to our controller. We should prefix our system mode. So, the current user's credentials are not used to
setters with “set”: setMethodName(). Variable will be execute controller logic, and the user's permissions and field-level
referenced in the Visualforce page using the {! MethodName} security do not apply. However, if a controller extension extends a
notation standard controller, the logic from the standard controller does not
Action Methods: no concept of getting or setting, for example. execute in system mode. Instead, it executes in user mode, in
Move to another page, update data, send an email which the permissions, field-level security, and sharing rules of
the current user apply. We can choose whether a controller
• Alternate Get/Set – Properties: Apex properties are kind of a
extension respects a user's organization-wide defaults, role
combination of a variable with getter and setter methods, with
hierarchy, and sharing rules by using the with sharing keywords
a syntax that groups them together more clearly. A simple
in the class definition.
property that references a custom object might be declared like
this.
Web Content
Example:
• To upload Contents to a VF page, Static Resources are
o let's assume we want to display a textbox in our
used! Static resources allow us to upload content that we
Visualforce page. When the user enters some value in this
can reference in a VF page and Static resources are
textbox and clicks on a button we want the value entered
referenced using the $Resource global variable. These
by the user to be in our Apex class (basically our
Content include: Archives (such as .zip and .jar files) tag:
controller)
<apex:image url=””>, Images <apex:image url=””>, CSS
18
fies <apex:stylesheet value=””>, Javascripts in the page layout. We can use or add this Visualforce
<apex:includescript value=””> page by modifying the page layout.
• But first, to be able to reference Resources in VF, they Overriding Standard Buttons or Links: Replace built-in
should be uploaded into SF! Build > Develop > Static functionality in SF by overriding the standard buttons and
Resources links to go to a Visualforce page instead of the normal
page.
Incorporate Visualforce Pages into Force.com New Custom Buttons or Links: Instead of overriding the
standard features of our SF pages, we can add new features
From a Tab: Add custom tabs to our organization that display a to them. Add custom links and buttons that go to VF pages
VF page to any object’s page layout.
Within a Standard Page Layout: Extend our page layouts by Link Directly: Every VF page has a unique URL, so we can
embedding VF pages on them to display completely simply link to a page and share the link in other apps,
custom content on a standard page. To embed a VF page emails, embedded in documents, and so on.
into page layout, the VF page should be using the standard
controller tag referencing the same entity that will be used TOP
TOP
Lightning Components Types
• Two types: Each of these components can be configured and
customized depending on our need
o Standard Components: are available once the Lightning
Experience is enabled (Chatter Feed, Chatter Publisher,
Flow, Filter List, Recent Items, Report Chart, Rich Text,
VF)
o Custom Components: we can create their own custom
Lightning Components, or get them from the
AppExchange
Create Lightning Components
use Developer Console and note that we cannot create lighting
components from the SF UI!
o File – New – Lightning Component (Component,
Controller, Helper, Style, Documentation, Renderer,
Design, Svg)
o Type the Component code between the tags
<aura:component> and </aura:component>
19
o Note: to make our Components viewable from the owner and parent components can call JavaScript methods on child
components.
Lightning App Builder, use the tag:
<aura:component @track : Fields are reactive. If a field’s value changes, and the field is used
implements="flexipage:availableForAllPageTypes" in a template or in a getter of a property that’s used in a template, the
access="global"> component rerenders and displays the new value.
Preview Lightning Components There is one use case for @track. When a field contains an object or an
array, there’s a limit to the depth of changes that are tracked. To tell the
use an App: framework to observe changes to the properties of an object or to the
o File – New – Lightning Application (Application, elements of an array, decorate the field with @track.
Controller, Helper, Style, Documentation, Renderer, @wire : To read SF data, LWC use a reactive wire service. When the wire
Svg) service provisions data, the component rerenders. Components use @wire in
o Call the Component that we just made between the tags their JavaScript class to specify a wire adapter or an Apex method.
<aura:application> and </aura:application>
TOP
o To call the Component, use the tag<c:componentname/> AURA and LWC
Compare: LWC is faster than Aura, because as it no longer
Iteration requires the user to download the JavaScript and wait for
for:each={array} the engine to compile it before rendering the component.
Use this directive to iterate over an array and render a list. It is possible to include LWC in Aura, vice-versa is not true.
for:item="currentItem" Aura are built using both HTML and JavaScript, but LWC
Use this directive to access the current item. is built directly on the Web stack.
The currentItem placeholder is an identifier that the model injects into the Disadvantages of Lightning Web Components
current scope. Overriding standard buttons like Create, Edit & View
for:index="index" Custom Actions, Global Actions, List View Actions
Use this directive to access the current item's zero-based index. Related List View Actions, Lightning Out [Beta]
Rendering LWC as PDF Page, Using LWC in Email Templates,
The index placeholder is a new identifier that the model injects into the Console APIs (Navigation Item API, Workspace API, Utility Bar
current scope. API)
Resources in a Lightning Component Chatter Action, Conversation Toolkit API
Component (.cmp); The only required resource in a bundle. Contains Omni Toolkit API, Quick Action API
markup for the component Aura Components model
Controller (.js); This file contains the client-side JS controller methods to How an individual page or component is stored on SF:
handle events fired and handled by the components. VF pages are stored on SF as a single entity, an ApexPage. When we
Helper (.js); This file contains JS functions that can be called from any use SF Extensions for VSC to copy our VF pages to our local storage
JavaScript code in a component bundle. This will be a Helper class to the to work on them, an individual Visualforce page is represented as
Controller. It will be useful when we need to reuse the same logic two files in the metadata/pages directory: ourPageName.page and
somewhere else ourPageName.page-meta.xml
Style (.css); Creates CSS Styles to the particular components o Complex component might look like this:
Documentation (.auradoc); By adding documentation, we can easily
determine the usage of the particular component. It's similar to comment
Renderer (.js); Client-side renderer to override default rendering for a
component
Design (.design); File required for components used in Lightning App
Builder, Lightning Pages, or Community Builder
SVG (.svg); Custom icon resource for components used ii the Lightning
App Builder or Community
TOP
Resources in Lightning Web Component
Similar to an AURA component, the main contents of a LWC are also
html, javascript. There are optional content like css. But then in
addition to these for LWC, an xml configuration file is also included Aura components apps are very different. There’s only one
which defines the metadata values for the component. So, a LWC “page” for the entire app! We call these “single-page
component: applications” (SPAs). Instead of navigating from page to
HTML; Has a root tag <template> which contains your component’s page, users navigate from state to state.
HTML. When renders, the <template> tag is replaced with If we create our VF pages using JavaScript remoting and
<namespace-component-name>. Apex @RemoteAction methods, we already design our
Javascript; Import functionality declared in a module eg-lwc(the
controller code in a way that can be highly reusable for Aura
core module), we use the import statement. To allow other code to use
components. We need to update existing code.
functionality in a module, we use the export statement.
LightningElement is custom wrapper of the standard HTML element
and we extend it in the component and export. Lightning Data Service (LDS)
Configuration (Metadata) is only available with Aura components.
XML file that defines the metadata configuration values for the how do we handle related fields and multiple fields?
component eg- Components Label, Availability, Configuration Without writing any APEX code, we can do the DML
Attributes, Builder Attributes insert or update records. We also have a layout option to
CSS; To style a component. The style sheet is applied automatically.
control the fields. LDS is also giving a permission as a
TOP flexibility to do it as well.
Decorators (LWC) How do you update related field using LDS?
@api : To expose a public property, decorate a field with @api. Public I am thinking that one thing that comes to mind is we cannot
properties define the API for a component. update the related records. Lightning does not have access to it.
To expose a public method, decorate it with @api. Public methods are part We have to had like record data component somewhere to set
of a component’s API. To communicate down the containment hierarchy, that field to save it, set that field values. Maybe we can use force
record data. I am just trying to find custom solution
20
<script> />
Actions are functions we write in JavaScript and attach to UI $Lightning.use("c:HelloLWCEx <div
elements. Ladder time at last! ampleApp", function() { id="LightningComponentid" />
o First, realize that actions aren’t direct method or function $Lightning.createComponent( <script>
calls, in either Visualforce or Aura "c:helloComponentForVFLWC", $Lightning.use("c:LightExampl
components. We don’t call them, the framework invokes { }, eApp1", function() {
"LightningComponentid", $Lightning.createComponent(
them when appropriate. So far the same.
function(cmp) { "c:LightExample1",
o However, in VF our actions are methods defined on an
}); { },
Apex class. We get some language infrastructure around </script> "LightningComponentid",
our method, like instance variables, and class and </apex:page> function(cmp) {});
instance methods. });
o Aura component actions aren’t defined on a class. </script>
({myAction: function(component, event, helper) </apex:page>
{ // add code for the action },
})
Component Attributes: In the above Visualforce page, apex:includeLightning tag imports
necessary dependencies and scripts to enable Visualforce to act as
o A component attribute is declared like this:
<aura:attribute name="myAttribute"
Lightning component container.
type="Integer"/> We can use $Lightning.use() method in JavaScript to refer to Lightning
o Component attributes require, at a minimum, a name and Application which extends ltng:outApp.
a data type. (There are optional attributes for defaults and We can use $Lightning.createComponent create Lightning Component
so on.) Reference the attribute in markup using standard dynamically.
We can call $Lightning.use() multiple times on a page, but all calls must
expression syntax. {!v.myAttribute}
reference the same Lightning dependency app.
o Get and set the attribute value in our controller
TOP
JavaScript code using (surprise!) the get and set methods.
The get and set methods are functions available on the
component parameter passed into the myAction action
handler function.
TOP
Use LWC in Visualforce
LWC for Visualforce is based on Lightning Out, a powerful and flexible
feature that lets you embed LWC into almost any web page. When used
with Visualforce, some of the details become simpler. For example, you
don’t need to deal with authentication, and you don’t need to configure a
Connected App.
LWC Lightning Component
helloComponentForVFLWC.htm Lightning
l Component LightExample1
<template> <aura:component>
<lightning-card title="Use <div>
LWC in Visualforce" icon- <h1> This is lightning
name="custom:custom19"> component for visualforce
<div class="slds-m- page</h1>
around_medium"> </div>
Hello, This is LWC for </aura:component>
visualforce page
</div>
</lightning-card>
</template>
helloComponentForVFLWC.js
import { LightningElement } from
'lwc';
export default class
HelloComponentForVFLWC extends
LightningElement {}
HelloLWCExampleApp.app
Here important point is that ltng:outApp needs to be extended in app.
ltng:outApp adds SLDS resources to the page to allow our Lightning
components to be styled with the Salesforce Lightning Design System. If
we don’t want SLDS resources added to the page, we need to extend
from ltng:outAppUnstyled instead.
<aura:application <aura:application
extends="ltng:outApp" extends="ltng:outApp"
access="GLOBAL"> access="GLOBAL">
<aura:dependency <aura:dependency
resource="helloComponentForVFL resource="c:LightExample1" />
WC" /> </aura:application>
</aura:application>
HelloLWCExampleVF.page VF page LightningExampleVF1
<apex:page showHeader="false" <apex:page showHeader="false"
sidebar="false"> sidebar="false">
<apex:includeLightning /> <apex:includeLightning />
<div <apex:includeScript
id="LightningComponentid" /> value="/lightning/lightning.out.js"
21
LWC Life Cycle of Events
A lifecycle hook is a callback method triggered at a specific
phase of a component instance's lifecycle.
1. connectedCallback - Called when the element is inserted into a document With/without Sharing:
2. constructor - Called when the component is created. Use of with sharing or without sharing keywords on a class to
3. disconnectedCallback - Called when the element is removed from a specify whether sharing rules must be enforced.
document. The with sharing keyword allows to specify that the sharing
4. errorCallback - Called when component throws an error. rules for the current user are considered for the class and We have
5. render - Called when need to update the UI. but will be called before or to explicitly set this keyword for the class because Apex code runs
after connectedCallback. in system context.
Use of without sharing keywords when declaring a class to
Aura Life Cycle of Events flow
ensure that the sharing rules for the current user are not enforced.
Rendering lifecycle is as follows:
If we don't use the With/without Sharing keyword then the class
1. Init event - fire an event after component constructed but before
rendering.
will run in the System Context. In system context, Apex code has
2. render event - method is called to render the component's body. access to all objects and fields— object permissions, field-level
3. afterRender event - Method is called to enable to interact with the security, sharing rules aren't applied for the current user.
DOM tree after the framework's rendering service has inserted DOM elements.
4. render event - this preferred over creating a custom render() and * public with sharing class X {}
overriding afterRender event. * public without sharing class Y{}
* public class Z{} // Class C is a non-specified-sharing
Aura Component events vs Application class.
events Now, let's consider the following case scenarios:
1. Components events can be handled by same component or 1. class Y extends X // class B's code now executes in class
component which is present in containment hierarchy, Application A's mode, i.e. in "with sharing" mode.
event are something like radio, it will broadcast the message, and 2. class Z calls class X // called method's code in class A will
whoever subscribe that event, will get the message. execute in class A's mode, i.e. in "with sharing" mode.
2. Apart from this, other things are same in both type of event, 3. class Z extends class X // code in class C now executes in
i.e., create an lightning event, register an event, fire an event, and the parent class A's mode, i.e. in "with sharing" mode.
capture event parms, perform the action once receive the event. 4. class X calls Z // code in class C is executed in class C's
mode, i.e. in "without sharing" mode although it's sharing
LWC uses regular native JavaScript events and we would have to settings are unspecified in the class' declaration.
use Lightning Message Service or some pub/sub library to 5. class X extends Z // class A's code now executes in the
communicate beyond parent and child. parent class C's mode, i.e. in "without sharing" mode.
pubsub, is an old technique, but right now we are "Lightning If with sharing class (X) calls without sharing class (Y);
Message Service" in order to communicate between the two
then the called method(s) will be executed in the mode of the
components.
class in which they were defined, the called method(s) will
execute in without sharing mode. Because, calling a function
Lightning Message Service in a class will use the sharing mode of that class, unless it is
helps to communicate (sending information from one to another) undefined, in which case the mode stays the same.
across the DOM, we are using this service for communicating If without sharing class (Y) calls with sharing class (X);
unrelated components (which they don’t have parent child or child then called code will now be executed in the mode of the
parent relations) i.e., between the Visualforce pages, Aura class in which it was defined, in this case, in class A's mode,
components, and Lightning web components, including i.e. in "with sharing" mode.
components in a pop-out utility bar. 1st creating message channel
which is meta.xml file then 2nd for sending information from one WITH SECURITY_ENFORCED (permission to Query)
external to another external component (lwc components) This clause enables object-level or field-level security
import… from ‘lightning/messageService also need to import permissions checking for SOQL queries in Apex code,
message channel into the .js file. 3rd we need to use subscribe including subqueries and cross-object relationships.
channel method.
Lightning Locker Service (security)
1. Using Lightning message service to communicate across the Lightning Locker enhances security by isolating Lightning
DOM between VF pages, Aura components, and Lightning components that belong to one namespace from components in a
web components, including components in a pop-out utility different namespace component. And we have Lightning Locker
bar. tools help us to develop more secure code that is compatible and
2. Using platform events to connect business processes in SF runs efficiently with Lightning Locker.
and external sources through the exchange of real-time event Some Functionality provided by Locker Service:
data. It means we can use Lightning Message service only in Lightning Locker implicitly enables JavaScript strict mode.
VF pages and lightning components whereas platform events A component can only traverse the DOM and access elements
can be used with Apex, triggers, Lightning Flows, process created by a component in the same namespace.
builders and external systems. Lightning Locker analyzes the MIME types of files sent
3. Lightning Message Service is a front-end service that works in through the browser.
client-side UI, which would include popped out utility bar
LWC – Shadow DOM
item windows and parent/child iFrame windows (primarily
VF). All interactions have to originate from the same Shadow DOM is a standard that encapsulates the DOM gives
Lightning Experience application instance — i.e. same ability protect the component from being manipulated by arbitrary
browser tab. HTML, CSS, and JavaScript.
4. A lot of things can be done using platform events which It means that, if we define any CSS styles in a parent component,
cannot be done using Lightning message service. then it will not leak into its child Component.
22
TOP
Testing System Assert Methods
Testing Requirement and Framework • We still did not compare the actual result with the
• It is done to: Make sure that there are no errors + Make sure expected result! to verify as many possible scenarios
that the expected output is working as expected as per the with positive & negative test case
code specs + Be able to deploy into the Production
environment! We cannot deploy our code to Production
unless tested!
• Testing can be performed:
o Manually through the User Interface: important but
testing through the user interface is prone to errors and will
not catch all of the use cases for our application.
o Automatically through Unit Tests: special classes and
methods that are made for testing only, and that automate
the testing procedure: Unit tests are class methods that Test.startTest and Test.stopTest System
verify whether a particular piece of code is working Methods
properly. • Test.startTest and Test.stopTest, are system static methods
• In SF, Testing is REQUIRED for Deployment to Production provided by Apex
environment! • These methods will separate the Governor Limits and will
give a new fresh Governor Limit set right before Test
Testing Requirement for Deployment execution
• Apex code can only be written in a sandbox environment or a Test.startTest
Developer org, not in production • Marks the point in your code when your test begins
• After being developed in a Sandbox or Developer • Used in conjunction with the stopTest method
environment, Apex code: Can be deployed to a production • Each test method is allowed to call it only once
org and Can be made into packages and distributed via the • Code before this method should be used to initialize
AppExchange. In order to be able to deploy Apex to variables, populate data structures etc...
Production, or to the AppExchange: • After you call this method, you get a fresh set of governor
o At least 75% of our entire SF Org. Apex code must be limits for the remainder of the test until you call
covered by Unit Tests Test.stopTest
When deploying to Production, each Unit Test in our Test.stopTest
Org, is executed! • Marks the point in your code when your test ends
Calls to System.debug are not counted as part of Apex • Used in conjunction with the startTest method
code coverage • Each test method is allowed to call it only once
Test methods and test classes are not counted as part of
Apex code coverage
o Each one of those tests must pass. Each trigger must have
some coverage (%1). All classes and triggers must compile Unit Test BEST PRACTICES
successfully. • Aim to cover 100% Apex code lines with your Unit Tests.
Remember, only 75% is required, but aim for 100%
Testing Framework • Although it is not needed for Deployment, Use the System
• There are many ways to execute Unit Tests: Via the Setup Assert Class Methods to compare the output of your Methods
with the expected output. Using the System Assert Class
Page: Apex Test Execution page, Apex Classes page list –
Methods, try to verify both positive and negative test
Run All Tests, Specific Apex Class – Run a specific Test or
scenario
Via the Developer Console or Via Force.com IDE or Other
IDEs like MavensMate • Use startTest and stopTest methods to avoid Governor
Limits while testing actual code of functionality. And note
that all test data should be created outside and prior to calling
Unit Test these methods.
• Unit test refers to a piece of code that tests a particular unit of • If the class is Private and we are not able to access, we just
Apex code and its functionality. need to use @testVisible annotation.
• They are defined as methods in test classes which execute • Writing the test class for trigger we just use the DML and 1%
functionalities written in Apex Triggers and Apex Classes coverage is enough.
• Are Methods contained in separate Classes called Test • VSC: SFDX: Invoke Apex Tests > then choose the test class
Classes which are specifically created for that purpose name or run all
• Don’t commit any data to the database and Don’t send any TOP
emails
• Are always flagged with keyword testMethod or @isTest
annotation at the method definition level
• Must always be defined in a test class. This test class should
be annotated with @isTest annotation
• Are always defined as static methods
• Test methods take no arguments
• Example, if we want to test if the Account before update
Trigger succeeds, we would create an Account!
23
Test Data • Creating Test Data by Uploading Test Data into Static
• Test Methods need Data to function and the Data (SF Resource and loading it from the Test Class. This method
records) that is created in test methods aren’t committed to allows you to load data in a test class without writing much
the database. code. Using the Test.loadData() method, developer can
• They’re rolled back when the test finishes execution. This populate data in the test methods. Test.loadData() method
rollback behavior is handy for testing because we don’t have returns a list of sObjects that corresponds to each record
to clean up our test data after the test executes. inserted
• By default, Apex tests don’t have access to pre-existing data Steps required: Create data you want to load in a .csv file.
in the org, except for access to setup and metadata objects, Create a static resource and upload the .csv file in it: setup –
such as the User or Profile objects. static resources – New – Name it 'testAccounts' – pick csv
• Creating test data makes our tests more robust and prevents file – Save. Call Test.loadData in your test method, and
failures that are caused by missing or changed data in the org. assign it to a List of sObjects:
We can create test data to be used by the Test Class List<sObject> ls = Test.loadData(Account.sObjectType,
• Created Test Data by Separate Method in the test class. 'testAccounts');
This method is NOT annotated with the @isTest annotation Call Test.loadData in a test method to populate the test accounts
or testMethod keyword. Test Class using an internal Method TOP
to generate data.
• Creating Test Data by Using a Factory Class: The Test
Class can call a Method that is not within it to generate data. Invoking Apex in Execute Anonymous vs. Unit
This class is called a Factory Class. A Factory Class as its Tests
name implies is used to generate data: It should be in the Methods of Invoking Apex: Database Trigger, Anonymous
Public or global scope to be visible to other test classes. It Apex, Asynchronous Apex, Web Services, Email Services, VF or
should be defined with the @isTest annotation therefore, Lightning Pages
they are excluded from the organization code size limit. It
can be called by test methods but not by non-test code. The
methods in the public test utility class are defined the same
way methods are in non-test classes. The methods can take
parameters and can return a value
TOP
Asynchronous Apex (Future, Batch, full Salesforce user license or Force.com App Subscription user license, per 24 hours. This
is an organization-wide limit. Chatter Only,Chatter customer users, Customer Portal User,
Queueable) and partner portal User licenses aren’t included in this limit calculation.
When to go Asynchronous: Processing a very large number
of records or Making callouts to external web services or Batch or Scheduled Apex
Creating a better and faster user experience o if we need to process a large number of records. For
Future Methods example, if we want to clean up or archive up to 50
o In situations where we need to make a callout to a web million records, the batchable interface is our answer.
service or want to offload simple processing to an We can even schedule our batches to run at a particular
asynchronous task time.
Changing a method from synchronous to asynchronous o To use it, our class implements the Database.Batchable
just add the @future annotation to our method. For interface. We also define start(), execute(), and finish()
example, to create a method for performing a web methods. We can then invoke a batch class using the
service callout, we could do something like this: Database.executeBatch method.
@future(callout=true)
o Limitations o Batchable Limitations
We can’t track execution because no Apex job ID is Troubleshooting can be troublesome.
returned. Jobs are queued and subject to server
Parameters must be primitive data types, arrays of availability, which can sometimes take longer
primitive data types, or collections of primitive data types. than anticipated.
Future methods can’t take objects as arguments.
We can’t chain future methods and have one call another.
Future methods must be static methods and can only return
a void type.
CALLOUT FROM TRIGGER
We can invoke callouts from triggers by encapsulating the callouts in @future methods.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To
add an annotation to a method, specify it immediately before the method or class definition.
However, this scenario will work if your required operation can be performed in an
asynchronous call as the @future method works asynchronously.
Also, there is a Governor Limit associated with the @future methods:
Total number of SOQL queries issued for future methods : 200 static void myFutureMethod(Set<Id> ids
Total heap size for future methods : 12 MB
Total number of methods with the future annotation allowed per Apex invocation : 50
Salesforce also imposes a limit on the number of asynchronous method invocations( like Queueable Apex
Batch Apex, Queueable Apex, Scheduled Apex, and future methods): 200 method calls per
24
o Queueable Apex provides the following orgs. We can add components with a Change Set, but we
benefits to future methods: Non-primitive can’t delete them. We must use another way to delete
types, Monitoring, Chaining jobs components, typically manually.
TOP 2- Deploying using the Force.com IDE
Debug and Deployment Tools 3- Deploying using Packages
Monitor and Access Debug Logs TOP
Debug Log
• A debug log records database operation, system processes, and errors SF Environments
that occur when executing a transaction or while running Unit test
Environments
• A debug log helps in debugging issues related to:
• Broadly speaking, there are three types of environments:
Database changes, HTTP callouts, APEX errors,
o Production Environments - SF.com environments that
Workflow rules, Assignment rules, Approval process,
Validation rules have active paying users accessing business critical data
o Development Environments - SF.com environments
• Debug Log: Can be viewed in the Setup Page (Set trace
flag>Start and Exp Date>Debug level (None, Error, Warn, where you can extend, integrate and develop on
info, Fine, Finer…), Developer Console and Force.com IDE, Force.com without affecting your production
Can be filtered as they are generated to get specific info in the environments – Built on a Sandbox!
log, Contain a customizable level of info, Have size limits: 2 o Test Environments - These can be Production or
MB info per each log and 50 MB debug log per org Development Environments specifically used for testing
TOP application functionality before deploying to production
or releasing to customers – Built on a Sandbox!
Developer Console, Workbench and Force.com
IDE SF Application Lifecycle Milestones
• A typical SF App Lifecycle include the following milestones:
o Discovery: get the overall application requirement,
features, testing, integration, import from the key
stakeholders
o Analysis: documentation created based on the Discovery
phase
o Build: create the metadata in the Sandbox
o Testing: test the application to make sure that all Use
Cases are covered
o Deployment: getting the application installed into
Production, Live environment
TOP
Deploying Metadata
• Metadata is the data (configuration and attributes) that defines our Org
• Deploying Metadata is moving it from an org to another org
• Remember, a Sandbox is a totally separate org than a • For larger and more complex projects, several
Production environment development and test environment orgs are needed, such
1-Deploying using Change Sets as:
• A Change Set is a bundle of metadata components that make o Multiple development environment for each
up an App or piece of functionality developer
• The easiest way to move changes between a sandbox and a o QA environment
production environment is with a Change Set, they are o UAT: User Acceptance Testing
accessible from the SF Setup Page, and allows metadata o Staging
migration between related SF orgs o Production
• Deploying using Change Sets is easy to use, allowing us to
select components and find dependencies.
• Because everything happens in the cloud, we don’t need to TOP
bring files to a local file system.
• We can also reuse a Change Set, or clone it and make minor
changes
• After a change set is locked, we can deploy to all connected
environments, secure in the knowledge that nothing can
change.
• Change Sets Drawbacks: We can move metadata only
between the related orgs. We can’t move changes between
two independent Production orgs or Developer Editions
25
OTHER QUESTIONS SOAP API we just have to download the enterprise WSDL file to
Business processes (SFDC configuration) our external system, after that we just need to update username,
Multiple business processes allow us to track separate sales, password and the secret key
support, and lead lifecycles. We just need to focus on the objects which we have to get the
A sales, support or lead process is assigned to a record type. The information and for getting the information platform events,
record type determines the user profiles that are associated with the whenever what happened in the SF, it will trigger and capture that
business process. our external system. Whenever we receive any information from
Lead Processes – We capture and process the lead and do the platform event, we just execute that our integration.
conversion of the lead then opportunity will get created. When the SOAP isn’t an option for accessing the Bulk or Chatter
opportunity gets created then our sales process will gonna start APIs - they are only exposed as REST calls
Sales Processes – who will work on that, sales are coming to
active and opportunity is qualifying or not etc., these all things Real-time scenario:
come up when the product get sold then support process will start I have approval steps. Whenever the record is approved,
Support Processes – working with the case Status field. It also I have to make a sync (send) with that my third-party system. It
come with the record type. If the process changes from one step to means we are inserting the record into the legacy system. That
another it changes the record type. Customer care, agent support system will store the record and as a response, it will send me the
etc. If they solve the case at that moment, they will close the case legacy number ID which I need to store it back. Whenever
right away, if they did not solve the issue then they push it, then something changes, this external id will help us to make the sync
record type and stage will change. It will be assigned to other between the legacy system and the SF.
person, so they are going to solve that case.
TOP How did you implement real-time sync?
SF to legacy system. whenever record changes by the
trigger I implemented asynchronous method for the real-time sync
Record types
up to the legacy system. Whenever the record is updated, trigger
It is just whenever we have a situation that we need to change the
called the asynchronous APEX and this asynchronous APEX
page layout or change the picklist values according to the profile
make a sync to the external system.
of the user. At that time, we take a help of a record type. Because
record types have flexibility and functionality like we can choose
What is the asynchronous APEX and which one u used?
different page layouts according to the record types. Also helps us
Feature and Batch method. We can use only 50 trigger
for sales process or support process like different sales process has
callouts with feature method.
different records then they should have different page layout and
Batch: to make a callout, we need to implement the
different picklist values.
method into the Batch method is Database.callout, so we can
make a callout to the external system and similarly if we are using
As a recap, record types allow you to offer different business
the feature method, we have to use callout = true for making a
processes, picklist values, and page layouts to different users
request from the external system.
based on their profiles. Record types can be used in various ways,
Are you also guys using sync methods?
for example:
- A record type can be created each user separately for a
Considerations for calling external system
specific object.
What is the API LIMITs we need to fetch out…
- A manager can have different picklist value, page layout
Whenever we are making request from the external to
for the record than an employee.
the inside the system, might be we have reached the API LIMITs.
As always, SF developer limits apply. For example,
TOP
depending upon our license, we may not be able to place
more than 15k calls a day.
Integration with SF (REST and SOAP API)
Callout allows us to connect to 3rd party web services such as
REST includes that our connected app and client secrets, Google, Amazon, Facebook, and any other external web service.
username, password, secret key. - via SOAP and REST API
It is simple to use with nearly all platform languages & - via APEX class
technologies. A JS API (“JavaScript REST Toolkit”) enables - manual thing
client web applications to place direct calls to SF (i.e., no same
- can send multiple records in a single transaction
origin issue). Can support XML or JSON protocols.
- supported Sync & Async requests
SF REST API Integration is mainly focused around sending
data from your application and fetching data from SF. The main Experience REST API reporting purpose:
thing is that our application is having the customer data which
we want to send it to SF, a nd we want to retrieve the customer Company had their legacy system and whenever we
data which is in SF for that SF REST API integration flows 3 create/update a customer in legacy system, we want to
things they are- create/update that record as an ‘Account’ in SF. So what we
● Allows the user of our app to access and transfer their SF need to do to accomplish this is to write an ‘AFTER INSERT’
data, trigger in legacy system database. The trigger will make a
● User will push data from application to SF, REST API call to SF and will insert/update the record in the
● Finally allows the user to retrieve SF data within the app. ‘Account’ object in SF.
26
1- We need to get our Security Token if we need (If you have 2. Decision-making
specified the ‘Login IP Ranges’ at the profile level, then you Schedule a kick-off call with the right people to review the
will not see this option.) > Reset security token information gathered during pre-planning. During this phase,
2- Create a connected app via App Manager on setup menu with research development costs and ask how software updates and
connected API name is POSTMAN upgrades may affect integration.
a. Check enable OAuth settings 3. Execution
b. Specify callback url like localhost:8080 Document test scenarios to use in a sandbox-like environment. Have
c. Full access from available OAuth scope and save all parties complete their testing? Once done, execute the integration
d. We will get Consumer Key and Secret in production and address problems by following the protocols
We need to edit policies by choosing ‘Admin approved users created during pre-planning.
are pre-authorized’ Organizations that address all of the considerations and dodge the
3- We need to give access by selecting the Profile of the common mistakes boost their chances of SF integration success. A
user who will be connecting through REST API well-planned integration saves time and money and reduces errors.
4- To connect to SF from Postman, you need to prepare the Furthermore, data will be clean and transfer properly.
connection string as per following format
https://login.SF.com/services/ MuleSoft has been part of the SF family for over a year. During
oauth2/token?grant_type=password& that time, we’ve been helping companies achieve digital
client_id=<client_id>&client_secret=< transformation by easily connecting all their business systems. So,
client_secret>&username=<username>& what does MuleSoft do? Let’s explore the powerful world
password=<password><security_token> of integration.
5- POSTMAN > create a request, select a method (POST),
paste our connection string and SEND and we logged on What is SF integration?
to SF SF integration is the process of connecting SF CRM and
a. We can execute a SOQL Query in SF through Cloud instances to each other or to other enterprise systems,
REST API. The URI for the REST Query is such as ERP or SaaS applications. With API-led integration, SF
https://<instance_url>/services/ data can fuel analytics, provide customers with better services,
data/v50.0/query?q=<SOQL Query> reduce inefficiencies, and provide insights for decision making.
b. Once we have response returned by the API, we can
process the response in whatever way we want. E.g. So, what does MuleSoft do?
if we are using Java to make API calls, use Java Customers expect connected experiences. They don’t want to see
libraries and methods to process the JSON response the seams where your systems and departments meet. MuleSoft
returned by the API brings this together by helping organizations change and innovate
c. We can create a record (POST) faster by making it easy to connect any application, data, and
https://<instance_url>/services/dat device with APIs — Application Programming Interfaces. APIs
a/v50.0/sobjects/<Object API Name> are messengers that take requests and tell a system what a user
d. We can update a record (PATCH) … wants it to do, then returns the response back to that user.
sobjects/<Object API Name>/< SF MuleSoft makes it easy to unify data to deliver a single view of
record Id>
the customer, automate business processes, and build connected
e. We can delete a record (DELETE) … experiences. By using a modern API-led approach,
sobjects/<Object API Name>/< SF
each integration becomes a reusable building block. This process
record Id>
that optimizes a reusable process enables organizations to
f. To retrieve resource metadata (HEAD) accelerate IT delivery, increase organizational agility, and deliver
TOP innovation at scale.
Integration with 3rd party (ANYPOINT)
Mulesoft (doing integration) story Informatica
- Have u ever realized best practices doing integration? Build smarter customer relationships
We had to first before using data loader export the files into Enhancing SF data with data from multiple cloud applications and
CSV file then uploaded to data loader to get the records into on-premises systems—such as SAP, Oracle EBS, Oracle Eloqua,
SF. But it was insanely hard process to query data from Atlas. Marketo, and NetSuite—gives you a trusted, holistic view of your
We don’t even sure there are so many records, objects and customer. With better insights, your sales and service teams can
fields, instead of that I thought we can use Mulesoft to build a deepen customer relationships, improve campaigns, and better
one kind API query to hit the legacy system and get the personalize prospecting.
information properly back into SF. That way we can save 3 Extend your multi-cloud architecture
weeks of time, we can make less complicated more Have multiple SF orgs or a lot of endpoints? Simplify and
integration. That integration is called initial migration, one- optimize your multi-cloud data integration by synchronizing front-
time integration. But there is another frame which is ongoing and back-office systems and matching and linking data across data
integration, whatever they worked with Atlas, it reflected the sources.
SF. We didn’t only initial migration but also do ongoing The Informatica SF Platform Connector supports SF Sales Cloud,
integration using Mulesoft as well. Service Cloud, Financial Services Cloud, and the core SF
Platform, including support for standard and custom objects.
SF integration process contains three major phases. SF Marketing Cloud Connector
1. Pre-planning The Informatica SF Marketing Cloud Connector lets us
● Define the goals of the integration. synchronize massive amounts of account, contact, and lead data
● With goals defined and a project lead selected, identify between SF Marketing Cloud and a variety of on-premises
where the data originates databases and systems, cloud applications, and cloud services
● Designate how often the data should sync between the two using the unique data extensions architecture of Marketing Cloud.
systems. TOP
27
Outbound messaging Roles and Profiles and Permission Sets
Outbound message allows us to specify that changes to fields (Roles see, profile do)
within SF can cause messages with field values to be sent to Roles are one of the ways you can control access to records.
designated external servers. ● We can assign permission on the role with (organizational
- via SOAP wide default, OWD).
- via workflow rules, approval process without code organization-wide default sharing settings give you a
- out-of-box thing baseline level of access for each object and enable you to
- can send single parent record fields extend that level of access using hierarchies or sharing
- supported only async transactions rules.
Whenever the record is changing, SF sending information to any It is a feature to restrict access (visibility) to records of
3rd party system. It is a one-way thing. Hitting the API, working in data.
a SOAP API model; whenever the record changes, we have to OWD access level actions:
send these kinds of information to the URL. Public Full access:
We can design web services API in two ways; send and receive This option is available for setting the Campaign object
the information. We integrated sales cloud and marketing cloud. only along with other access options. Through public
Advantages = access the user can have the ability to search records,
● Can be invoked via workflow rules and Apex. reports, add related records, edit details of the records and
● Up to 100 notifications can take place within a single can delete the record.
SOAP message. This makes it very efficient. When the Campaign object is set to public full access, all
● Guaranteed message delivery for up to 24 hours (retries users in that organization can be able to view, edit, transfer
for that duration). Asynchronous so no client latency. and delete.
Disadvantages Public Read/Write/Transfer:
● Receiving service must implement SFs’ outbound This option is available for Leads and Cases objects only
messaging WSDL. along with other access options. When lead or case objects
● REST is not an option for outbound messaging. are set to public read/write/transfer, then all users can
● Governor/developer limits exist. view,edit, transfer and report on all the case and lead
Top records.
Public Read/Write:
Whenever a record is set to public read/write the user can
Query() and Queryall() view, edit and report on all the records.
Both are using for getting the records. If we use the query(), that is Public Read only:
not retrieve the deleted objects. queryall() retrieve the deleted When a record is set to public read-only the user can
records. search the records, view and report on every record but the
In the real-time we are using only query(), because we don’t want user cannot edit that record. Only record owners and
to retrieve deleted records generally. assigned users can edit that records.
queryMore() get the records in the batches. We just get the 200 Private:
records then another 200 records up to 2000 records. We use When a record is set to private only that record owner and
querymore for junks of records. users above that role in an hierarchy can view, edit and
TOP report on those records.
28
● All metadata permissions are managed inside the - Pagination - If it is UI level, if we are using
profile. Visualforce, we have to use pagination.
● In addition to objects, profiles also control: Top
● Field-level security (which fields are visible
or editable), page layouts, record types.
Lazy notes
● Defining profile for a user is mandatory
We just suppose if the user enters on the screen, we first display
20 records and scroll to the bottom then next 20 records will be
Permission set
implemented. We implemented that just to avoid for performance
Only for enhance not decrease the permission.
issue.
Permission sets could be considered for particular profiles. They
@future First of all, we need to definitely to check if it is
offer flexibility in how you add certain permissions (objects, field-
catchable or not.
level security, page layouts, record types, apps, tabs) to certain
On the rapper class we are using get-set methods. I mean getter
users – almost like you are tagging an individual user. In order to
setter
grant a very specific ability to a user, you obviously don’t want to
Top
create a whole new profile.
TOP Authentication while integration – Single Sign-
on (SSO)
Single Sign-On
Custom settings vs Custom Metadata I just go to the trailhead documentation and follow the
Settings that help us to put configuration and it will be easily configuration steps.
accessible across the org. Example: We generally use single sign-on for Microsoft
For example, we are doing an integration vs legacy system and OneDrive. Once we upload the document into SF, it gives us the
that legacy system require some any APIs, endpoint of the legacy flexibility to upload the document MS OneDrive also.
system might be changing when we move from sandbox to SF has its own system of user authentication, but some companies
production. We don’t have to make changes in the APEX code. prefer to use an existing single sign-on capability to simplify and
We use the custom settings inside the code, we just need to make standardize their user authentication.
changes in the custom settings. Design only when we have kind of Single sign-on (SSO) is an authentication method that enables
configuration depends on the org. As a developer we have some users to access multiple applications with one login and one set of
piece of a configuration, that will change when the org changes credentials. When we set up SSO, we configure one system to
and we the custom settings which replace the information to use trust another to authenticate users, eliminating the need for users
new configurations. to log in to each system separately.
Whenever we have org dependent data, information or We can even configure an SSO chain where users log in to an
configuration, we use the custom settings. external application to access SF and then use SF to access
another org
Custom settings are similar to custom objects and enable Manage User Passwords
application developers to create custom sets of data, as well as SF provides each user in your org with a unique username and
create and associate custom data for an organization, profile, or password that the user must enter at each login. As an admin, you
specific user. can configure several settings to ensure that your users’ passwords
are strong and secure.
There are two types of custom settings: Multi-Factor Authentication
List Custom Settings - How we are creating a record from Network-Based Security– We are using IP
contact object?
Hierarchy Custom Settings – This kind of data can be accessible
by this user/profile. We specify that data on user/profile bases.
TOP SF IoT REST API
Create a Connected App
Large volumes of data - best practices Create a connected app in SF, and enable OAuth. The
- readOnly() keyword in Visualforce pages helps us to client application uses the connected app to connect to
handle large data. SF.
- Batch class (number of batches), we are just setting Get an Access Token
number of records (1 to 2000 by default 200). To get an access token, make a POST request to the
authorization endpoint.
29