Wa0007.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 182

Salesforce Admin 201 - First Course (Understand Platform) Basic Course / Declarative

Salesforce Platform Developer-1 / SFDC Developer Course - Development


Pre-Req - SFDC Admin
Recommended - OOPS Concepts
Salesforce Aura Component Framework Built ..
Lightning Design System
Salesforce LWC

Introduction to Cloud Computing


Force.com

Cloud Resources
Database
Operating System
Storage
Memory
Network

Rules - Governor Limits


Salesforce.. more SAAS and PAAS …
Platform As a Service Leverage Force.com
To build Cloud based application with help of Declarative Approach and Programmatic way
CRM – Customer Relation Ship Management
Medical Representative /Sales guys
Doctors
Medical Stores
Hospitals
Pharmaceuticals
Clinics
Tab - … CRM / Sales Guy - Sales Application

These are all my Customers


Leads got generated.
Very much interested
Ayush… CEO for a Mobile Company.. / Mobiles / Printers / Tabs
Service -

Marketing Cloud
Marketing - Campaigning

Advertisements
Tele Marketing
Bill Boards
Social Media Marketing
Web to Lead…
Trade shows

Prospective Lead / Customer .. who is interested in purchasing the product

Leads will get generated

Leads –
Three types Hot, Warm and Cold Leads

Leads are Assigned to Sales Users /Sales Managers

Connecting with leads..

Infosys - Shibangi - SVP -HR

Cognizant - Chaithanya - SVP Faclities

Sales Cloud
Convert these Leads… will get created.. Sales User - MSK

One Account can have more than one contact.


Account can have more the one Opportunity

Account Infosys
Congnizant

Sathyam

Contact Shibhangi
Chaithanya

SVP – Shaik -

Sathyam

Opportunities Order 100 Mobiles * 10000=10,00000=00


Order 50 Mobiles
10 Printers

Service Cloud

Mobiles are not working


Chaitanya – Two Printers are not working

Customer Care / Call Center

Set-up a Customer Car Center

Create - Case / Service Request / Incident / Ticket / Complaint number / Issue


Case ID will get generated

Should be Assigned to Case Manager or Case Engineer / Service


Escalation Rules
Case can be opened or should be resolved within 6 Days
It should get escalated

CRM Objects

Campaign
Lead
Account
Contact
Opportunity
Case
Salesforce Environments

Production Environment
Your actual Application Environment
Development Environment / Testing Environment Sandbox
The development and testing environment within Salesforce is termed as Salesforce
Sandbox.
Replica of Production Environment - Copy of Production
Deploy that code in the Production Environment…

Different types of Sandboxes

Sandbox Create –
Write our code in Sandbox.. 75% of code Converge..

Create a Developer Account

Make you understand about the platform…

Settings
Set-up
Platform Basic
Classic vs Lightning
Profile Settings
https://trailhead.salesforce.com/content/learn/modules/starting_force_com
https://trailhead.salesforce.com/en/content/learn/modules/salesforce-licensing
https://trailhead.salesforce.com/content/learn/modules/company_wide_org_settings
Salesforce comes out with two types of UI –User Interface..

Classic - UI …. Lightweight component framwork


Loading of the page will be fast

Lightning - Heavy weight Component framework..


Little bit slow…

Company Information
00D5g000003cUtC – Unique Org ID

Agenda
Activities / Scenario based….

Standard Objects
Custom Objects
Standard Fields
Custom Fields
Create a Custom Object -
Datatypes
Add Fields to the Custom Object
Page Layout
Field Dependencies
Page Sections
Classic vs Lightning

Introduce Recruitment Project

Requirements Gathering
Understand the Requirements
Derive the Objects
Derive the fields
Create Relationships between the Object

Create Teams …
Collaborate and will do it
In all the Salesforce Orgs..

https://interncoginzantbatch.quip.com/2s4MAUUmdPqu/Introduction-to-Cloud-Computing

Initial Building block for an Salesforce Application

SQL-
Database - Tables
Rows - Tuples
Columns – Attributes

Product Details
States / Attributes

Attributes / Columns

Product

Product ID
Product Name
Product Cost
Quantity

Salesforce is called as Objects – are also called as Table in Database

Everything is represented object

Object - Fields
Records

Two types

Standard Object - Objects that are created by Salesforce


Objects that are in built in Salesforce.

These objects you cannot delete…


You can modify it..

Custom Object - Objects that are created by Admin or Developer..

Label APIName

Account Account Account

Product Product Product__c (Appended by c)

Custom Object you can modify and you can delete.

Object Manager is nothing but a repository where you can find Standard and Custom
Objects

Whenever you create a custom object / Record …


15 digit Unique Case Sensitive ID will get created

00B5j00000KU7M4

Whenever I create a Custom Object


Four Standard Fields gets Created

Name
Owner
Created By
Last Modified By

Scenario 1 : Create a custom object called Position

Fields
Rows / Records

EmpId
Name
Job Title
Email ID
Salary
Phone

Field Names Type of Data Data / Values

Position Name Text Java Developer


Experience Number 10
Skills Required Text Java / J2EE
Start Date Date &Time 06-April-2022
Technical Qualifications Text
Educational Qualifications Picklist B.Tech, BE, MBA,
MCA
Projects
Salary Currency $2000
Department Pick List Eng,IT, Accounts,
Sales & Service

Public class Position


{
String PositionName;
Int Experience;
Public Position()
{
PositionName=”SFDC Developer”;
Experience=7;
}
Public static void main(String args[])
{
/////
////
}

Custom Fields
Department__c
Start_Date__c
Experience__c

***** Certification…
Different Properties of a Field…
Label
Field Name - API Name
Description
Help Text
Required /

Scenario 2: Create or Add various Custom fields on Position Object. Please refer below
table
Field Dependencies
Create a dependent relationship that causes the values in a picklist or multi-select picklist
to be dynamically filtered based on the value selected by the user in another field.
• The field that drives filtering is called the "controlling field." Standard and custom
checkboxes and picklists with at least one and less than 300 values can be controlling
fields.
• The field that has its values filtered is called the "dependent field." Custom picklists and
multi-select picklists can be dependent fields.

Registration form
Address Fields
Country Pickist 240 India / USA Controlling Field
State 23 States Delhi Telangana Dependent
Field (Controlling Field)
City 4 Cities Rashtrapathi Bhavan Road - Hyderabad
Dependent Field
Filtering. Dependency
This is called as Field Dependencies
Scenario 3:
Create Field Dependencies on Position Object
Controlling Field Sub Status Dependent Field
Status New NA
Open Pending, Approved
Closed Cancelled, Not
Approved, Filled
Department PayGrade
Eng Eng100,Eng 200, Eng-300, Eng-400
IT IT100, IT200,IT 300, IT 400

Session / Teach back / Learning - WorkShop


Please explore how field dependencies can be created on Multi Picklist and Check Boxes

Difference between – Object and Tab


Tab- View, Insert, Update, Delete the records in a particular object.
Page Sections- Page layouts Create Page sections on a Page layout
Scenario 4: Create Page Sections on Custom object

Description Details Section


Fields
Job Description Skills Required
Educational Qualifications Responsibilities
Compensation Plan Section
Min Pay and Maximum Pay
Rearrange the fields

***** Page Layout Field Properties are two types 1) Read Only 2) Required

Recruiting Process

Registration.
Resumes
Test
Shortlisting of the candidates
Interview
Back Ground Verification
Career Portal / Job Portal..

Project Managers / Hiring Managers


Additional Scope / Work – Project Requirements

Aswani- Project Manager 10 Resources / Ramp-up –


Developers
Designers
Architect
Tester

Aswani- Create Job Description, Years of Experience, Qualifications


Any Certifications, Good to have additional knowledge

Project Recruiter or HR …

Publish these details on Job Portals


Naukri, Linkedin, Indeed, Monster
Internal Job Postings

Position or Job Position

Candidates will Registered / Applied for that Position by filling a form (Job
Application)
***** with one Job application you can apply only for one Position

Short list the profiles – communicates.


Scheduling the Interviews..for Candidates

Interviewers - Technical Interviewers. ..


Kiran & Vinay Candidates
Nitish and Satyam - Technical…
Document their interview details
Feedback form or Review form…

Offer Letter –

Recruiter (HR)
Hiring Manager(HM) / Project Manager
HR Manager -> Report on the recruitment process.
Interviewer.
CEO. SVP –HR, SVP-Development
One to Many Relation

School Students
One school can have many students

Organization Employees

Coach Subjects

Cricket / FootBall Players

Customer Accounts

Many to One Relation ships

Many Interns Working One Campus

Players Play FootBall

Student Studies University

Passengers Travel Single Train

Many to Many Relation Ships

Basically Salesforce offers two types of relationship:


One To Many Relationship
Many To Many Relationship (Using the concept of Junction object)

Why don’t we relate the objects

1 Parent Object / Master Object


M Child Object / Detail Object
Position -
Candidate - Name, Gender, Email, City, Contact Number
Job Application - Job ID, Position, Experience, Role.., location
Job Posting Site- Site Name..
Shortlisting - Final Grades, Skills Matching, Experience, Projects
Interview - Interviewer Name, Type of Interview, Interviewer ID, Skill or Position
Feedback / Review Details — Technical Skills, Communication Skills, Cultural Fit,
Leaderships....(1-10)
Offer Letter - Candidate ID, DOJ, Location, Basic Salary, HRA, PF, DA, Medical etc etc
Back Ground Verification - Candidate, Education Qualifications, PAN, Aadhar Card,
Experience, Transcript..,

These relationships are mainly categorized into the following types:


• Lookup
• Master-Detail

Look-up relationship

A lookup relationship can be used to link two objects together. It is the


most basic type of relationship that creates a child-parent relationship
between two objects.
******* Very Important *************
Look-up icon gets created on the Page layout.
• When you define a lookup relationship, you have the option to include a
lookup field on the page layouts for that object as well as create a
related list on the associated object's page layouts.
• Loosely Coupled Relationship (also referred to aggregation in database
terminologies)
• Two Objects have relationship but they are not dependent.
• Sharing and Security on these objects are independent.
• No Cascade Deletion – Delete a record in a parent object the
corresponding records are not removed
• The field reference can have null value
• We can create upto 38 Lookup relationships on a Child Object

Net Developer - J1 Shaik


J2 Sashank
J3 Abhinandan
Master Detail Relationship

A master-detail relationship creates a tight relationship between the


parent and the child.
Dependent… each other. Child record is dependent on Master Record
Compositions
Sharing and Security is dependent on Master Record / Object…
Master Object or Parent Object is controlling.
Cascade Deletion. – if you delete a master Record the corresponding
child records also get deleted.
• The field reference cannot have null value. it will become required
value…Red ***
• You can create two MD relationships on a detail or child object

Total how many you can create

38 Lookup + 2 MD on a Child or Detail Object.

Master-detail relationships created some extra functionality such as


Roll-up summary fields that allow you to calculate data on the parent
from the child records

07-April-2022

Scenario 5: As discussed, Create Loo-up relationships as per the Data Model

Position Job Application


1 M

Candidate Job Application


1 M

Position Interviewer

Master Detail - Tight couple -

Interviewer conducted Review / Feedback


1 R
Job Application Offer Letter

Job Application Reviews


1 M

Master Detail

Master Detail
Lookup – Loosely coupled..

******Relationship field should always go on child Object

****** Related List is created only on Master Object****

If you want to see who are the candidates have applied for a Position

If you want to see which all the positions these candidates have applied

Scenario 6: Create MD Relationship between as the Data Model

Position Interviewer
Job Application Review

Many to Many Relation Ships

Customer Buyer / Purchase Products

Patients Consultation Doctors

1- Patient Many Doctor

2- M - Patients One Doctor

Scenario: 7 Create a Junction Object called Job Posting and create MD relationship
between

Position (M) Job Posting (C)

Job Posting Site (M) Job Posting (C)


Schema Builder-
With the help of Schema Builder you can view your objects in a Graphical Representation
You can create objects, fields and Relationships.

Scenario 8: Represent all Custom Objects relationship for Recruiting App in Schema
Builder

Self Relationship

Cloud Computing Technologies


AWS
GCP
Salesforce
Oracle Cloud
Azure

AI & ML
Python
NLP
Tensorflow
Supervised
UnSupervised

UI Technologes
React
Angular
HTML, CSS & Java Script

Backend Technoloies
Java
Node

Programming Technologies

Hierarchical relationship

In Salesforce, only a user object has this type of relationship where we can create a
hierarchy of users in the organization. For example, a user can have his manager, and his
manager may have senior manager, and so on till the CEO or CIO level. The best example
is the manager field on a user object

External lookup relationship

What is an External Object?

External objects are similar to custom objects, but external object record data is
stored outside your Salesforce organization.

How to Create an External Object?

External lookup relationship


We can create two special lookups on an external object apart from the standard lookup
relationship.
They are external lookup relationship and indirect lookup relationship.
External lookup relationship allows us to link an external object to a parent external
object whose data is stored in an external data source. In other words, it allows us to link
two external objects.

Scenario 9 - Create external lookup relationship between Order and Supplier Objects

Indirect lookup relationship


An indirect lookup relationship allows us to link an external object to a standard or custom
object. We can only create an indirect lookup to an object with a unique external ID field on
the parent object that is used to match the records in this relationship. While creating an
indirect lookup relationship field on an external object, we have to specify the child object
field and the parent object field to match and associate records in the relationship. For
example, we can display a related list of payments from the ERP external record with
matching external IDs on the account object.
08-April-2022

Demo
How to Create a User
Licenses
Users & Set-Up a User
Activate
Freeze
Deactivate
Enable Admins to Login (Login Access Policies)
Session Settings (Retain admin session after logging-off as another User)
Profiles + Standard Profiles
Permission Set
Workshop - Profiles + Permission Set
Data Security
Org Access
Object Access
Record Access
Record Types

OWD (Organization Wide Defaults)


Role Hierarchies
Sharing Rules | [Public Groups]
Manual Sharing
Workshop - Record Access
Permission set Groups & Restriction Rules (overview)

Things to consider when designing Apps

Consider the actors—who will be using the app?


CEO
Recruiter
HR Manager
SVP-HR and SVP-Dev
Candidates
Interviewer
What will these users expect to see and do?
What data is most important?
Candidate Details -
Review
Offer
What should these users be able to see—are there any data restrictions?

How can we make the user experience more streamlined and efficient?
Profiles / Roles / Accessibility of Objects and Records
Which users should be able to customize the app?
Sys Admin & Developer

How to Create a User


Licenses
Users & Set-Up a User
Activate
Freeze
Deactivate

12 Salesforce licenses

In your org 12 Users created in the Salesforce Org


Create a User – Syd Admin rights to create a user…
Every user should have valid Salesforce License to login into the org..
Every user should get associated with a Profile.

******1 Certification Question

Deactivate User:
Deactivating a user in Salesforce means that user will not be deleted from the system but
will no longer be able to log in to Salesforce and their records can be transferred to another
user. They cannot be part of workflows or part of any automated processes.
Deactivating a user, the licenses are available for use in your organization.
Deactivated users lose access to any records that were manually shared with them, or
records that were shared with them as team members. Users higher in the role hierarchy
relative to the deactivated users also lose access to those records. However, you can still
transfer their data to other users and view their names on the Users page.
Freeze User:
Freezing a user in Salesforce means that only stops the user from being able to login.
In some cases, you can’t immediately deactivate a user (such as when a user is selected in
a custom hierarchy field or a user that’s assigned as the sole recipient of a workflow email
alert). To prevent users from logging into your organization while you perform the steps to
deactivate them, you can freeze user accounts.
Freezing user accounts doesn’t make their user licenses available for use in your
organization.
If you don't want the user to login into Salesforce then just go ahead and freeze that user or
if that user is not using Salesforce instance anymore then you can deactivate that user.
One point to consider here: Deactivating the user frees up the license which can be used
by another user but in case if you freeze the user then the license is still being used.
Enable Admins to Login (Login Access Policies)
Administrators Can Log in as Any User -
Session Settings (Retain admin session after logging-off as another User)
Un check Force relogin after Login-As-User

Profiles + Standard Profiles

Sys Admin should determine what level of Access that he is going to provide for different
users in the org..
How is going to determine…

Profiles determines the what level of Access a particular user has…

Every user should be assigned with one Profile


One Profile can have multiple users.

Divided two types –

Standard Profiles
Profiles which are created by Salesforce.
Ex: Solutions Manager, Standard user, Standard Platform user, System Admin…
Custom Profiles – Profiles which are created by admin or developer
Profiles will consider a Salesforce license.

You cannot create a Profile… if you want to create a profile u need to clone an existing
Profile
It is recommended to Clone any Standard Profile.
Profiles are controlling
1) Page layouts
2) App Level Access
3) Tab Level Access
4) Login HRs
5) IP Rangers
6) Administrative Permissions
7) General User Permissions
8) Standard & Custom Object Permissions
CRUD - Create, Read, Update and Delete
9) Field Level Security
10) Password settings / policies
11) Record Types
12) Access to Apex Classes
13) Access to Enable VFPages

Profiles have two UI

Activity –
Create a Profile
Configure a Profile
Assign a user to that profile
Login with that user profile. what kind of access levels that user has..

Scenario 15: Create a Recruiter Profile and provide below and Object level access as
per the table and assign this profile only to (Mario, Cynthia, Meghan and Andrew)

1) Recruitment App, Sales App (both Classic and Lightning) //App Level Access -
*************************************************************
2) Default On Only Recruitment Tabs. // Tab Level Access
************** Certification Question
Default On - You can view the object on the Tab
Default Off - You cannot see an object on the tab but you can see the object
in All Items of App Launcher Page or + in classic
Tab Hidden - You cannot see the object either on Tab or in App Launcher. it
is hidden.
********************************************************************
3) Custom Object Level Access (Kindly refer the table)
4) Login Hrs (9:00 AM to 6:00 PM only on Weekdays) Org Level Access
Select the days and hours that users with this profile are allowed to log in. Note that all
times are exact times specific to a time zone. Login hours will be applied at those exact
times even for users in different time zones.
5) IP Ranges (specific IP's which are provided by Network team)
6) Administrative Permissions //special permissions. Business will give.)
7) General User Permissions
8) Standard & Custom Object Permissions.
10) Password Policies.
3 Records for all objects with various users

Assign this profile to a User and Login with that user and check whether the user is
having above access levels on the Org or Application
We need to enable this..how to enable it?
******Enable: Administrators Can Log in as Any User
*** Disable Force relogin after Login-As-User – Session Settings

**** when you logged in as a particular user..you cannot perform any admin related
activities

Scenario: 16 **********Home Work****************


Create a Hiring Manager Profile and provide Object level access as per the table and
provide access only to (Phil and Ben Stuart)

1) Recruitment App, Sales App, Salesforce Chatter (both Classic and Lightning) App Level
Access
2) Only Recruitment Tab level Access.
Default On - Custom Tabs On
Default Off - Chatter Tab
3) Object Level Access (Kindly refer the table)
Assign the users to the profiles...and Navigate the App and see the changes.
Hiring Managers: Phil and Ben
Stuart,************************************************************************************************
***
Scenario: 18
Create an Interviewer Profile and provide Object level access as per the table and provide
access only to (Melisa Lee)

1) Recruitment App, Sales App (both Classic and Lightning)


2) Only Recruitment Tab level Access.
Default On - Custom Tabs On except Offer Tab-Tab Hidden
3) Object Level Access (Kindly refer the table)
Assign the users to the profiles...and Navigate the App and see the changes.
Interviewer: Meeliza Lee

Permission Sets

Position -R
Candidate - R
Job Application -R
Phil and Ben, Aditya..

Philkhatz will come to Sashank Request


To grant additional permissions (Create, Edit and Delete) on Position, Candidate and Job
Application.. only to me not to any users in Hiring Manger profile

Permission Sets- Grant addition permissions to a users..


****** 1 Cert 1000 Permissions set can be created for a Single Org..
Permission sets are not profile…
**** you can assign permission set to multiple users

*** Permissions set can be assigned to


App Level
Object Level

Scenario 19

Phil Khatz will reach out to Sys Admin he will request Sys admin to Provide or Grant
Additional Permissions like Edit, Create and Delete on Position, Candidate and Job
Application Objects only to me not to all other users who are part of Hiring Manager Profile

Scenario 20

Create a Permission set so that Mario and Megan when hey login as Recruiter Profile they
should able to see addition App level Access (Chatter and Service –Classic and Lightning).
Field Level Security

Providing accessibility and visibility of your object fields

Field level security is implemented three ways

1) Profile Level

Read Access Edit Access

Scenario 21: Ensure Min and Max Pay fields are not visible for Interviewer Profile users.

2) While Creating a field you can enable FLS..


Visible Read Only

Scenario 22: Create an Email ID or Phone number field on Candidate object where FLS
For these fields are Read Only fields..

Interviewer - Visible & Read


Hiring Manager - Visible & Read
Recruiter Profile - Visible
Sys admin Visble

3) Permission Set..

Record Types

Types of Record that u want


To differentiate the record types…

Scenario 23: On Position Object.


Create two Record Types...
1) Technical Record Type
2) Non-Technical Record Type..

i) Create three multi pick list values


1) Operating System (ios, Android)
2) Programming Languages
3) Domain Knowledge.

ii) Create two Page Layouts


1) Technical Page Layout
Add OS and Programming Language fields to this layout
2) Non-Technical Page Layout
Add or Assign Domain knowledge Field..

iii) Create two Record Types and assign only to Recruiter and Sys Admin Profile only
1) Technical Record Type
Assign this record type to Technical Page Layout
Edit the Dept and Paygrade Fields

2) Non Technical Record Type


Assign this record type to Non Technical Page Layout
Edit the Dept and Paygrade Fields

Scenario 24: HW- Create two Record Types.. on Candidate object –


Additional Fields on Candidate Page Layout - Email, Phone, Gender, Country

1) Non US Candidate
2) US Candidate
i) Create additional fields
US Candidate
SSNO
Unique ID No
Green Card Holder
H1B Candidate
Non US Candidate
Aadhar Card
PAN
Country Specific Identity
ii) Create two Page Layouts.
Assign those fields to Page Layouts
iii) Create Record type assign those page layouts with respective fields
iv) Assign it only to SysAdmin and Sales Profile or Recruiter profile
11-Aprl-2022
Workshop on Field Dependencies Ashwini - Mars
Workshop on External Relationship
Workshop of Look-up filter Srija - Venus

Everyone are cleared on the first week on concepts

Data Security / Record Level Access


Org Access
Object Access
Record Access
Record Types

OWD (Organization Wide Defaults)


Role Hierarchies
Sharing Rules | [Public Groups]
Manual Sharing
Workshop - Record Access

Permission set Groups & Restriction Rules (overview)


Activity Management
Custom Formula Field
Business Process Automation | Automation Concepts
Validation Rules
Workflow Rules
Evaluation Criteria
Rule Criteria
Immediate & Time Bound Actions

Record Level Access / Sharing Security Model

Every user has flexibility of editing other owner records


Where is the security to my own records?
Every user is editing every one record.
Data has to be restricted…
Outmost care of your records specifically at the Access, editing of the records..
If one user deletes other user’s record..
Who will have full record level Access and what are the types of Record Level
Access

Three types of Record Level Access

1) Full Access Privileges


Admin
Owner of the Record / User
Queues

• View
• Edit
• Transfer ownership
• Delete
• Share

Scenario 25: Transfer Ownership


Transfer Sys Admin Position record to the Megan Smith.

***** user should have a valid salesforce license


He can also transfer the record to a Queue

********What is this Queue?


Queue is a group of users who will share the workload effectively among themselves
Once a Record is assigned to a Queue, any user who is part of Queue should accept that
record to become owner of that record. And this owner can further transfer the record to
any user or to a Queue. ***************
**** Queue should be created on objects..

Queues allow groups of users to manage a shared workload more effectively. A queue is a
location where records can be routed to await processing by a group member. The records
remain in the queue until a user accepts them for processing or they are transferred to
another queue. You can specify the set of objects that are supported by each queue, as
well as the set of users that are allowed to retrieve records from the queue.

Basically queues are helpful in Sales Cloud and Service Cloud.

APAC Sales Users Queue-


Leads which gets generated from any APAC Country, its leads should assigned
automatically to a User..

NA Sales User Queue-

To add members to this queue, select a type of member, then choose the group, role, or user from
the "Available Members" and move them to the "Selected Members." If the sharing model for all
objects in the Queue is Public Read/Write/Transfer, you do not need to assign users to the queue,
as all users already have access to the records for those objects.

Scenario 26: Queue- Create a Queue called Recruiter Queue on Position, Candidate and
Job Application and assign Mario, Megan and Cynthia as a group of Queue Users.

• User above him (who has ownership) in the role hierarchy. – will have Full
Access to the record.. if you mark or check an option called “Grant Access
Using Role Hieracrhy”

Read/Write or Read-Only Access:


Role and Role Hierarchy is must
OWD

Sharing Model – Will tell what kind of record level Access you have …
And it is decided by OWD

Organization Wide Default

• Organization-wide defaults are a security setting that defines the baseline level of
access to data/ records that you do not own.
• They are the only way to restrict access to data in the sharing model.
• They can be defined for the custom as well as several standard objects.

• Access levels:
• Public Read/Write (all users can see and edit every record)
All users can view, edit, and report on all records.
• Public Read-Only (all users can see every record)
All users can view and report on records, but only the owner, and users
above that role in the hierarchy, can edit them.
• Private (users can only see records that they own)
Only the record owner, and users above that role in the hierarchy, can
view, edit, and report on those records.
Public Read/Write/Transfer – Only - is only for Case and Lead objects
Defined Role and Role Hierarchy Structure in your Organization
Scenario 27: Create Role and Role Hierarchy Structure as per below Chart. And add or assign
users for these roles that you created

Scenario 28: Change the OWD setting from Public Read/Write only to Private for
Position object.

Controlled by Parent

Sharing and Security is dependent on Master Record / Object…


Master Object or Parent Object is controlling.

Scenario 29: Enable OWD settings as per below table


Sharing Rules | [Public Groups]
Manual Sharing

OWD – Restricting the Record Access…

If u want to share the records below or above the role and hierarchy users..need to
Share the records…

There are three ways to share the record.

1) Manual Sharing
2) Sharing Rules
3) Apex Sharing Rules

Though ur OWD setting is Private or Read only you can share the records.

1) Manual Sharing – IF you want to share only single record…. You can use Manual
Sharing.
Scenario 30: Share a Record from Position from Megan to Mario and provide Read and
Write Access to MArio
2) Sharing Rules
Is to provide access the record
Are divided into two types

Use sharing rules to make automatic exceptions to your organization-wide sharing settings
for defined sets of users.
Note: "Roles and subordinates" includes all users in a role, and the roles below that role.
You can use sharing rules only to grant wider access to data, not to restrict access.
You can share the records at below user hierarchies and to other hierarchy users
also
Criteria Based Sharing
You can share the records based on Criteria or Condition
Ex : Department = IT, ENG
Status= “Open”

Scenario 31: Share all the Position records whose Department equals to IT, Eng and
Service to – Role called SVP-HR *** you can share these records to

1) Role and Subordinates - (Below the Hierarchies) – SVP-HR


2) Public Groups
3) Roles

Owner Based Sharing


Sharing the records based on the Owner.

Scenario 32: Share the records whose owner is Cynthia to SVP Dev Role or Public
Group.
Sharing the records based on the ownership

Apex Sharing - Development – Apex Programming

Public Groups
A public group is a set of users. It can contain individual users, other groups, the users in a
particular role or territory, or the users in a role or territory plus all of the users below that
role or territory in the hierarchy.

Scenario 33: Create a Public Group Called Leadership Group


Users - Cynthia, Megan, Andrew
Roles - SVP-Marketing SVPHR and SVP Dev
Salesforce Platform –

M Model
V View
C Controller

Administrative related tasks


Record Level Security -
Full Access, Read and Write and Read only access
Sharing Model.
OWD- Settings
Private
Public Read only
Public Read and Write
Public Read/Write and Transfer
Sharing Rules ..

Custom Formula Field


Rollup Summary | Field History Tracking
Business Process Automation | Automation Concepts
Validation Rules
Workflow Rules
Evaluation Criteria
Rule Criteria
Immediate & Time Bound Actions

I need to perform some Automation Process. some tasks should complete automatically
with less intervention or no user involvement.

Automation Process.
Business Logics or Business functionalities which are given by client of by requirements
documents. you are supposed to implement the automation process
What are the different Automation tools or Process tools does Salesforce is providing.. so
that I can implement in my Application

Business Logic Layer

***How to Automate a task..


Custom Formula Field -
These are the common fields on the Page layouts
It will perform some calculations. takeing some values from other field.s
1. Are part of each object details page fields section..
2. A read-only field that derives its value from a formula expression you define.
3. The formula field is updated when any of the source fields change.
4. You cannot view this field on the Page Layout of an Object
5. You can view this field on the details or record page layout of an objects..
6. Get the values from a formula expression which you define...

HRA
DA
PF
Medical Allowances
Special Allowances

Calculate the Total Salary of an employee based on Basic, HRA and other allowances
Before doing this exercise you need to have a record in Candidate and Job Application
Object to perform this calculation.
Create formula field called as HRA with 30%, other Allowances with 12% and Total Salary
in offer object. You cannot see these fields on the page layout.

Scenario 34:

Calculate the Total Salary of an employee based on Basic, HRA and other allowances
Before doing this exercise you need to have a record in Candidate and Job Application
Object to perform this calculation.

Create formula field called as HRA with 30% of Basic, other Allowances with 12% of Basic,
and DA Allowance of 12 % and Calculate the Total Salary in offer object. You cannot see
these fields on the page layout.

Basic Salary - 10000


HRA-30% - 3000
Other Allowance -1200
DA Allowance – 12

Total Salary=10000+HRA+OA+DA
=15400
Cross Object Formula’s & Advance Formula Fields

Salesforce has some inbuilt functions which can be used to perform complex operations in
the formula. Some of the functions are ( for example DATETIMEVALUE returns a year,
month, day and GMT time value, ISNUMBER() determines the given text value is a number
and returns true if it is, otherwise returns false. The following are the various kinds of inbuilt
functions used to write a formula.
1. Date and Time functions (DATE, DATEVALUE, DATETIMEVALUE, TODAY, etc.)
2. Logical functions (IF, ISBLANK, ISNULL, ISNUMBER, AND, OR etc.)
3. Math functions (MAX, MIN, ROUND, FLOOR, etc.)
4. Text functions (BEGINS, CONTAINS, INCLUDES, ISPICKVAL, LEFT, RIGHT, etc.)

Can also be used to reference the fields of other objects – called as Cross – Object
Formulas.
***** Create formulas that reference fields on parent or grandparent object (up to 10
levels)

Scenario 35:
Create a Cross Object Formula to display Candidate Name and Position Name on the Offer
Page Layout.

Roll-up Summary Fields

Aggregate functions

Sum()
Min()
Max()
Avg()
Count(Name)
Count(*)

Detail Records - Sum()

Display the value on Master Record..


It is enabled only on MD Relation Ship

Scenario 36:

Implement Roll-up Summary field on Job Application and Review object which we
discussed in the class. Complete this activity.
Experience Leadership Skills Culrutal Fit
J006

R001 7 8 8
R002 8 9 9
R003 9 8 8

Sum of Experience 24 25 25
Total No of Review – Count(Review) -3
Total Score 24+25+25=74

Sum()
Min()
Max()
Count()

If you see the field definition, opportunity to account is a lookup field. But in terms of
business logic it behaves as Master-Detail one .... e.g. you can create Rollup summary field
in account, if an account is deleted then related opportunity will be deleted.

Account - Opportunity
Opportunity - Product

Additional Scenario 37:

On Account Object & Opportunity Create Roll up summary to calculate below


Create a Page Section
Sum of Amount
Sum of Expected Revenue
Total No of Opportunities..

Field History Tracking - Security Feature

This page allows you to select the fields you want to track on the Position History related list.
Whenever a user modifies any of the fields selected below, the old and new field values are added
to the History related list as well as the date, time, nature of the change, and user making the
change. Note that multi-select picklist and large text field values are tracked as edited; their old and
new field values are not recorded.
Fields - Track… Data…
Will track.. old and new values of a particular field…
Who did the changes and the timings and date
Scenario 38: Implement Field History Tracking on Position Object. Do the same on
Candidate or Account object
12-April-2022

Business Process Automation | Automation Concepts


Validation Rules
Workflow Rules
Evaluation Criteria
Rule Criteria
Immediate & Time Bound Actions
Workflow Actions
Task
Field update
Email Alert
Send outbound SOAP message
Approval Process
Process Builder

Business Process Automation | Automation Concepts


Formula Fields
Advance Formula Fields
Roll up Summary Fields
Cross Object Formula…

Validation Rules

Validate the data what users are entering


To Restrict the data…
Email-Id, Auto Number, Phone Field – Specific formatting
(000)-(000)-(0000)
Enforce Conditional Formatting
To ensure accurate and relevant data in the fields. Data consistency
Enforce Required Field…

• Validation rules verify that the data a user enters in a record meets the standards
you specify before the record is saved.
• A validation rule contains a formula or expression that evaluates the data in one or
more fields and returns a value of True or False.
• Validation rules also include an error message to display to the user when the rule
returns a value of True due to an invalid value.
• Error message can be displayed directly below field or at top of the page.
• Multiple error messages may be displayed at one time.
Define a validation rule by specifying an error condition and a corresponding error message. The
error condition is written as a Boolean formula expression that returns true or false. When the
formula expression returns true, the save will be aborted and the error message will be displayed.
The user can correct the error and try again.

Scenario 39 - Write a validation rule where Min Pay cannot be greater than Max Pay…
It should through an error message stating that “Min Pay cannot be greater than Max Pay”
at the Min Pay field.

Scenario 40:
Candidate Object: - Build Validation Rules to Enforce Data Format using regex()- Use Reg
Exp to ensure State/Province field should have only two characters in Capital letters.
“Please provide State as Two Alphabets with Capital Letters” should display error of the
user not entering as per format.

Scenario 41:
Create a lookup relationship between Positions(C) to User (M) object as a HM field
Position Object. -Build Validation Rules on Hiring Manager field to Enforce Conditionally
Required Fields and display an error message.

Scenario 42:
Whenever a new Position is created or edited I want the Start Date of that Position should
be greater than two days from Today's date. Hint: Today (03-May-2020)+ 2 days.

Workflow Rules
Evaluation Criteria
Rule Criteria
Immediate & Time Bound Actions
Workflow Actions
Task
Field update
Email Alert
Send outbound SOAP message

Implementing Automation Process/ Business Logic

Workflow - Series of steps or task to complete a process…


Enough depending on Manual Process

Many of the tasks you normally assign, the emails you regularly send, and other record updates are
part of your organization's standard processes. Instead of doing this work manually, you can
configure workflow to do it automatically.
• Actions: Entry criteria: which records
• Object Type - Position
• Evaluation Criteria
created
created, and every time it's edited
created, and any time it's edited to subsequently meet criteria
• Rule Criteria
Condition / Criteria

• Timing: when to execute actions


• Immediately
• Time Dependent
Days or Time… Time Dependent Workflow

• What Actions to be performed or executed


Four Actions:

• Assign Task
• Send Email Alert
• From current user’s email address
• From organization-wide email
• Update Field
• Post Outbound SOAP Message

Scenario 43:

Create a work flow to assign Open Position to recruiter Queue for working on that record.
WF-Whenever a record is created or edited the record owner (field update) is changed to
Recruiter Queue

• Actions: Entry criteria: which records


• Object Type - Position
• Evaluation Criteria
created, and any time it's edited to subsequently meet criteria
• Rule Criteria
Status=”Open”

• Timing: when to execute actions


• Immediately
• What Actions to be performed or executed
• Update Field - Owner Field from Shashank to Recruiter Queue
Scenario 44:

Whenever a new Candidate is created (Evaluation Criteria) then Current Employer field
should be updated as Cognizant and mail should be sent to system admin:
Create a field called Employer and make this field as Read Only.

Actions: Entry criteria: which records


• Object Type - Candidate
• Evaluation Criteria
Created
Rule Criteria
Gender = Male or Female

• Timing: when to execute actions


• Immediately
• What Actions to be performed or executed
Four Actions:
• Send Email Alert
• Update Field

Email Template Creation


Time Dependent Workflow
This workflow will execute within the specified time.

Email Alert Triggering

Scenario 45 : Create a time dependent workflow for notifying owner to follow up on offer
letter? Create WF on Offer object if the Candidate he or she doesn’t accept or reject the
offer for seven days.. Create an Email Template and send it to the candidate to accept or
reject the offer letter.
Criteria – Offer Status=Sent

**** How many types of email templates that you can create
1) Text
2) HTML Using Classic Letterhead
3) Custom without Using classic Letterhead
4) Visualforce

{!Offer__c.Candidate_Name__c}

{!} Expression tag


Actions: Entry criteria: which records
• Object Type - Offer
• Evaluation
created, and any time it's edited to subsequently meet criteria
Rule Criteria
Offer Status=Sent
• Timing: when to execute actions
Time Dependent
Time Trigger – 2 Days after Offer Created Date
• What Actions to be performed or executed
• Send Email Alert

Scenario 46 : Whenever a new offer is created then bonus percentage should be updated
to 10%. Rule Criterial can be Status = draft. Workflow Actions update Status Field = Sent
an email should be sent to the system administrator and if require to Candidate.

Scenario 47 : For all the positon records when created or updated check if the priority is
Critical and Min Pay is >= 10000 and Max Pay <=15000, if so then status of such position
record should be updated to automatically “Open” and email should be sent to Owner.

Scenario 48 : Whenever a new Position record is created, automatically the record start
date should be next week from the current data.
Whenever the Position Status is New- Entry Criteria.

Scenario 49: Time-dependent


For example, Salesforce can automatically send an email reminder to the account team if a
high-value opportunity is still open ten days before the close date.
Criteria: Amount is >=3000000 USD
Email Reminder - Sales Team & Owner

Object = Opportunity
Evaluation Criteria - third
Rule Criteria: Amount >3000000 USD

Time Dependent
Time Trigger - 10 Days before Close date

Actions:
Email Alert to the Sales team / Admin or Sale user.
Approval Process

Giving some approval for any task


Taking Approval… which follows hierarchies
Because it is documented… to the data and to take consent from the stakeholders…

Where you can send records for approvals.


Configure this approval process in Salesforce.

• Approvals consist of 6 parts:


• Process Definition (Global Characteristics)
Object
Entry Criteria.
Send an Email Alert to the Approver
Submitter
Record Edit ability
Add the Submit for Approval button and Approval History related list to all
Opportunity page layouts

• Initial Submission Actions (Workflow Actions)


Four Workflow Actions

• Step Definition (Decision Criteria & Approval Assignment)


1- Amount<1000000 - Cynthia
2- Amount >=1000000 to <=2000000 - Megan

• Final Approval Actions (Workflow Actions)


Actions should be triggered
• Final Rejection Actions (Workflow Actions)
Rejects -
• Recall Actions (Workflow Actions)
Recalled – Admin or by the Approver..

***** once the record enters into Approval Process…. Immediately the record will get
locked.. only Sys Admin and edit the record.. and some time Approver can also edit the
record

There are two Approval Process

1) Jump Start Approval Process


2) Standard Setup Wizard Approval Process
Step by step by
Skip level Approval Process
Scenario 50: Jump Start Approval Process:

If the Opportunity Amount is greater than 1000000. Kindly get it approved by CEO
Cynthia. Update the record Status field has Approved. Create a status picklist field
with below values Pending, Approved, Rejected, Recalled.
Hint: JumpStart Approval Process...

: JumpStart Approval Process...


It is an approval process where the process is defined in a single step or
single page approval process

Add the Submit for Approval button and Approval History related list to all
Opportunity page layouts

• Final Approval Actions (Workflow Actions)


Status - Approved
• Final Rejection Actions (Workflow Actions)
Status -Rejected
• Recall Actions (Workflow Actions)
Recalled – Admin or by the Approver.

Jump Start Approval process

Approval Process.
Scenario 51: Multi Step Approval process

• When a new Position is created by Mario Riuz,

If the Paygrade <300 it goes to Phil for approval.


If the Paygrade >300 and 400 it goes for Phil for approval-> and Meghan Smith for
final approval

• Entry Criteria – Status Equals to New


• Final Approval Actions
Status- Open
Sub Status- Approved
Final Rejection Actions
Status- Closed
Sub Status – Rejected

• Approvals consist of 6 parts:


• Process Definition (Global Characteristics)
Object - Position
Entry Criteria. – Status= New
Send an Email Alert to the Approver
Submitter
Record Edit ability
Add the Submit for Approval button and Approval History related list to
all Opportunity page layouts

• Initial Submission Actions (Workflow Actions)


No

• Step Definition (Decision Criteria & Approval Assignment)


1-Step – Paygrade <300 Phil for Approval
2-Step – Paygrade >300 and 400 Phil and Meghan for final
approval (Contains)

• Final Approval Actions (Workflow Actions)


Status = Open
Substatus=Approved
Final Rejection Actions (Workflow Actions)
Stats =Closed
Sub status=Rejected or not approved

13-April-2022
Scenario 52:
Skip Level Approval Process.
When a new Position is created by Mario Riuz,
If the Paygrade <300 it goes to Phil for approval.
If the Paygrade >300 and 400 it goes Meghan Smith for approval
Entry Criteria – Status Equals to New
Final Approval Actions
Status- Open
Sub Status- Approved
Final Rejection Actions
Status- Closed
Sub Status – Rejected
Hint: Enter this step if the following criteria are met ,else Go to Next
Record:
Process Builder
Flows

Process Builder:-

• Process Builder is a ‘point and click’ administrator tool in Salesforce that can be
used to set up automation functions that help you in the sales process. It was
launched in 2015 as a successor to its Workflow feature. Workflow still works,
although it is no longer included in Salesforce updates.
• The Process Builder tool allows you to easily automate business processes using a
convenient graphical representation of your process as you build it. Automated
processes in the Process Builder consist of:
• Criteria that determine when to execute action groups
• Immediate and scheduled actions to execute when those criteria are met
• Any change that causes a record to match the criteria automatically triggers the
action group.

When to use Process Builder


Consider the automation that you want to set up. Process Builder is ideal for
automation functions that need more than one ‘if this, then that’ statement to be true
before the action can take place. You can begin automation functions in Process
Builder if a record is changed, if it is invoked by a different process, or if a
message is received.
Like Salesforce Workflow, Process Builder supports time-delayed actions. You can
use it to create records, update any related record, invoke processes, interact with
Flow and Apex as well as post to Chatter.

Workflow Actions
Task
Field update
Email Alert
Send outbound SOAP message

We can use a process builder to perform around eleven automation. Below is


the list of automation.
1. Apex
2. Create a Record
3. Email Alerts
4. Flows
5. Post to Chatter
6. Processes
7. Quick Action
8. Quip
9. Send Custom Notification
10. Submit for Approval
11. Update Records

Scenario 53.

Aditya is working in the ABC organization. And your organization want when a new
Candidate /Employee is created. His/her email id should get created automatically by using
the last name or Full Name and with the company name (Example: shiva@abc.com).
Whenever we will enter the data of new Candidate with there Full Name/Last Name, an
email id will be auto-generated and Introduction Email to be sent to the candidate..

Scenario 54.
At Universal Containers (UC), company policy states that hiring managers must always
take part in the interview process. UC wants a new interviewer record to be created
automatically for the hiring manager whenever a new position is created.
Scenario 55

When Opportunity is closed Won and Amount >2Million Dollar. Create an Order record
where Order Start Date equal to Today (), Status value should be equal to Draft ,
AccountId- Reference the Opportunity AccountID

Scenario 56.

You've been given a requirement to keep contact addresses in sync with the accounts they
belong to. Use Process Builder to create a process on the Account object that updates
child Contact addresses when an account's address is updated.

The process must have an Update Records action that updates Contact mailing address
fields (Street, City, State, Postal Code, Country) when the parent Account shipping address
field values are updated

Salesforce Flows

Flows- It is also called as Visual Workflows. Flow is an application inside


the Salesforce that automates a business process by collecting data and performing
operations in your org. Flow is a powerful business automation tool
that can manipulate data in Salesforce in a variety of ways. Such application can be
created right from the org's setup with just drag-drop/point-click. The ease of
creating flows makes it the number one go-to tool when it comes to implement complex
business requirements.

UI Screens
Perform Complex actions without writing code

Flow is an application inside the Salesforce that automates a business process by


collecting data and performing operations in your org or an external system. Flow can fetch,
delete, update and create records on multiple objects

Flows in Salesforce can be implemented in two ways


• Screen Flows
• Auto-launched Flow

Screen Flows
In this type of flow, there will be a series of screen elements to gather information from the
user and perform some operation. Screen flows can be accessed from custom buttons,
custom links, Visualforce Pages etc. This type of flow is implemented if a user interaction is
needed in the process. Custom Screen has to be implemented
Screen Flows
In this type of flow, there will be a series of screen elements to gather information from the
user and perform some operation. Screen flows can be accessed from custom buttons,
custom links, Visualforce Pages etc. This type of flow is implemented if a user interaction is
needed in the process. Custom Screen has to be implemented
Auto-launched Flow
Auto-screenshot runs in the background without any user interaction. Auto-launched flows
can be accessed from custom buttons, custom links, Visualforce Pages, process builder
and Apex etc. (Coding)

Behind-the-Scenes Automation
If your business process runs behind the scenes, and it should start automatically, such as
when a record changes, you have your pick of solutions.
Build an autolaunched flow that specifies a record trigger in Flow Builder.
Build an Apex trigger with Apex code.

Guided Visual Experiences


If your business process requires input from a user, you can use a:
Screen flow
Lightning component
Since it’s the simpler solution of the two, start with a screen flow. Build rich screens
that guide users through your business process, and automate the necessary logic
and actions between those screens.
A Screen Flow is called through a button or action, or displayed in a Lightning Page or the
Utility Bar, and appears as a screen to the user to interact with. This cannot be
automatically called. With Screen Flow you can create a custom UI (user interface) and
guide users through a business process that can be launched from Lightning Pages,
Experience Cloud (previously known as Community Cloud), quick actions and more.

Which type of Flow- Screen Flow

Three Building Blocks of Flow


Elements
Interactions
Screen
Action
Sub Flow

Logic
Loops
Assignment Operators
Decisions
Collections Sort
Collection Filter

Data (DML Operations)

Create Records
Updated the Records
Get / Fetch the Records
Delete the Records

Connectors - to connect with flows and screens and Actions.

Resources
Variables
Data types, are the individual variables of data that are to be
used in a Flow – these can be strings of text, numbers, records,
formulae, or collections.

Scenario 57
Display a “HELLO WORLD” or Hi – I am learning Salesforce l Flows in Salesforce

Scenario 58
Display LOGIN USER NAME in Hello World Screen. And run or execute tis flow on Home
Page
$ Global Variables
User, Profile, ORanization, Flow.. called as Global Variables
If you want to access these variables values of object fields…
First Name : “{!$User.FirstName}”
Last Name : “{!$User.LastName}”
Scenario 59

Create a UI where you can enter Account Name, Account Number, Amount for an
Account Object where user can input these three values.

But user is able to enter the values on the screen or UI.. but the data is not stored
and it is displayed at run time (flow)

Scenario 60

Ensure the user can input the values in the screen elements and also the data or
information entered should save it in Accounts object or in Database

0015j00000dfVHMAA2 0015j00000dfVHMAA2

Scenario 61 - Replicate Scenario 60 where user can input values on the screen elements
and the data has to save in Candidate Object. and please take care of validation rules and
required files…. And display or execute that flow on Home Page (HW)
Do a Business Process Automation Tools - Comparative Study?

14-April-2022

Quiz, Everyday Morning – Revise contents… Brownies.


1) Trainer will explain the Offer Object Requirement (Mini Case Study). Enhancing
the offer object.
Record Types
Implementing Formula Fields
Implementing Validation Rules or
Any other Business Logic tools (21st-April) is the submission date.

Agenda-

Reports & Dashboards - General Concepts


Types
Four Types of Reports
Tabular
Data show in the form of Columns and Rows are called as Tabular
reports. basic type of reports.
Summary
Group By Row is called as Summary Report

Matrix
Group By Row and Column is called Matrix Report
Joined

Filter the reports


Adding formulas to the reports
Downloading the reports in Excel format
Printing a Report
Reports in Classic vs Lighting
Scheduling a Report
Report folder should be shared
You can share the report to urself and to othe team members but folder
should be save….
Start Date
End Date

Subscribing a Report
Particular Conditions or Criteria
Particular week or a day
Receive Notifications
Adding a Graph / Chart to a report
Adding Custom Formula Report
Adding Conditional Formatting to the Report
Custom Report Types
Bucket Fields
Report Export & Subscription
Folders - (Sharing Access to Reports & Dashboards)
Report Formulas - Row & Summary

Salesforce has created Standard Report Templates for all Standard and Custom
Objects

Reports

Show the result in the form of Summary


Showing the data in the form of Analytical way (Graphs and Charts)
Understand whats happening in the Application to the data…
It will also tell you where you stand…
Brief idea about the data..

Where do you enable Reports and Dashboard permissions for a particular user in
Profiles / Administrative and General User Permissions
Reports in salesforce are dynamic.

What is a Custom Report Type?

Custom report types allow you to build a framework in the report wizard, from which
users can create and customize reports. You build custom report types off of the
relationships (master-detail and lookup) between objects so that you can:
Choose which objects to display to users creating and customizing reports
Define the relationships between objects displayed to users creating and
customizing reports
Select which objects' fields can be used as columns in reports
With custom report types, you can enable users to create reports from the
predefined objects, object relationships, and fields that you specify.
Scenario 62-
Replicate all 14 Reports that are created in the Report folder both on Custom and
Standard Objects.
Explore these reports coming out with various scenarios.
Few Reports should be generated on Sales Cloud (Objects) Applications
Few Reports should be generated on Service Cloud (Objects) Application
Create at least three different Custom Report Types

Dashboards Components
Dynamic Dashboards

Dashboard

• Where can see all the reports in one place


• It is graphical representation of data showing in the form of Analytics view
with charts and graphs.
• It is one place where you can represent the data to your leadership…
• Without reports you cannot create dashboards
• Dashboards are dependent on Reports
• You cannot create a dashboard with Tabular reports

Dashboard Components
We can place various components.

16-April-2022

Data Management

Handle the data in Salesforce


Where is the data getting stored or saved… on a UI.
It is getting saved in database…
What database salesforce is using.. (Oracle)

DML Operations
Insert
Update
Upsert (Insert + Update)
Delete

Need to perform above operations on my tables / objects with bulkify


How do I perform..

How many ways or methods you can perform DML Operations on your objects
Four ways

1) Data Import Wizard


2) Data Loader
3) Dataloader io
4) Workbench

1) Data Import wizard

Its an internal tool within the salesforce where you can perform below DML operations
It supports only three DML Operations
Insert
Upsert
Update
It will support Data Import Wizard to import accounts, contacts, leads, solutions, campaign
members, person accounts, but not support for all Standard objects … but supports all Custom
Objects
******* It will support 50K records at a time..********** 1 Cert
Salesforce supports only .csv file for performing any DML operations
Whenever you are performing any DML operations, Salesforce fields and .csv file header fields
should match. ensure you need to map these fields in the Data Import Wizard

Scenario 63- Create a table as below and Perform Insert, Update and Upsert
Operations.

Exercise: Activity for Salesforce Import Wizards


1) Create a Book Object with Fields

Book Name Text


Book ID Text
Author Text
Book Type Pick List (Fiction, Classic, Drama,
Biography)
Price Currency
Create a Tab
1) Add it to the Tab Section

Insert to add new records.

Data Loader

It was an external tool.


You need to download this software …before you install u need to jdk 11.0 software installed in ur
laptop
Data Loader is a client app for the bulk import and export of data. Install Java Runtime Environment
(JRE) version 11 or later, for example, Zulu OpenJDK version 11 or later, before installing Data
Loader.
With data in a comma-separated values (CSV) file, Data Loader can create, edit, or delete
Salesforce records for any standard or custom object.
Data Loader exports Salesforce records into CSV files. You can then edit those CSV files or use
them as templates for importing data into Salesforce.
Currently Downloadable Version: 54.0.0

First Export that data into a .csv file… and you that .csv file template for any DML Operations

Data Loader will support below DML Operations

Export - Export the data from an object


Export All - Export the data from object and from Recycle bin
Import -
Update
Upsert
Delete
Hard Delete - Permanent Delete

***** Certification - 5 Million records you can bulky you can insert… the records

First Export that data into a .csv file… and you that .csv file template for any DML Operations
Ensure both object fields and csv header field should match and map

SOQL – Salesforce Object Query Language

Scenario 64- Perform Export All, Upsert, Delete and Hard Delete operations with Data Loader
on Books objects

Dataloader io

Use dataloader.io to import, export, and delete unlimited data in Salesforce.

Scenario 65- Use Dataloader io for import, export, and delete in Salesforce.

Scenario 66- Use Workbench to perform all DML operations …

Data Export: Data Export lets you prepare a copy of all your data in salesforce.com. From this page you
can start the export process manually or schedule it to run automatically. When an export is ready for
download you will receive an email containing a link that allows you to download the file(s). ***** 1 Certi The
export files are also available on this page for 48 hours, after which time they are deleted. ****

Export Now
Schedule a Report

Mass transfer the records


Mass Delete the records - specific standard objects
Mass transfer Owner ship

Reporting Snapshots
Reporting snapshots allow users to run reports and save the report results as records on custom objects. Unlike reports,
users can schedule reporting snapshots to summarize data at specific times, and work with the summarized data similarly
to how they work with other records in Salesforce.
The benefits of using reporting snapshots include:

• Running faster reports by reporting on data that is already summarized


• Creating dashboards that refresh quickly by associating them with pre-summarized data
• Sorting and filtering specific data summaries via list views
• Viewing trends in data via custom object records

Reporting snapshots allow you to load data from a custom report to a custom object on a regularly scheduled
basis. Reporting snapshots enable you to work with report data as you would with other records in
salesforce.com.

Inadvertently

19-April-2022

Business Process Automation Tools - Comparative Study -

Workflows
Approval Process
Process Builder
Flows

Compare study - Data Loader, Data Import Wizard, & Data Export –

Sales Organization
Definition
Leads
Web to Leads
Lead Conversion
Account and Contact
Account Team
Opportunity
Opportunity Team
Product
Price Book
Opportunity Line Items
Campaign
Campaign Member
Campaign Influence
Duplicate Management
Multi Currency
Multi Language
Create an Sales app (Name it as some Sales App) and Add below objects.
Leads
Organization/Accounts
Contacts
Opportunities
Products
Price Books
Reports
Dashboards
Campaign (Most Important)

Scenario 67- Create an App (Name it as some Sales App) and Add below objects.

• Leads
• Organization/Accounts
• Contacts
• Opportunities
• Products
• Price Books
• Reports
• Dashboards
• Campaign (Most Important)

1) First Create an App (My Sales App) ...and add all the Standard Object- Refer the
PDF document..

2) Create a Campaign with the Campaign Name and details


Add Web to Lead value to the type field of Campaign
Fill the Campaign detail page
Leads-

3) Web-to-Lead Setup
Configure on Customer Application web
Where you can generate the leads from Web Application.
Code to generate web-to lead- which will automatically connect to lead object of SF..
Web-to-Lead (Built in code is there) – Configure.
Configure Auto Response Rule -
5) Configure Lead Assignment Rules (Automatically assign to Respective SalesRep)
****Automatically assign leads to users or queues based on criteria you define. You can
create multiple rules with different conditions, but only one rule can be active at a time.
****
You need to create as many as templates
Configure
i) Email Template - Auto Response
ii) Auto-Response Rules

iii) Lead Assignment Rules Lead will get automatically assigned to a Sales
user./ Sales Queue
That User should have Salesforce Licenses.
Create an Lead Assignment Template. (Email Template)
***** USer should have valid Salesforce License. *****************
iv) Web Lead to Form
Using pre-existing pages on your company's website, you can capture contact and profile
information from users and automatically generate new leads in salesforce.com, enabling
you to respond in real-time to customer requests.
****** Users should have valid salesforce license *********
Help for this Page
Using pre-existing pages on your company's website, you can capture contact and profile
information from users and automatically generate new leads in salesforce.com, enabling
you to respond in real-time to customer requests.

6) Create an Auto Response Rule and also create multiple email template as per your
Sales process. Completed
Automatically determine which email templates to use when sending auto-response
messages to new leads from your website.
7) Create Lead Assignment Rule - Assign lead to a specific Sales USer..Lead will
get automatically assigned to a Sales user./ Sales Queue
Automatically assign leads to users or queues based on criteria you define. You can create
multiple rules with different conditions, but only one rule can be active at a time.
Completed
Assignment Emails.. to be created..
Configure Web to Lead
8) Create Web to Lead (Create a Record) automatically Lead will get created in Leads
Object
**** Update the Campaign member related field by adding the lead to the respective
Campaign.
Sales user will start connecting with the lead to collect some more information and also will
set up a meeting to give demo of your products.
********************************************************************************************************
*********************************************
9) Create an Email Template and send it to the correct lead.

10) Change the lead status as contacted on the Kanban Board


11) Before you convert that lead - Phone, Rating, Email- Mandatory fields should be
updated.. you cannot convert that lead
12)***************** Lead Conversion Process *************************
Create a Validation Rule so that without updating Email, Phone and Rating, we
cannot convert a lead into Accounts, Opportunities and Contacts. (Adding Functionality)
AND(OR( ISPICKVAL( Rating , ""), ISNULL( Phone ) , ISNULL( Email )), (
IsConverted =true))
Once you convert the lead.. it will create Accounts, Opportunities and Contacts.
********************************************************************************************************
**********
Every Opportunities has to purchase a Product Or a Service. Hence I need to Create a
Product. You can always edit and create extra fields and Product Family fields… Product is
part of Opportunity Object. Here you will give the Product information but not price
information.
Scenario 68- Product- Price Book and Quote Process
Account - contact - Opportunity
Opportunity is related to Product, Price Book and Quote..
Product is related to Price Book is related to Price Book Entries
Product - Price Book Process
Product Company
|
Super Stockist (SS)
|
Distributors
Wholesalers Retailers

13)Create and Add Products into the Product Object. (Product and Opportunities are
related)
14)****Go to Price Book and Add the Products first to the Standard Price Book and add
price for each Product.
You have added the Price for each and very Product
15)Go to the Product Choose the Standard Price Book and add the respective Products to
your Opportunity. This is called Opportunity Line Item..

*********************End of Product and Price Book Process***************


Quote Process.
Product and Quote is also Related
16)You need to send a Quote to the customer on the total value. For this enable Quote
object by typing Quote in the set-up menu.

17)Create a Quote and add all the products to the Quote and if require give discount to the
customer.-

18)Sync that Quote and create the quote in an PDF file and share it to the Customer
(Revised Quote) -
Discount - Deal Cost is very high… Aditya is regular… customer
19)Update the Opportunity and compare the total Amount values in the opportunity and
quote and both should match.
20) Create a Big deal alert under Opportunity settings.
20)Update the Opportunity as Closed Won and update the fields like Lead Source and
Primary Campaign Source.
21 You can see the updates in the Campaign object with the Opportunity Cost and Closed
Won.
22) You can create a formula field where you can calculate the target amount vs Actual /
achieved amount and also % of Actual Target reached.

**************** Please complete or practice Sales Cloud as per above steps given
*************************
A price book is a list of products and their prices.
The standard price book is the master list of all your products and their default standard
prices. Salesforce creates the standard price book when you start creating product
records. It includes all your products and their standard prices regardless of any custom
price books that include those products.
A custom price book is a separate list of products with custom prices, called list prices.
Custom price books are ideal for offering products at different prices to different market
segments, regions, or other subsets of your customers. Create a separate price book for
each set of customers that you want to address. For example, if you have one set of prices
for domestic customers and another for international customers, create a domestic price
book and an international one.

What are Account Teams?

When you collaborate on accounts with colleagues, use account teams to facilitate
teamwork and track progress. Roles on a team can include an executive sponsor, a
dedicated support agent, and a project manager, for example. Team members can be
internal users or partner users.
Why use Account Teams?
Account Team defines additional users that are involved in an Account, in addition to the
Account Owner. The additional users added as the Account Team can have extra access
permission or without extra permission Account and on the related Contact, Opportunity,
and Case.
Adding members to an account team serves several purposes
Documentation & accountability. Clearly defining each user’s role within the management of
an account provides an easy way to establish accountability.
Record access. When a user is assigned to an account team, they are granted record-level
access to the account record and some of its related records:
Add Teams to Your Accounts
If your Salesforce admin has enabled account teams, the Account Team related list appears
on each account. You can add, edit, or remove team members.
Account Teams help multiple users to better collaborate on accounts by defining a role for each team member,
setting record-level access individually, and viewing teams in list views and reports. When enabled, the account
teams feature is available in Salesforce Lightning, Salesforce Classic, and the mobile app. Users may prepare
default account teams for speedy setup of new accounts. Account Teams are not the same as opportunity teams.

1) You can add Account Teams for a records


2) Enable in Set-up -> enable Account Teams
3) Add a default Account team
4) Add users and Roles and Access level
5) ******** Account Team you can provide Read and Write Access to Account, Opportunity and Cases
object records************
Scenario 69- Create Accounts team

Opportunity Team

Salesforce opportunity teams


Opportunity Teams help multiple users to better collaborate on opportunities by defining a role for each team
member, setting record-level access individually, and viewing teams in list views and reports.
When enabled, the opportunity teams are available in Salesforce Lightning, Salesforce Classic, and the
mobile app. Users may prepare default opportunity teams for speedy setup of new opportunities. Opportunity
Teams are not the same as account teams.
If you’d like to use opportunity splits, enable team selling first, then enable opportunity splits.

Scenario 70- Create Opportunities team

Campaign Member
People who are part of sales
Who participate in campaign
As an organizer..

Campaign members are the contacts and leads in your CRM that you included in the campaign and
are trying to market to
Scenario 71- Create Campaign members
Campaign Influence
Opportunity Revenue
Campaign Data

Salesforce Campaign Influence is how Salesforce Opportunities are associated with the Campaigns
that helped generate them. It’s all about joining the dots between sales revenue (stored in
opportunities) and marketing data (stored in campaigns) – and therefore, is the fundamental
connection in measuring Marketing ROI (return on investment).

Configuring the Campaign Influence in Lightning:


Click Gear Icon on top right side | Click Setup.
1. In the "Quick Find" search box, enter Campaign Influence | click Campaign Influence
Settings.
2. Click Enabled and Save.
3. After you have enabled the Campaign Influence, navigate to the User detail page:
4. In the "Quick Find" search box, enter Users | click Users.
5. Click on the name of the user you want to assign license and scroll down to the Related list
Permission Set License Assignments and assign either "CRM User" or "Sales User" license
to the User.
6. Create a permission set with the "Campaign Influence" permission
7. Click Gear Icon on top right side | Setup | Users | Permission Sets
8. Click on the New button
9. Provide the name of the label as Campaign Influence
10. Select the license as CRM User or Sales user
11. Click on Save
12. Click App Permissions | Edit | Enable permission "Campaign Influence" on the permission
set.
13. After Enabling the Campaign Influence, Click on Manage Assignment button and select
name to assign it to or other users you want to have that permission set.

Scenario 72- Implement Campaign influence with Opportunity record..

Duplicate Management
Maintaining clean, accurate data is one of the most important things you can do to get the most out
of Salesforce. It builds the trust of your sales team and helps you work toward complying with
various data protection and privacy regulations. Salesforce gives you tools for managing duplicates
one at a time and across your org, and to track your progress in eliminating duplicates.
To maintain a clean and accurate data in an organization, Salesforce introduced a new concept
called Duplicate Management with Data. This feature provides an effective solution to control
whether to allow duplicate records or not in Salesforce as well as when to allow such duplicates.
The feature supports following 3 objects:
• Lead
• Contact
• Account
Here, we will discuss how to create a matching rule and duplicate rule for Lead.

Scenario 73 – Implement Duplicate rules and Matching rules on Books object and try to
figure it out no duplicates found related list on the layout..

21-April-2022

Compare - Data Loader, Data Import Wizard, & Data Export.


Business Process Automation Tools - Comparative Study

Laptops
Printers
Smart Phones

To get the problem rectified…

Ashwin - Marketing Team - Who help in conducting various campaigns


Sales Team - Did a Wonderful job for converting major hot leads to Accounts, contacts
and Opportunities
Contacts
Aditya
Srija
Siddhika
Service Team – will take of service related queries.
Customer Executive – track the queries,
Service Engineers –who can rectify ur issues
Close the tickets within the SLA’s

Communication Process between Customer and Service Center / Organization. Service Process
• access to self-help capabilities, and by streamlining all customer service interactions.

Scenario 74: Set-up Service Cloud Process

Contents:
Step- No 1
• Service Cloud Objects / or Service Cloud App
Add Objects
Accounts
Contacts
Opportunities
Cases
Solutions
Knowledge
Step-2
Go to Case Object and add “Hardware” and “Software” Values to the type Field
picklist.

Step-3
• Create Case Auto Response Rules – Configure & Create an Email Template - Auto
Response Email Template

Step-4
• Create Case Assignment Rules – Configure & Create an Email Template stating
that the case is assigned to a Service Engineer Completed

Step 5- Review the Case Object

Cases can be generated


Call
Walk to a Customer Care center
Email and Web
Messaging Event..

Step No 6

• Create Web-to-Case HTML Generator


Step No 7

Company Business Hours


Enable Business Hours Field on all Case Page layouts…

Select the days and hours that your support team is available. These hours, when
associated with escalation rules, determine the times at which cases can escalate.
If you enter blank business hours for a day, that means your organization does not
operate on that day.

• Configure Case Escalation Rules -


Work Flow- If the case created > business hours, the status field should be
changed to Escalated and email alert should go to the Manager

Solutions and Knowledge will help the customer executive to provide solutions on
the spot..

• Solutions

Scenario 75:
Additional Activity- You can create a solution and send this solution for Approval to
a Solution Manager User.

How do you add a solution to a Case?

Scenario 76: Additional Activity – You can create a formula field called Duration
Taken to Close the Case. which will calculate the total duration taken to close the
case
Date/Time Closed - Date/Time Opened

Case Teams-

Email to Case: Scenario 77:


allows us to generate a case automatically when a customer emails in. (generally on
support email). It also populates some case information automatically saving manual effort.
Salesforce automatically creates cases and auto-populates case fields when customers send
messages to the email addresses you specify.
Salesforce Email-to-Case should be used when you have one or more support email addresses
which agents handle manually. We can configure more than one Email-to-Case channel if our
organization has multiple support email addresses & processes.
22-April-2022

Lightning Service Console Scenario 78:

The Service Console is a standard Salesforce Lightning console app that you can customize to
meet the team’s case management needs, allowing them to access all things case-related, all from
one screen
It streamline the processes of service agents in order to meet all service needs. With the help of
this, agents can speed up the activities like creating new contacts, cases, registering products and
processing returns, all without losing the context of the interaction or needing to switch screens
Each and every service representative (reps) and manager want to see the things like Accounts,
Contacts, associated Cases with Accounts and Contacts, activities of reps on a single tab instead of
switching to multiple tabs in order to see different cases with different associated Accounts and
Contacts. All this can be achieved with the help of Salesforce Lightning Service Console.

Softphone utilities let your Lightning console users make calls directly from Salesforce. Before
you add the softphone utility to your Lightning console app, first set up and configure the softphone
and Open CTI.

Definition – Knowledge Base

Who sees her articles? Other agents, customers in self-service sites, or customers searching on a
public website. Who sees her articles? Other agents, customers in self-service sites, or customers
searching on a public website.

Lightning Knowledge – Impl Scenario 79:

Knowledge Settings
Data Category Groups & Data Categories
Record Types, Custom Fields & Page Layouts
Surface Knowledge Articles inside Lightning Console
Auto Suggestion - Knowledge Articles (Case Subject)

• Enable Lightning Knowledge and assign appropriate user licenses.


• Customize page layouts and record types to support knowledge article management.
• Customize access to, permissions for, and visibility of knowledge tools and processes.
• Create and manage articles to ensure quality of information.
• Manage and close cases more efficiently using knowledge articles.
She needs Knowledge-specific permissions and settings enabled to help her successfully create
and manage knowledge articles and use those articles to close cases and navigate customer
service responsibilities.

Quick Text and Macros

25-April-2022

Aditya Raj- Data Loader

Apex Classes
VFP
Standard Controller
List Controller
Custom Controller
Custom Extension Controller
SOQL, SOSL and DML
Exception Handling
Asynchronous Apex
Apex Triggers
Apex Test Classes
Sandbox Creation & Deployment Process

Scenario 80:

Experience Cloud
- It’s built on 360 degrees’ platform
- It will connect with Customers and Partners on a Social platform
- Earlier it was called as Community Cloud and now it is called as
Experience Cloud
- Sales and Service Products Companies
- Build strong relationship with source of truth

Customer Portal
Partner Portal
Community Portal-
Help u to create the sites..

• Create multiple experiences for specific needs.


• Extend business processes to partners and customers.
• Integrate data (such as orders or financial information) from third-party providers.
• Use themes and templates to create beautiful branded experiences.
• Use Salesforce CMS to create content and deliver to any channel.
27-April-2022
Salesforce Platform Developer 1 Course
• OOPs
• Introduction to Apex
• Data Types and Logic Control in Apex
• Apex Classes
• sObject Relationships
• SOQL, SOSL
• Data Manipulation Language
• Apex Debugging
• Apex Triggers, Events, Context Variables, Recurrsive Triggers
• Trigger order of execution
• Exception Handling
• Test Classes
• Visualforce Pages/MVC Pattern
• Visualforce Controller (Essentials) - Standard, Custom and Extensions
• Concept - Synchronous vs Asynchronous operations
• Apex annotations & interfaces (@future, Batchable, Schedulable)
• (Queuable, @InvocableMethod)
• Deployment using Change sets

OOPS

Blueprint
Car - States

Name
Model
Engine Type
No of Tyres

Behaviors
Driving
Accelerating
Apply Brakes

Car – BMW, Merc, Audi – Objects.

Laptop - Dell, Mac, Lenovo

On Demand Applications….. on Cloud..

integer Integer (Wrapper Class)


• Apex supports the following data-types:
• Primitive (Integer, Double, Blob, Long, Date, Datetime, String, ID, or Boolean, String, Object,
Time)
• Collections (Lists, Sets and Maps), sObject
• Enums - Just like in other programming languages, Enum type represents a fixed set of
named constants.
• An enum is a data type which contains fixed set of constants. It can be used for days
of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and
SATURDAY) ,directions (NORTH, SOUTH, EAST and WEST) etc. The enum constants are
static and final implicitly.
• Classes, Objects and Interfaces

Types of variables..
Local Variables
Instance Variables //Instance variable are also variable of object commonly known
as field or property. They are referred as object variable.
Static Variables / Class

Data Types : Date

Scenario 81:

addDays(additionalDays)
Adds the specified number of additional days to a Date

Date myDate=Date.newInstance(2020, 03, 06);


Date NewDate=myDate.addDays(10); //addDays()
System.debug(NewDate);

Date myDate=Date.newInstance(2020, 03, 06);


Date NewDate=myDate.addMonths(5); // addMonths()
System.debug(NewDate);

date myDate = date.newInstance(1990, 11, 21);


date newDate = myDate.addYears(3); //addYears()
System.debug(newDate);

daysBetween(secondDate)

Returns the number of days between the Date that called the method and the specified date.

Date startDate = Date.newInstance(2008, 1, 1);


Date dueDate = Date.newInstance(2008, 1, 30);
Integer numberDaysDue = startDate.daysBetween(dueDate); //Days Between
System.debug(numberDaysDue);

Boolean isActive = true;


System.debug(‘Boolean: ‘ + isActive); //Boolean
System.debug(‘Date: ‘ + Date.newInstance(2020, 01, 18)); //Date
Datetime currDateTime = Datetime.now();
System.debug(‘Date: ‘ + currDateTime); //DateTime
System.debug(‘Time: ‘ + Time.newInstance(22, 40, 36, 03)); //Time

Controlling Statement

• If-else
• Switch-Case
Untill Summer 18 release Apex doesn’t have Switch statement … it was added in the
platform
Syntax is different … when it is compared to Switch Case statement..
Instead of Case .. we use when keyword..
• Continue statement
• break statement
Loops
• For loop
• while loop
• do-while loop

Datatype[] arrayname = new datatype[size];

String [] products=new List<String>(); // List collection


products.add('Laptop');
products.add('Keyboards');
products.add('Mouses');
products.add('Monitors');
products.add('Routers');
products.add('Switches');

for(integer i=0; i<products.size();i++)


{
System.debug('The products are ' +products[i]);
}

Apex allows you to use the private, protected, public, and global access modifiers when
defining methods and variables

Private :- This is the default and means that the method or variable is accessible only within the
Apex. If you do not specify an access modifier, the method or variable is private.

Protected :- This means that the method or variable is visible to any inner classes in the defining
Apex class, and to the classes that extend the defining Apex class. You can only use this access
modifier for instance methods and member variables.

Public :- This means the method or variable can be used by any Apex in this application or
namespace.
global :- This means the method or variable can be used by any Apex code that has access to the
class, not just the Apex code in the same application. This access modifier should be used for any
method that needs to be referenced outside of the application, either in the SOAP API or by
other Apex code. If you declare a method or variable as global, you must also declare the class that
contains it as global.

Class
Private
Public
Global
Abstract
Virtual

1. Object is an instance of a class while class is a blueprint of an object. An object represents


the class and consists of properties and behavior.
2. Properties refer to the fields declared with in class and behavior represents to the methods
available in the class.
3. In real world, we can understand object as a cell phone that has its properties like: name,
cost, color etc and behavior like calling, chatting etc.
4. So we can say that object is a real world entity. Some real world objects are: ball, fan, car
etc.
5. There is a syntax to create an object in the Java.

Student std = new Student();


Here, std is an object that represents the class Student during runtime.
The new keyword creates an actual physical copy of the object and assign it to the std variable. It
will have physical existence and get memory in heap area. The new operator dynamically allocates
memory for an object.

HTML – Modern HTML 5.0


CSS
Java Script –

Angular -

Static- Variables, Methods, Blocks

Multilevel
Hierarchical

Encapsulation
Polymorphism
Method Overloading
Method Overriding
Abstraction
Interfaces
Collections
List
Set
Map

Class - Food
Veg()
Non Veg()

Class Lunch Class Dinner

Class Lunch extends Food

Class Dinner extends Food

Encapsulation:

Encapsulation:
The wrapping up of data and methods together is called encapsulation. For example, if we
take a class we write the variables and methods inside the class. Thus, class is binding them
together. So class is an example for encapsulation.
Encapsulation
The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private, it means it can only be accessed within the same class. No outside class can
access private data member (variable) of other class.

*How to implement encapsulation in java/Apex:


1) Make the instance variables private so that they cannot be accessed directly from outside the
class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
3) Private members cannot be accessed outside of the class. If you want to access private
members outside of the class you must write getter and setter methods

Apex Properties: An Apex property is similar to a variable; however, you can do additional things
in your code to a property value before it is accessed or returned.
Property definitions include one or two code blocks, representing a get accessor and a set
accessor: The code in a get accessor executes when the property is read.
The code in a set accessor executes when the property is assigned a new value.
If a property has only a get accessor, it is considered read only. If a property has only a set
accessor, it is considered write only. A property with both accessors is considered read-write.
Public class BasicClass {
// Property declaration
access_modifier return_type property_name {
get {
//Get accessor code block
}
set {
//Set accessor code block
}
}
}

Why Encapsulation?
• Better control of class attributes and methods
• Class attributes can be made read-only (if you only use the get method), or write-only (if you
only use the set method)
• Flexible: the programmer can change one part of the code without affecting other parts
• Increased security of data

Public Void setName(String Name)


{
Writing the value
}

Public String getName()


{
Return N;
Reading the value
}

printSum(integer x, integer y)

printSum(Decimal x, Decimal y)

printSum(integer x, integer y, integer z)

Apex supports method overloading and always occur in the same class

Method Overriding

Redefining the base class method in derived class is called Method Overriding
Redefining

Method Overriding:
================
Redefining the base class method in derived class is called Method Overriding
1. Overridden methods should have the same argument list.
2. Overridden methods should have the same return type.
3. Overridden methods can have the same access level and cannot be narrower.
4. Overridden method invocation is decided at run time
5.*** To override any method in the Parent class that must be declared as 'virtual' and Child
class method must be declared as 'override'
Abstraction and Abstract Class Implementation
//Example for abstract class- IF any class having at least one Abstract method that is called as
Abstract class. Abstract Class:
=============
1. It's a class which contains at least one abstract method.
2. abstract class and method must be prefixed with 'abstract' keyword
3. abstract class cannot be instantiated
4. When a class is inherited from an abstract class, it must implement abstract methods of
an abstract class, otherwise the derived class also becomes abstract class
5. By default abstract methods are virtual.

Cognizant
Two types of Employees

FullTime Employee Contract Employee

Salary

Salary process is different Salary Process is different

Public decimal PrintMonthlySalary()


{
Implementation is different Implementation is different
}

Collections

Type of variable - it will store multiple number of records..


It is used to store, fetch and manipulate data (DML Insert, update,

List
Set
Map

List is an ordered collection


It will accept duplicate values
Primitive
sObjects
User Defined Object
Apex Objects
<>

List<String> studentlist=new List<String>();


List<Integer>marks=new List<Integer>();

List
Integer
Marks
New - allocating a memory
List<Integer>();
<>

List<String>studentlist=new List<String>();

List<Account>accs=[Select Name,AnnualRevenue from Account LIMIT 5];


System.debug(accs);

List Program

List<String>mylist= new List<String>();


mylist.add('Sashank');
mylist.add('Deepak');
mylist.add('Ashwin');
mylist.add('Mukul');
mylist.add('Sai Bharghav');
mylist.add('Sujeet');
System.debug(mylist);

List<String>allName=new List<String>();
allName.addAll(mylist); // mylist is getting added to anoter list called allName... addAll()....

System.debug('Second Index Name ' +mylist.get(2));


System.debug('Fourth Index name is ' +mylist.get(4));

Set Collection

Set<String>Products=new Set<String>{'Mobiles','Computers', 'Laptops'};


System.debug('Product Names are ' + Products);

Products.add('Routers');
System.debug('Product Names are ' + Products);
System.debug('Product Names are ' + Products.size());

Products.add('Laptops');
System.debug('Product Names are ' + Products);
System.debug('Product Names are ' + Products.size());

Products.remove('Laptops');
System.debug('Product Names are ' + Products);
System.debug('Product Names are ' + Products.size());
Boolean result=Products.contains('Laptops');
//check wether the set contains the particlar element Laptops or not and retrns true or false
System.debug('Does the set have the value' + result);

List<String>Names=new List<String>{'Dell Bhoomi','J2EE','SFDC'};


Set<String>slist=new Set<String>();
slist.add('Dell Bhoomi');
slist.add('Sony');
slist.add('AIML');
slist.add('SFDC');
boolean result1;
result1=slist.retainall(Names); // List of Elements to Retain... keep only the values that are existing
in the list or set
system.debug(result1);

Map Collection

Map<String,String>currencies=new Map<String,String>();
1- String – Key - will be Unique….. only
2- String - Value – for key what is the value.. value can be unique or duplicate values

Country - First String


Currency - Second String

Map<Integer,String>StudDetails=new Map<Integer,String>();
Key - Roll No (Integer)
Values - Ashwin , Shashank

MAP
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and
values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in
Apex types.
To declare a map, use the Map keyword followed by the data types of the key and the value within
<> characters.

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


Map<ID, Set<String>> m = new Map<ID, Set<String>>();

Key value pairs-


Key value should be unique. If I want to access the values, I need to have key. Values can be
duplicate.
Put(), Set(), Get()

Total Use cases for Apex Programming till Collections 49 Programs / Use Cases

29-March-2022
Business Process Automation Tools - Comparative Study – Satellites Team on Monday

Review the Orgs-

SQL- simple English language to communicate with the Database -

Retrieving the data or Searching the data..

Select * from Employee –


Select * will not work in Salesforce

▪ SOQL is not used in Triggers and can be used only in Apex classes and anonymous
block.

SOQL in Salesforce.
▪ SOQL stands for "Salesforce Object Query Language”.
▪ It returns Records.
▪ Records are stores in collection. Records are pertaining to single sObject.
▪ SOQL is similar to the SELECT statement in the widely used Structured Query Language
(SQL) but is designed specifically for Salesforce data.
▪ Search in single sObject and it retains records.
▪ SOQL retrieves the data from the database using “SELECT” keyword.
▪ It works on multiple objects at the same time.
▪ SOQL is not used in Triggers and can be used only in Apex classes and anonymous
block.
▪ SOQL against the same field will be slow.

The following are SOQL keywords :


AND, ASC, DESC, EXCLUDES, FIRST, FROM, GROUP, HAVING, IN, INCLUDES, LAST,
LIKE, LIMIT, NOT, NULL, NULLS, OR, SELECT, WHERE, WITH

Select ID,Name from Account

Select FirstName,LastName from Contact

Select Name,Department__c, Min_Pay__c from Position__c

Select FirstName,LastName from contact where FirstName NOT IN('Rose','Sean')

Select FirstName,LastName from contact where FirstName IN('Rose','Sean')

Select Name, Department__c, Min_Pay__c from Position__c where Department__c IN('IT',


'Sales', 'Engineering')

Select Name, Department__c, Min_Pay__c, Max_Pay__c from Position__c where


Min_Pay__c >=4000 and Max_Pay__c <=8000
Select Name, Department__c, Min_Pay__c, Max_Pay__c from Position__c where
Department__c ='IT' OR Department__c ='Engineering'

Select Name, Department__c, Operating_System__c, Min_Pay__c, Max_Pay__c from


Position__c where Operating_System__c INCLUDES('iOS','Android')

Select FirstName,LastName,Phone from contact where Phone!=null

Select FirstName,LastName,Phone from contact where Phone=null

Select FirstName,LastName,Phone,Email from contact where Phone=null and Email =null

Select FirstName,LastName,Phone,Email from contact where (Phone != null and Email


!=null) or Email=null

Select id,Name from Account where Name LIKE 'Edg%'

Select id,Name from Account where Name LIKE 'E%'

Select Name,Industry From Account ORDER By Industry DESC

Select Name,Amount from Opportunity Order by Name Desc

Select FirstName, LastName, Phone from contact ORDER BY FirstName DESC NULLS
LAST.

Select FirstName,LastName,Phone from contact where Phone!=null ORDER BY


FIRSTNAME ASC

Select Name,Amount from Opportunity LIMIT 20

Select Name,Amount from Opportunity Order By Name ASC LIMIT 20

Select Name,Amount, StageName from Opportunity where StageName='Closed Won' Order


By Name ASC LIMIT 20

OFFSet

Select Name,Amount, StageName from Opportunity Order By Name ASC LIMIT 20


OFFSET 10

Select Name,Amount, StageName from Opportunity Order By Name ASC OFFSET 10

Aggregate Functions:
Min()
Max()
Sum()
Avg()
Count()
Count(Field Name)
Select StageName,Sum(Amount) from Opportunity Group By StageName

Select StageName,Sum(Amount),Avg(Amount) from Opportunity Group By StageName


Having Avg(Amount)>=350000

select LeadSource, Count(Name) from Lead Group By LeadSource

Select StageName,Count(Name) from Opportunity Group By StageName

Select Sum(Amount) from Opportunity where isClosed=false AND Probability > 60

Select Fields(All) from Account LIMIT 10

Select Fields(STANDARD) from Account LIMIT 10

Select Fields(Custom) from Account LIMIT 10

Select Name, ID, Fields(Custom) from Account LIMIT 10

Select Name, Count(ID) from Account Group By Name Having Count(ID)>1

Select Name, Count(StageName) from Opportunity Group By Name Having


Count(StageName)>1

Select Name, Count(StageName) from Opportunity Group By Name HAVING NAME LIKE
'Univer%'

SOQL Queries

List<Position__c> plist=[Select Name,Department__c, Status__c from Position__c];


for(Position__c p:plist)
{
System.debug('Position is ' + p.Name + ' Department ' + p.Department__c + ' And Status '
+p.Status__c);
}

****************************************************************************************************
List<Contact>contactlist=[Select ID,Name from Contact Order by Name Desc Limit 10];
for(Contact c:contactlist)
{
System.debug('Name of the contact ' +c.Name);
}

****************************************************************************************************

// Apex with SOQL to fetch the Account Records


public class FetchAccountRecords
{
public static void FetchAccounts()
{
List<Account>acc=[Select Name,Industry from Account];
for(integer i=0;i<acc.size();i++)
{
System.debug(acc[i]);
}

}
****************************************************************************************************
List<Position__c> plist=[Select Name,Department__c, Status__c from Position__c where
Status__c='Open' ];
for(Position__c p:plist)
{
System.debug('Position is ' + p.Name + ' Department ' + p.Department__c + ' And Status '
+p.Status__c);
}

****************************************************************************************************
// SOQL qeries support Apex variable binding.. you can use an Apex variable and filter
SOQL records against that
//value of that variable
String pstats='Open';
List<Position__c> plist=[Select Name,Department__c, Status__c from Position__c where
Status__c=:pstats ];
for(Position__c p:plist)
{
System.debug('Position is ' + p.Name + ' Department ' + p.Department__c + ' And Status '
+p.Status__c);
}

****************************************************************************************************
Integer pCount=[Select count() from Position__c where Status__c='Open'];
System.debug('No of Open Position Records ' +pCount );

****************************************************************************************************
Position__c p=[Select Name,Department__c, Status__c from Position__c order by name
Limit 1];
System.debug('Position Record ' +p);

Total 42 SOQL Queries


SOSL in Salesforce.
▪ SOSL stands for “Salesforce Object Search language”.
▪ It returns fields.
▪ Records are pertaining to different sObjects.
▪ Search in entire Org and returns fields.
▪ SOSL retrieves the data from the database using the keyword “FIND“.
▪ It doesn’t work on multiple objects at the same time and need to write different SOQL
queries for different objects.
▪ Searching data in your objects
▪ Search the data and retrieve the data..

1. Find {joe} – Finding joe anywhere in the system… (Org) returning ID where Joe is
found

2. Find {Suneel} IN Name Fields Returning Candidate__c

3. Find {Grand} IN Name Fields Returning Opportunity

4. Find {Grand} IN Name Fields Returning Opportunity(Name,Amount,StageName)

5. Find {Edg*}

6. Find {Edg*} in Name fields returning Opportunity(Name,Id)

7. Find {Edg*} in Name fields returning Opportunity(Name,Id Order by ID)

8. Find {Edg*} in Name fields returning Account(ID,Name),Contact, Opportunity, Lead

9. Find {Edg*} in Name fields returning Account(ID,Name),Contact(Name),


Opportunity(Name), Lead

10. Find {Edg*} in Name fields returning Account(ID,Name),Contact(Name, Salutation


Order by Name), Opportunity(Name, Amount, StageName Order By StageName
Desc), Lead

11. Retrieve Name & Industry from Account and Name & Department from Position
where Names must be started with ‘sa’.

List<List<Sobject>> mylist=[Find 'sa*' in Name Fields returning


Account(Name,Industry),
Position__c(Name,Department__c)];
List<Account>alist=mylist.get(0);
List<Position__c>plist=mylist.get(1);
for(Account a:alist)
{
System.debug('Account Name ' + a.Name + ' Industry ' + a.Industry);
}
for(Position__c p:plist)
{
System.debug('Position Name ' + p.Name + ' Department ' + p.Department__c);
}

Total 12 SOSL Queries executed

02-May-2022
Exceptions

Try and Catch…

Try -

try and catch in Apex


Try and catch both are Java keywords and used for exception handling. The try block is used to
enclose the suspected code. Suspected code is a code that may raise an exception during program
execution.
try{
int a = 10;
int b = 0
int c = a/b; // exception
}
The catch block also known as handler is used to handle the exception. It handles the exception
thrown by the code enclosed into the try block. Try block must provide a catch handler or a finally
block. We will discuss about finally block in our next topic.
The catch block must be used after the try block only. We can also use multiple catch block with a
single try block.

Arrayoutofbound Exception in Java


System.DmlException: Insert failed. First exception on row 0; first error:
REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]

You are trying attempt to access the fourth element of List

SOQL Query

List<Account> lm = [SELECT Name FROM Account WHERE Name = 'XYZ'];


System.debug(lm.size()); - List

Account m = [SELECT Name FROM Account WHERE Name = 'XYZ' LIMIT 1];
m- is a single object variable
Below code

//QueryException
try{
/* the below SOQL statement doesn't cause an exception, even though yo don't
have a accouunt record wit name='XYZ'..
The list lm will be empty*/
List<Account> lm = [SELECT Name FROM Account WHERE Name = 'XYZ'];
System.debug(lm.size());
// Output is lm.size(0)..

/* Problem is below statemen causing a System.QueryException ... becuase we are assigning


the
return value to an Account object... XYZ..
but no Account is returned .....*/

Account m = [SELECT Name FROM Account WHERE Name = 'XYZ' LIMIT 1];
}
catch(QueryException qe)
{
System.debug('The following excepton has occured : ' + qe.getMessage());
}

try{
Position__c pinv = new Position__c(
Job_Description__c='Machine Learning');
insert pinv; // Record will get inserted...
// Query the Position we just inserted
Position__c v = [SELECT Name FROM Position__c WHERE Id = :pinv.Id];
// Causes an SObjectException because we didn't retrieve
// the Description__c field.
String s = v.Job_Description__c;
}
catch(SObjectException se)
{
System.debug('The following exception has occured' +se.getMessage());
}

MathException
ListException (Array outbound except)
Null Pointer Exception
Query Exception
DML Exception
SObject Exception

Total 7 exception Programs we have completed

DML Operation
DML – Data Manipulation Languages

Declarative Approach… How did you perform various DML Operations?

What are the tools that you have used…

Insert / Import
Update
Delete
Upsert
Export
Export All
Hard Delete

150 … Not more than 150 DML Statements


➢ 150 ….. you are crossing the Governor Limits

Single Insertion

Account myAcct2 = new Account();


myAcct2.Name = 'Tina’s Teas';
myAcct2.AccountNumber = '623956';
myAcct2.Phone = '555-0129';
Insert myAcct2; // DML statement that we executed

Account newAccount=new Account(Name='OU Camps');


insert newAccount;

Tools that we have used

1. Data Import Wizard


2. Data Loader
3. Workbench
4. DataLoader.io

You can perform above DML operations by using the Apex Code or DML statements or
Methods of “ Database Class”

Insert / Import
Update
Delete
Upsert
Merge
UnDelete

Insert
Position__c p1=new Position__c(Name='Test Manager',Job_Description__c='Testin Apps',
Max_Pay__c=95000, Min_Pay__C=8888);
Position__c p2=new Position__c(Name='GCP Architect',Job_Description__c='Google
Cloud', Max_Pay__c=15000, Min_Pay__C=9888);
Position__c p3=new Position__c(Name='Oracle Architect',Job_Description__c='Oracle
Cloud', Max_Pay__c=12000, Min_Pay__C=9888);

List<Position__c> plist=new List<Position__c>{p1,p2,p3};


try{
Insert plist; // DML Operation
System.debug('Record Sccessfuly Inserted');
}
catch(DMLException de )
{
System.debug(de.getMessage());
}

Update: -1

Position__c p1=[Select Name, Job_Description__c, Max_Pay__c,Min_Pay__c from


Position__c where Name='Test Manager'];
p1.Department__c='Accounts';
p1.Job_Description__c='Resolvng Tech isssues';
try{
Update p1; // DML Operation
System.debug('Record pdated');
}
catch(DMLException ec)
{
System.debug(ec.getMessage());
}

Update-2

Inserting and Immediately updating the record with the respective matching using the Id
created.
Account a=new Account(Name='KGF-Part2');
insert a; // Id will get created
Account myacc=[SELECT Id,Name, BillingCity from Account where Id=:a.Id]; // Matching
the ID and update will trigger only on this sObject record
myacc.BillingCity='Hyderabad';
myacc.Industry='Banking';
try
{
update myacc;
}
catch(DMLException de)
{
System.debug('The Exception Occured' +de.getMessage());

Update 3

// List of Records with SOQL statement limiting set of records DML Update Statement Bulk
Records
public class UpdatePosition {
public static void updatePositons()
{
Position__c [] plist=[Select Name, Job_Description__c from Position__c where
Department__c='Engineering' LIMIT 5];
//Loop the records
for(Position__c pos:plist)
{
pos.Education_Qualifications__c='BTech';
}
update plist; // Update the records
System.debug('Records Updated');
}
}

Delete

Position__c p1=[Select Name, Job_Description__c, Max_Pay__c,Min_Pay__c from


Position__c where Name='Test Manager'];
try{
Delete p1; // DML Operation
System.debug('Record Deleted');
}
catch(DMLException ec)
{
System.debug(ec.getMessage());
}

Six
04-May-2022

1. Total Admin Uses cases are 80


2. Total Use cases for Apex Programming Till Collections 49 Programs / Use Cases.
3. Total 42 SOQL Queries executed on various topics.
4. Total 12 SOSL Queries executed.
5. Total 7 exception Programs we have completed.

Upsert - Update + Insert


Declarative approach
Data Import wizard & Data Loader
Apex Programming
If you are adding a new record it will check your database table or object and then it will Insert the
record
Sashank Record is already available in the database
Sashank Record insert a new record in the database

Record Id …
Matching External Id

If you are updating any existing record it will get updated.

Upsert helps avoid the creation of duplicate records and can save you time as you don’t have to
determine which records exist first.
External ID **** 1 Cert
is field in Salesforce to say that this field is primary key in external Database which can be used to
identify that external record exists in Salesforce or not.
If the record exists Salesforce will have an intelligence to update the record or it will create a record.
This field is usually references an ID from another (external) system. When a field is marked as
external Id, the field will be automatically indexed.
You can use External IDs to ensure you have an ID that can be referenced both inside and outside
of Salesforce.
Ex: If any application (Oracle) that have data of employees (like empId, name, designation etc.) is
now linking with Salesforce so when they both linked together and application's data imported to
Salesforce so at that time the empId of employees in existing application is considered as an
external Id for Salesforce.
Note: External Id is not case-sensitive – for example, “XYZ” will be matched with “xyz”. if the custom
field has enable the “Unique” attribute and the case-sensitive option for that attribute is selected,
uppercase and lowercase letters will not be considered identical.

An object can have at most 7 External IDs’ fields. The field type should be any one of auto-number,
email, number, or text. Custom fields marked as unique also count against an object’s limit of 7
External IDs’ fields.

CustExtID1
CustExtID2
Email ID - Unique
7 External Id’s

If you want to delete 50 records or 100 records from an object..


Enable Custom Object Truncate - Enabled

With the declarative approach – Data Loader with External ID

Apex Programming

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

Book__c b1=new Book__c( Book_ID__c='B054', Name='Kashmiri Files', Author__c='Anupam


Kher');
insert b1;
Book__c b1=new Book__c( Book_ID__c='B062', Name='Veronica', Author__c='Chethan Baghat');
Insert b1;

// b1 record has been inserted


// so the variable b1 has now an ID
// which will be used to match the records by upsert
b1.Price__c=987;
// Create a new book record b2, which doesn't have in the database

Book__c b2=new Book__c(Book_ID__c='B063', Name='Valamai', Author__c='Ajit Kumar');

//List which will hold the new Books to Upsert


List<Book__c> Books =new List<Book__c> {b1,b2};
// Call Upsert
upsert Books;
// Result: B1 is updated and b2 is created.

// Insert the Josh contact


Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance');
insert josh;
// Josh's record has been inserted
// so the variable josh has now an ID
// which will be used to match the records by upsert
josh.Description = 'Josh\'s record has been updated by the upsert operation.';
// Create the Kathy contact, but don't persist it in the database
Contact kathy = new Contact(FirstName='Kathy',LastName='Brown',Department='Technology');
// List to hold the new contacts to upsert
List<Contact> contacts = new List<Contact> { josh, kathy };
// Call upsert
upsert contacts;
// Result: Josh is updated and Kathy is created.

Merge :

List<Account> a1=new List<Account>{new Account(Name='Vijay Thalapathi!! Beast'),new Account


(Name='Beast')};
Insert a1;
List<Account> a1=new List<Account>{new Account(Name='Vijay Thalapathi!! Beast'),new Account
(Name='Beast')};
Insert a1;

Merger Above both Contacts

Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Vijay Thalapathi!!
Beast' LIMIT 1];
Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Beast' LIMIT 1];
try {
merge masterAcct mergeAcct; // Merge command
}
catch (DmlException e)
{
// Process exception here
}

UnDelete :
Restoring or recovering the record from Recycle bin. Records will reside 15 days in Recycle
bin after that records will be deleted automatically.
Hard Delete X UnDelete
***** 1 Cert Hard Delete – Permanently deleting the data.. u need to have Profile level Bulk API
Hard Delete..*****

Position__c plist=[Select Name, Job_Description__c, Max_Pay__c,Min_Pay__c from Position__c


where Name='Test Manager' ALL ROWS];
try
{
undelete plist;
System.debug('Record Undeleted or Restored');
}
catch(DMLException de)
{
System.debug(de.getMessage());
}

Bulk DML
You can perform DML operations either on a single sObject, or in bulk on a list of sObjects.
Performing bulk DML operations is the recommended way because it helps avoid hitting governor
limits, such as the DML limit of 150 statements per Apex transaction.
Below Example

// Create a list of contacts


List<Contact> conList = new List<Contact>
{
new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
new Contact(FirstName='Kim',LastName='Shain',Department='Education'),
new Contact(FirstName='John',LastName='Abraham', Department='Finance')
};
// Bulk insert all contacts with one DML call
insert conList;
// List to hold the new contacts to update
List<Contact> listToUpdate = new List<Contact>();
// Iterate through the list and add a title only
// if the department is Finance
for(Contact con : conList)
{
if (con.Department == 'Finance')
{
con.Title = 'Financial analyst';
// Add updated contact sObject to the list.
listToUpdate.add(con);
}
}
// Bulk update all contacts with one DML call
update listToUpdate;

Sub Queries
Write a Query to return the list of Accounts whose Opportunity Stage as ‘Closed Won’
Write a Query to return the list of Accounts whose Opportunity isClosed=’false’
Write a Query to return the list of Opportunity and Contact Name whose leadsource=’Web’

Relationship Query in Apex – Salesforce


Under Category Called One to Many Relation
Look-up
Master Detail

and often we need to fetch the list of all child records related to parent record in SOQL

Account - Dhoni Industries Contacts


i. MS Dhoni
ii. Ravindra Jadega
iii. Suresh Raina

Opportunity
i. Order- Cricket Bats – MSDhoni
ii. Order – Cricket Balls - Jadega
iii. Order - Pads and Glouses –
Suresh

Ashwin Solutoin Contact Ashwin

Most of the times, we have relationships between the objects(master-detail OR lookup) and often
we need to fetch the list of all child records related to parent record in SOQL. This can be achieved
using relationship query in Salesforce.
We can also say it as a Inner Query (query inside query).
For using relationship query, most important is, to know the Name of relationship between the
two objects. You can get this relationship name by going to the Look-up OR Master-detail field on
child object.
Using relationship queries, we can retrieve the related objects data using the SOQL query.

1. Parent to Child Relation Ship


2. Child-to-Parent relationship

Child-to-Parent relationship

For example, the Contact child object has a child-to-parent relationship to the Account object, so
the value of relationshipName in Contact is Account. These relationships are traversed by
specifying the parent using dot notation in the query, for example:
Foreign Key is your Account Object

1. Select Contact.FirstName, Contact.LastName, Contact.Account.Name from Contact

2. Select Opportunity.Name, Opportunity.Amount, Opportunity.Account.Name from Opportunity

3. Select Case.CaseNumber, Case.Account.Name from Case

4. Select ID,Name,Account.Name, Account.Industry from Contact where


Account.Industry='Energy'

This above query returns Account Names, Contact Names and Contact ID for only te contacts
whose account is related account Industry=’Energy’;

5. Contact c=[Select FirstName, LastName, Account.Name, Account.Industry from contact


where id ='0032v00002oCXKY'];
System.debug('Account Name: ' + c.Account.Name);
System.debug('Industry: ' + c.Account.Industry);

For Parent-to-Child relationships

The parent object has a name for the child relationship that is unique to the parent, the plural of
the child object name. For example, Account has child relationships to Assets, Cases, and Contacts
among other objects, and has a relationshipName for each, Assets, Cases, and Contacts. These
relationships can be traversed only in the SELECT clause, using a nested SOQL query.
1. Always One to Many.
2. Specify the relationships using a Sub Query..
3. *** For all Standard Objects sub queries, you should specify the plural name of the object
that is the name of the relationship for each object

The Child Relationship Name for the lookup field on Contact is "Contacts" Therefore, you would use "Contacts" in Account
queries to refer to Contact records whose Account field references a given Account.

Salesforce Object Query Language (SOQL) Understanding Relationship Names


Write a query which will returns all accounts, and for each account, the first and last name of each
contact associated with (the child of) that account?

Contact.FirstName
Contact.LastName

Parent : Account
Child: Contact

1. Select Account.Name,(Select Contact.FirstName,Contact.LastName from


Account.Contacts)From Account

The above query will returns all accounts and for each account, the first and last name of each
contact associated with (the child of) that account

Write a query which will returns all accounts, and for each account, Opportunity Name of each
Opportunity associated with (the child of) that account?

2. Select Account.Name, (select Opportunity.Name from Account.Opportunities)


from Account

Write a Query which will return all Positions and for each Position, get me the Job Applications of
each Job Application associated with the child of Position__c

Job_Applications__r

3. List<Position__c> accList = [select id ,Name , Department__c ,


(select name , id from Job_Applications__r) from Position__c];
for(Position__c a:accList)
{
System.debug(' ID ' + a.id + ' Name ' + a.name + ' Department ' + a.Department__c);
}
First one is for Account(Parent) – Contact (Child) relationship.

4) List<Account> accList = [select id,name,(select name, id, email from contacts) from
account];
for(Account a:accList)
{
System.debug('ID' +a.id+ 'Name' +a.name);
}

Write query a Parent to Child Relationship from


Candidate to Job Applications
Positions to Interviews
Job Application to Reviews - And try Aggregate functions in the Query..

Notes: Points to be Remembered

Child to Parent
***** Dot Notation
***** No Sub Query

Parent to Child
Standard Objects
***** Sub Query
***** Plurals (Contacts, Assests, Cases, Products, etc)

Custom Objects
***** Sub Query
***** __r (Suffix ) for Child Objects

05-May-2022
Visualforce Pages/MVC Pattern
Visualforce Controller (Essentials) - Standard, Custom and Extensions

Component - Image, Text Box, Picklist, Command Button, List Button, Label, Radio Button, Check
Box, Message I want to display

HTML type Mark up language…


Proprietary to Salesforce
<html> <apex Title=>
<Title=’Welcome’>

</Title>
</html>

CSS - Cascading Style Sheets

<apex:Page stdController = “Account” Title=”Welcome”>


<apex:form>
<apex:PageBlock Title=”Accounts”>
<apex:CommandButton value=’Click Me’ Action=”{!Save}”/>
</apex:PageBlock>
</apex:form>
</apex:page>

What are the development tools for writing VFPages


1) Developer Console
2) Salesforce UI
3) Inline Editor – Ensure Development Mode is enabled
4) VS code

{!} Expresion tags


{!$User} is a global variable will have $
Email Templates
{!$User.LastName} we are going to access of the LASTNAME field in that object.
{!Account.Name} going to access the value from Name filed of Account object.
$- is not applicable to all Standard Objects and Custom objects.. Applicable to certain Standard
Objects
$ - Global Variable
1) User
2) Organization
3) Profile
4) Task
5) Event

Standard Controller
Visualforce consists of many built-in controllers which can be used to access and display data. It
works on the MVC (model-view-controller) approach. The controllers interact with the database and
pull the data from the database to view the data through a webpage created by apex page.

A Visualforce controller is a set of instructions that specify what happens when a user interacts with
the components specified in associated Visualforce markup, such as when a user clicks a button or
link. Controllers also provide access to the data that should be displayed in a page, and can modify
component behavior.
The Lightning platform provides a number of standard controllers that contain the same functionality
and logic that are used for standard Salesforce pages. For example, if you use the standard
Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as
clicking Save on a standard Account edit page.

A standard controller exists for every Salesforce object that can be queried using the Lightning
Platform API.

To associate a standard controller with a Visualforce page, use the standardController attribute on
the <apex:page> tag and assign it the name of any Salesforce object that can be queried using the
Lightning Platform API.

Scenario: 1 Create a VFPage and display the current user details on the Page

.vfp is the extension

<apex:Page>
<apex:Form>
<apex:PageBlock>
<apex:PageBlockSection>

Scenario 2: Create three PageBlock Sections on a VFPage.


Apex Programming
VFPages
Web Services

Standard Controllers
Standard & Custom objects
Account, contact, Opportunity
Position__c, Book__c, Candidate__c
Standard Controller are already created
Standard+custom objects

<apex:Page standardController= “Accounts”>


<apex:Page standardController= “Positoin__c”>

Scenario 3: Create a VFPage of StandardController of Position object and display or bring a record
into the current context.
<!—
-->
You need to pass a record ID in the url..
https://nalandatech-dev-ed--c.visualforce.com/apex/StandardDemo?id=a005j00000AxTAoAAN

HW- Scenario 4: Create a VFPage of StandardController of Account object and


display or bring a record into the current context.

Scenario 5: Create a VFPage where you can display the complete details of a Particular Position
Record… into the current context
Scenario 6: Create a VFPage where user can input the values into an Account object. / Create a
VFPage to insert the Account Records
Std Controller - Account
<apex:Input Field>
To Save or Insert the data … Buttons or Labels

Scenario 7: Please display the associated contact information (Name, Mailing city, Phone, Title) for
a Particular Account. Use a Page Block Table as a component … and pass the account Record Id
into the current context

Scenario 8: Please display the associated Opportunity information (Name, Amount, Stage,
AccountName ) for a Particular Account. Use a Page Block Table as a component … and pass the
account Record Id into the current context

Scenario 9: Create a VFPage on Review object where all the Score parameters like (Experience,
Cultural Fit, Leadership skills) should display in the Radio button, and option values or Ratings
should be Excellent, Very Good, Good, Fair, Bad…for all the three reviews.

Convert VF Page to Lightning Experience

Add this Code to you .vfp file

<apex:page controller="CandidateCustomController" lightningStylesheets="true"


standardStylesheets="false" sidebar="false" docType="html-5.0" applyBodyTag="False"
applyHtmlTag="false" showHeader="false">

Standard List Controller

Standard List Controllers.


Standard list controllers allow you to create Visualforce pages that can display or act on a set of
records. Examples of existing Salesforce pages that work with a set of records include list pages,
related lists, and mass action pages
Displaying a list of records is a fundamental behavior of almost all web apps. Visualforce makes it
extremely easy to display a list of records of the same type, using just markup, no back-end code.
A standard list controller can return up to 10,000 records. Custom controllers can work with
larger results sets.
Using a standard list controller is very similar to using a standard controller. First you set
the standardController attribute on the <apex:page> component, then you set the
recordSetVar attribute on the same component.
The recordSetVar attribute not only indicates that the page uses a list controller, it sets the
variable name of the record collection. This variable can be used to access data in the
record collection.

<apex:Page stdlistcontroler> X

<apex:Page:standardcontroller=”Positon__c” Recordservar
Scenario 10: Use standard List Controller to display list of Account Records on a VFPage.

HW- Scenario 11: Use standard List Controller to display list of Opportunity Records on a VFPage.

Scenario 12: Use standard List Controller to display list of Position Records on a VFPage in a PDF
format.

Custom Controller : A custom controller is an Apex class that implements all of the logic for a
page without leveraging a standard controller. Use custom controllers when you want your
Visualforce page to run entirely in system mode, which does not enforce the permissions and field-
level security of the current user.

Scenario 13 : Create a custcontroller which will display a name on a VFPage

Scenario 14: Create a custcontroller and Invoke the Custom Controller constructor () and display
Student details on a VFPage

Scenario 15: Create a custcontroller and Invoke the Custom Controller constructor () and a apex
metod and display Student details on a VFPage by clicking on a Button

Scenario 16: Create a custcontroller and display Name and EmpNo on an Output label of VFpage

Apex Classes

1) System
2) Date
3) String
4) List
5) Map and Set
6) Page Reference
7) Exceptions
8) MathException
9) ListException (Array outbound except)
10) Null Pointer Exception
11) Query Exception
12) DML Exception
13) SObject Exception

Scenario 17 : With PageRefernce is a class ensure user input EmpName and city details and print
these details on a VFPage and use ReRender attribute so that when the user clicks on a button the
fields should get refreshed…

Scenario 18 : Write an Apex controller where you can perform Addition, Subtraction, Multiplication,
Division operations and execute the same logic on a VFpage..

Scenario 19: Write an apex controller to fetch the Account records using SOQL statement and
display all those records on a VFPage
Scenario 20: Write an apex controller to fetch the Position / Opportunity records using SOQL
statement and display all those records on a VFPage
Position – where Department= IT, Engineering and Sales
Opportunity - where Stage=’Closed Won’

Scenario 21: Write an Apex Controller where user can insert Records into Account objects
Use DML Operation Insert

Example- Custom Controller


- Custom Extension
- Development Mode

06-May-2022

5) Inline Editor – Ensure Development Mode is enabled in User

Scenario 22: Create a Custom controller where user can insert records in Candidate FirstName
and LastName and Gender fields in Candidate object

// Apex Controller to insert records..


public class CandidateCustomController
{
public string candidateName{set;get;}
public string gender{set;get;}
public string stateProvince{set;get;}

public pageReference mySave()


{
Candidate__c can=new Candidate__c();
can.Name=candidateName; // Maping the object fields to Apex variables
can.Gender__c=gender;
can.State_Province__c=stateProvince;
insert can; // DML
return new PageReference('/'+can.Id); // returning Id of the record..
}

<apex:page controller="CandidateCustomController">
<apex:form>
<apex:pageBlock title="Candidate Page">
<apex:pageBlockSection title="Enter Candidate Details">
<apex:panelGrid columns="2" border="2" bgcolor="Pink">

<apex:outputLabel value="Candidate Name"></apex:outputLabel>


<apex:inputText value="{!candidateName}"/>
<apex:outputLabel value="Gender"></apex:outputLabel>
<apex:selectRadio value="{!gender}">

<apex:selectOption itemLabel="Male" itemValue="Male"></apex:selectOption>


<apex:selectOption itemLabel="Female"
itemValue="Female"></apex:selectOption>
<apex:selectOption itemLabel="Other"
itemValue="Other"></apex:selectOption>
</apex:selectRadio>

<apex:outputLabel value="State Province"></apex:outputLabel>


<apex:inputText value="{!stateProvince}"/>
</apex:panelGrid>
<apex:commandButton value="Cick to Insert" action="{!mySave}"/>

</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Scenario 23: Create a Custom controller where user can insert records in Position object (HW)

Custom Extension Controller or Extension Controller

A controller extension is an Apex class that extends the functionality of a standard or custom
controller.

Account
Contact
Candidate__c

Extending the functionality Standard Controller – Apex Class

Custom Controller - Apex Class – Extending the functionality

System Mode
As per your System settings

User Mode - Sashank


permissions, field-level security, a nd sharing rules

A controller extension is an Apex class that extends the functionality of a standard or custom
controller. Use controller extensions when You want to leverage the built-in functionality of a
standard controller but override one or more actions, such as edit, view, save, or delete.

Controller extension in Salesforce is an Apex class containing a constructor that is used to


add or extend the functionalities of a Standard Controller or custom controller in Salesforce
<apex:page standardController=”Position__c” extensions=”Class1, Class2,..”> Correct
Class1, Class2

<apex:page Controller=”MYControllerName” extensions=”,..”> Correct syntax

<apex:page standardController=”Account” Controller=”MyController”> Wrong

<apex:page standardController=”Account”extensions=”ExtensionAccount”> Correct


Sysntax

ApexPages.StandardController

Create an Extension Controller class to get an Account Record from Account object.

Standardcontroller = Account
Extension controller = Extension Account (Apex Class)

public class ExtensionAccount {

private final Account acc;

public ExtensionAccount(ApexPages.StandardController controller)


{
this.acc=(Account)controller.getRecord();
}
public String getGreeting() // Apex Propertie // getter
{
return ' Hello ' + acc.Name + '(' + acc.id +')';
}
}

<apex:page standardController="Account" extensions="ExtensionAccount"> <br/><br/>


<p>
{!Greeting}
</p>
<apex:form >
<apex:outputLabel >View the Account Record </apex:outputLabel>
<apex:inputField value="{!account.Name}"/>
<apex:CommandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>
Scenario 24:
Create one controller and one extension classes to display Account and Contact records..on
VFPage..

<apex:page Controller=”AccountObjExtension” extensions=” AccountObjContact”>

// Apex Controller Class which will return the Account Records


public class AccountObjExtension {
public List<Account>getAccounts()
{
List<Account> accList=[Select Name,AccountNumber from Account];
return acclist;
}

public class AccountObjContact {


public List<Contact>conList{get;set;}
public AccountObjContact(AccountObjExtension actob)
{
conList=[Select FirstName,LastName,Email from Contact];
}
}

<!-- Displaying Account and Contact Records with help of Controller and extension controller
classes-->

<apex:page controller="AccountObjExtension" extensions="AccountObjContact">


<!-- Account Records-->
<apex:PageBlock Title="Fetching Account Records">
<apex:PageBlockTable value="{!Accounts}" var="accList">
<apex:column value="{!accList.Name}"/>
<apex:column value="{!accList.AccountNumber}"/>
</apex:PageBlockTable>
</apex:PageBlock>

<!-- Contact Records-->


<apex:PageBlock Title="Fetching Contact Records">
<apex:PageBlockTable value="{!conList}" var="con">
<apex:column value="{!con.FirstName}"/>
<apex:column value="{!con.LastName}"/>
<apex:column value="{!con.Email}"/>

</apex:PageBlockTable>
</apex:PageBlock>
</apex:page>

Scenario 25: Create an Extension class and leverage the Account object functionality to display or
fetch the records on a VFPage. Use SOQL statement in the extension class.

public class AccountExtensionRecords


{
private ApexPages.StandardSetController setController;
public AccountExtensionRecords(ApexPages.StandardSetController setController)
{
this.setController=setController;
Account[] records=[select Name,AccountNumber from Account Limit 10];
// ApexPages.StandardSetController.setSelected()to set the list of records from your
Apex Controller
// so that the records are selected on Page Load...
setController.setSelected(records);
}

<!--Create an Extension class and leverage the Account object functionality to display or
fetch the records on a VFPage.
-Use SOQL statement in the extension class-->
<apex:page standardController="Account" extensions="AccountExtensionRecords"
recordSetVar="accounts" >
<apex:pageBlock>
<apex:pageBlockTable value="{!accounts}" var="acc">
<apex:column value="{!acc.Name}"/>
<apex:column value="{!acc.AccountNumber}"/>

</apex:pageBlockTable>

</apex:pageBlock>
</apex:page>

Scenario 26: Create two extension classes and invoke or call the classes from a VFPage

public class ExtFirst


{
public ExtFirst(ApexPages.StandardController std)
{

}
public String getFriend()
{
return 'Ajit & Vijay Thalapatthi';
}

}
public class ExtSecond
{
public ExtSecond(ApexPages.StandardController sec)
{

}
public String getCities()
{
return 'Hyderabad & Bangalore';
}

<apex:page standardController="Account" extensions="ExtFirst, ExtSecond"


showHeader="true"><br/><br/>
<apex:outputText value="{!Friend}"></apex:outputText><br/><br/>
<apex:outputText value="{!Cities}"></apex:outputText><br/><br/>

</apex:page>

Apex Triggers, Events, Context Variables, Recursive Triggers


Trigger order of execution

Lines of code or a proceduere will be invoked whenever a events occurs in a database…Trigger will
perform actions … these actions will be performed either before or after the events..

Triggers will run before objects records are created, updated or deleted into the database,, or after
the records are inserted, updated, deleted and restored(Undelete)

Triggers are divided into two types

Before Trigger
It can be used to update or validate record values before they are saved to Database….

After Trigger
It can be used to access the field values that are already set by the database such as a
record's Id or last Updated field,
And these after triggers are used to affect the changes in other records.

DML Operations
Insert
Update
Upsert
Merge
Delete
Undelete

These events are also divided or Categorized based on Before and After Triggers
Before Trigger will support only three events

1) Before Insert
2) Before Update
3) Before Delete

After Triggers
1) After Insert
2) After Update
3) After Delete
4) After UnDelete

View - Tables …. Database…


You can create view… perform some complex actions or process..
Create View Empview on Employee;
Replica same table or objects

BEFORE and AFTER triggers fired by DML statements can be defined only on tables, not
on views. However, triggers on the base tables of a view are fired if an INSERT, UPDATE,
or DELETE statement is issued against the view.

BEFORE and AFTER triggers fired by DDL statements can be defined only on the database
or a schema, not on particular tables.

Before Insert :
These triggers will fire when we are trying to insert a new record into a specified object.

Before Insert :
These triggers will fire when we are trying to insert a new record into a specified object.
Operations which we have written in the trigger will be implemented before new records are
saved to the database.
In before Insert, Trigger.New stores the list of new records which we are trying to insert.
Trigger.New is one of the context variable
Stores the list of new records which are trying to insert.

After choosing the event make a choice of Context Variables:


Trigger.new
– Returns or Hold a list of the new versions of the sObject records.
Note that this sObject list is only available in insert and update triggers, and the records can
only be modified in before triggers.
Trigger.old
– Returns a list of the old versions of the sObject records. Note that this
sObject list is only available in update and delete triggers.
1. Delete supports only Trigger.old DeleteTrigger
2. Insert supports only Trigger.new Insert
3. Update supports both Trigger.old & Trigger.new
newMap
- A map of IDs to the new versions of the sObject records. Note that this map is only available
in before update, after insert, and after update triggers.

Write Trigger Syntax

Create Trigger<TriggerName> on <Object Name> (<Trigger events with comma separation>)


{
}

reate Trigger UpdateAccount on Account(before Insert, before update)

trigger memberInviteNotify on Member__c (after insert,after update)


{
if(trigger.isInsert)
{
// When a new record is created and inserted, the flow will come here
............................
............................
............................
}

if(trigger.isUpdate)
{

// When an existing record is modified, the flow will come here


............................
............................
............................
}
}

09-May-2022

VFP Component Library


https://nalandatech-dev-
ed.my.salesforce.com/apexpages/apexcomponents.apexp

Best Practices Visualforce

Consider following these best practices to improve the performance of your


Visualforce pages. Design your Visualforce pages according to some general
guidelines.
1. Use standard objects and declarative features.
2. Limit the amount of data that your Visualforce pages display.
3. Delay expensive calculations or data loading.
4. Offload processing to asynchronous tasks.
5. Cache global data in custom settings.
6. Write efficient:
1. Apex and SOQL
2. Getter methods
3. Optimize
4. View state
7. Component hierarchies
8. Polling
9. HTML
10. CSS
11. JavaScript
12. Image usage
13. Pages for Internet Explorer

DOM – Document Object Model

Order of execution in Visualforce page


1. Constructor of the controller.
2. Action method of the page.
3. Getter methods.
4. If there are any client-side technologies on the page, such as JavaScript, the
browser executes them. Example is window.onLoad().
Note:
If the page contains an <apex:form> component, all of the information necessary to
maintain the state of the database between page requests is saved as an encrypted
view state. The view state is updated whenever the page is updated.

Scenario 1: Create a Trigger when a new record is getting created automatically the Acc
Industry field should be updated as ‘Communications’

Bulikfied- More records

Scenario 2: Populate contact description when user creates contact.


- “Conntact Created Sucessfully by using before insert Trigger” – before Insert

Scenario 3: Populate contact description field with modified User Name when user
updates a contact.. – before update existing records
Before update..

Scenario 4:
When a new contact is created without Account then throw an error message

Scenario 5: Write a Trigger to merge scenario 2 and Scenario 3 in one Trigger

Scenario 6: Create a Triger when creating a Position, its related Min Pay should be
greater than >8000 and Max Pay should be greater than >=15000. If its is less than the
above number, it should throw an error message

trigger PositionMinMaxPay on Position__c (before insert) {


for(Position__c pos:Trigger.New)
{
if(pos.Min_Pay__c<8000 && pos.Max_Pay__c<=15000)
{
pos.addError(' Max Pay should be greater than 15000 and Min Pay lesser than 8000 ');
}
}
}

Scenario 7: Create a Trigger on Position when user enters a new record or updates an
existing record and if Min Pay greater than Max Pay, it should throw an error stating ‘Min
Pay Cannot be greater than Max Pay’
before Insert, before Update Events
Is insert and isUpdate- context variables

Scenario 8: Try to implement 6 and 7 in one Trigger both before Insert and before Update
Events

trigger PositionMinMaxPay on Position__c (before insert, before update) {


if(Trigger.isBefore) // Before Trigger
{
if(Trigger.isInsert || Trigger.isUpdate) // Context Variables
{
for(Position__c p:Trigger.New)
{
if(p.Min_Pay__c > p.Max_Pay__c)
{
p.Min_Pay__c.addError('Min Pay Cannot be greater than Max Pay in the
record');
}
}
}
}

Scenario 9: Create a Trigger to Avoid Using Candidate Name as ‘M’. It should throw an
error if Candidate Name starts with ‘M’

Scenario 10
Create a Triger where it should validate or compare or match the new Candidate
email id with an existing email ids list in Candidate object. If any email id matches it should
throw an error stating the ‘Email ID already exists in the database’

One Custom Validation – State & Province


Process Builder - Email ID Creation
Workflows - Candidate Company Name – Cognizant
Triggers - Two (Name, Email ID Matching) before insert, before update
System Validations

Scenario 11: Whenever a Case is created with Origin as email then set status as Working
and Priority as Normal

Scenario 12: Create a related contact record when an Account is created…


After Triggers- used to access field values that are set by the database, and to affect
changes in other records.

Scenario 13: Create an Opportunity automatically when an Account Record is created


**** Manadtaory Fields in Opp **********
Name=Acc.Name +’Opportunity’
Stage Name= Prospecting
Close Date = DateToday+20 days
Opp Account Id= Acc.ID////

Scenario 14: Create a Case automatically when an Account is created.

Scenario 15; Throw an error whenever a user tries to delete a Contact which is not
associated to any account..

Scenario 16: Whenever a new account is created with Annual Revenue more than 50000$
then add Narendra Modi as Contact Name. (HM)
After Insert..
Scenario 17: After insert trigger salesforce
Let us see an example of a trigger on contact which will create Account record
whenever contact is created without an account.

trigger ContactCustomTriggerExample on Contact (after insert)


{
List<Account> accListToInsert = new List<Account>();
for(Contact con : Trigger.New) {
//check if account is null on contact
if(con.AccountId == null ) {
Account acc = new Account();
//Add all required field on Account
acc.Name = con.LastName;
acc.Phone = con.Phone;
accListToInsert.add(acc);
}
}
if(!accListToInsert.isEmpty()){
insert accListToInsert;
}
}

Apex Handler
It is always a best practice to write a single trigger on object and process all
operations in Apex Class(we call it as Apex Handler).
Don’t write heavy logic in Trigger.. instead of writing the logic in the Trigger
you handle that logic in Apex Handler or Apex Class so that you can specify the order of
event based on the context variables…
Call that class on a Trigger

Scenario 18:
When an Account is created it should create a contact under that account with
Account Name

Recursive Trigger

Recursive Trigger
When you want to write a trigger that creates a new record as part of its processing logic.
However, that record may then cause another trigger to fire, which in turn causes another
to fire, and so on. You don't know how to stop that recursion.
Recursion occurs when same code is executed again and again. It can lead to infinite loop
and which can result to governor limit sometime. Sometime it can also result in
unexpected output or the error “maximum trigger depth exceeded”. So, we should
write code in such a way that it does not result to recursion.
For example, we may come across a situation where in a trigger we update a field which in
result invoke a workflow. Workflow contains one field update on same object. So trigger will
be executed two times. It can lead us to unexpected output.
Using a static variable in an Apex class to avoid an infinite loop. A static variable is
local to the context of a web request (or test method during a call to runTest()), so all
triggers that fire as a result of a user's action which has access to it.

Best Practices in Trigger


Trigger Best Practice for Apex Programing
1) One Trigger Per Object
2) Logic-less Triggers
3) Context-Specific Handler Methods
4) Bulkify your Code
5) Avoid SOQL Queries or DML statements inside FOR Loops
6) Using Collections, Streamlining Queries, and Efficient For Loops
7) Querying Large Data Sets
8) Use @future Appropriately
9) Avoid Hardcoding IDs
10) You cannot create a Trigger on Multiple objects

Order of Exaction
How does salesforce follow or implement the Order of Execution…..
10-May-2022

Apex Testing

Testing Concepts?
Why do we require Testing?

Unit Testing
Regression Testing
Functionality Testing
Load Testing
Integration

Basically Testing is divided into two types


Functional Testing
– Installation testing
– Smoke testing
– Configuration testing
– Compatibility testing
– Exception testing
– Interface testing
– Conversion testing
– Unit Testing
– Regression Testing
– Functionality Testing
– Integration / Assembly / String Testing
– System / Product Testing

Non Functional Testing


1. Performance testing
Load testing
Stress testing
Volume testing
2. Reliability testing
3. Security testing
4. Usability testing
5. Recoverability testing
6. Maintainability testing
7. Localization testing
8. Documentation testing
9. Data quality testing
10. Platform testing
11. Concurrency testing

Developers are called as Constructors

Testers are called as destructors or destroyers

Testing Techniques are divided into two types

1) White box Testing


Developers - Concerned about the working of code
Unit Testing- Divided into different Modules
They have to test there code…
Module code…
Java / C++ / C# / Apex
I need to test that code.. Developer permitted only to Unit Testing
2) Black Box Testing
Testers- Concerned behavior of the Application

▪ Introduction to Code Coverage

Code coverage is a measure that describes the degree to which the source
code of a program has been tested. It is usually measured in percentages.
Code coverage is also called test coverage or just coverage.
Code coverage is a part of feedback loop in the development process. As tests
are developed, code coverage highlights aspects of the code which may not
be adequately tested and which require additional testing. This loop will
continue until coverage meets some specified target.

Source Code

Salesforce requires at least 75% of your code to be covered by our test


classes. Salesforce requires at least 75% of your code to be covered by our
test classes.

Apex Testing
WHY UNIT TESTS ARE NEEDED
• Validate Desired Behavior
• Reduce the bug Cost
• Perform Bulk tests
• 75% Code coverage for Production deployment
WHAT TO TEST
• Apex Trigger
• Apex Class – Handler/Helper, WebService, Apex REST, SOAP
• VF Page
• Apex Batch/Queueable/Future Method
• Custom Controller
The following are the benefits of Apex unit tests.
1. Ensuring that your Apex classes and triggers work as expected
2. Having a suite of regression tests that can be rerun every time classes and triggers
are updated to ensure that future updates you make to your app don’t break existing
functionality
3. Meeting the code coverage requirements for deploying Apex to production or
distributing Apex to customers via packages
4. High-quality apps delivered to the production org, which makes production users
more productive
5. High-quality apps delivered to package subscribers, which increase your customers
trust

Apex Class
Apex Trigger
VFPage

@isTest - Apex Annotation


TestClass

Calculator Apex Class


@isTest
CalculatorTest TestClass

1. Methods of your test class have to be static, void and testMethod keyword has to
be used.

Four digit Pin Number

Error Guessing

0000 valid
1111 valid
9999 valid
11WW Not valid
76jj
@@ii
%%44
Example-1
public class Calculations
{
public static String Name='MSK'; // not null
public static integer printSum(integer x, integer y)
{
return x+y;
}
public static integer printMul(integer x, integer y)
{
return x*y;
}

@isTest // is annotation ...


public class CalculationsTest {

public static testmethod void testprintSum() // testmethod is a keyword is


compulsory.. it is not going to retrnn any value
{
integer x=20;
integer y=40;
integer expected=60;
Calculations c1=new Calculations();
integer actual=c1.printSum(x, y);
System.assertEquals(expected, actual);

}
public static testmethod void testprintMul()
{
integer x=20;
integer y=40;
integer expected=800;
Calculations c2=new Calculations();
integer actual=c2.printMul(x, y);
System.assertEquals(expected, actual);
}

public static testmethod void testName()


{
System.assertEquals('MSK',Calculations.Name,'Name is empty');
}
}
Example-2

You add an Apex class that contains a method for updating the book price. This
method is called by the trigger that you will be adding in the next step.

You now have a class that contains some code that iterates over a list of books and
updates the Price field for each book. This code is part of the applyDiscount static
method called by the trigger that you will create in the next step.

Apex Class:

public class Books


{
public static void applydiscount(Book__c [] book1)
{
for(Book__c b:book1)
{
b.Price__c *=0.9;
}
}

you create a trigger for the Book__c custom object that calls
the applyDiscount method of the Book Class class that you created in the
previous step.
// Trigger Handler
trigger BooksTriger on Book__c (before insert) {
Book__c [] books1=Trigger.New;
books.applydiscount(books1);
}

You now have all the code that is needed to update the price of all books that get
inserted. However, there is still one piece of the puzzle missing. Unit tests are an
important part of writing code and are required. In the next step, you will see why
this is so and you will be able to add a test class.
You add a test class with one test method. You also run the test and verify code
coverage. The test method exercises and validates the code in the trigger and class.
Also, it enables you to reach 100% code coverage for the trigger and class.

Test Class

@isTest
private class HelloWorldTestClass {
static testMethod void validateHelloWorld() {
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);

// Insert book
insert b;

// Retrieve the new book


b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);

// Test that the trigger correctly updated the price


System.assertEquals(90, b.Price__c);
}
}

11-May-2022
Concept - Synchronous vs Asynchronous operations
Apex annotations & interfaces (@future, Batchable, Schedulable)
(Queuable, @InvocableMethod)
Deployment using Change sets

@Future

public class MyTasks {


public MyTasks()
{
takeShower();
havingBreakfast();
carServicing();
watchingMovie();
}
public static void takeShower()
{
system.debug('I am taking shower');
}
public static void havingBreakfast()
{
System.debug('I am having my Breakfast');
}
@future
public static void carServicing()
{
System.debug('I need to give my car for servicing');
}
public static void watchingMovie()
{
System.debug('Watching Movie with my GirlFriend');
}
}

Batch Apex Class

It is used to run large jobs (think thousands or millions of records!) that would
exceed normal processing limits. Each time you invoke a batch class, the job is
placed on the Apex job queue and is executed as a discrete transaction.

For example, if you want to make a field update of all records in any object which is
having more number of records, then governor limits restricts us to process that
operation. Because in a single transaction we can only process 10,000 records.
In batch apex, it will fetch all records which you want to perform the field update and
divide them into a list of 200 records & every 200 records operation is performed
separately.
When we are hitting the Governing Limits --------- > we use batch Apex.

How Batch Apex Works


To write a Batch Apex class, your class must implement
the Database.Batchable interface and include the following three methods:
Start () method is automatically called at the beginning of the apex job. This method
will collect record or objects on which the operation should be performed. These
records are divided into subtasks and pass those to execute method.
Execute() Method performs an operation which we want to perform on the records
fetched from start method.
Finish () method executes after all batches are processed. Use this method to send
confirmation email notifications.

Scenario : Fetch Position Records and update the Position Name with ‘Cognizant’
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Batch Apex

global class BatchApexDemo implements Database.Batchable<sObject> {


global Database.QueryLocator start(Database.BatchableContext BC)
{
/// Query Locator will be writing a Query on ostion object to get the data..
//Database.BatchableContext object.. this object to track the progress of the
batch job..
String query='SELECT Id,Name from Position__c';
return Database.getQueryLocator(query); // Will recevie the records..
}
global void execute(Database.BatchableContext BC, List<Position__c>plist)
//process each batch of record...
{
for(Position__c p:plist)
{
// Update the Position Name
p.Name=p.Name + 'Cognizant';
}
try{
update plist;
}
catch(Exception e)
{
System.debug(e);
}
}

global void finish(Database.BatchableContext Bc)


{
// execute any post processing oeraions
// Sending an Email
// Sending any notification email..
}

/*BatchApexDemo BAD= new BatchApexDemo();


Id JobId=Database.executeBatch(BAD, 5); /// 5 Batch Size
System.debug('The Batch Apex Job Id is ' +JobId);*/

/////////////////////////////////////////////////////////////////////////
Queueable Apex
Queueable Interface
We can add upto 50 Jobs to the Queue with System.enqueuejob in a Single transaction

Schedulable Apex:

To invoke the Apex batch classes to run at specific times, first we need to implement
the Schedulable interface for the Apex class,
then specify the schedule using either the standard Salesforce Schedule Apex
page in the user interface,
or we can use the System.schedule method.

The Schedulable interface that contains one method that must be implemented
always, i.e execute.

global void execute(SchedulableContext sc)


{
}
The implemented method should always be declared as global or public.
This method is used to instantiate the class you want to schedule.

public class FirstQueuable implements Queueable{


public void execute(QueueableContext context)
{
Contact a=new Contact(LastName='Sanju Baba', Phone='(415)777-8828');
insert a;
// Chain the Jobs...
System.enqueueJob(new SecondQueuable());
}
}

/*String jobid=System.enqueueJob(new FirstQueuable());


System.debug('Job ID is ' +jobid);*/

public class SecondQueuable implements Queueable{


public void execute(QueueableContext context)
{
Position__c p=new Position__c(Name='Film
PRoducer',Department__c='IT',RecordTypeId='0125j000000N8lIAAS',
Min_Pay__c=8765, Max_Pay__c=9987);
insert p;
}

////////////////////////////////////////////////////////////////////////////////////////////////
CRON Expression
An expression is written in the form of 'Seconds, minutes, hours, day of the
month, month day of the week, optional year.'
'Seconds' : 0-60
'Min' : 0-60
'Hours' : 0-24
'Day-Months' : 1-31
'Month' : 1-12
'Day-Week' : 1-7
'Optional Year' : --
String str = '0 0 10 * 3 2';

'Seconds' : 0-60
'Min' : 0-60
'Hours' : 0-24
'Day-Months' : 1-31
'Month' : 1-12
'Day-Week' : 1-7
'Optional Year' : --

SPECIAL CHARACTERS :
? : Special character specifies no specific value. This is only available for the day of
the month and day of the week.
EXAMPLE 1 :
Write the expression to schedule an operation 10th of August at 12:30 PM.
===========================================
'0 30 12 10 8 ?'
'0 30 12 10 AUG ?'
'0 30 12 10 AUG ? 2013'
===========================================
EXAMPLE 2 :
Write an expression to schedule an operation on Jan Monday 12:30.
===========================================
'0 30 12 ? 1 MON'
'0 30 12 ? 1 2'
===========================================

* : Specifies all the values


EXAMPLE 1 :
Write the expression to schedule an operation on every day of the AUG at 12:30
PM.
===========================================
'0 30 12 * AUG ?‘ * all days of Aug Month
'0 30 12 * 8 ?‘ * all days of Aug ? Is optional (2021)
===========================================
EXAMPLE 2 :
Expression to schedule on every hour on 10th AUG.
===========================================
'0 30 * 10 8 ?'
===========================================
L : Specifies the end of the range. This is available the only day of the month
or day of the week.
EXAMPLE :
Write an expression to schedule the operation on last Friday of March at 10:20.
===========================================
'0 20 10 ? 3 6L'
===========================================

SCHEDULE APEX LIMITATIONS :

1. We can schedule only 100 jobs at a time.


2. Max no. of apex schedule jobs in 24 hours is 2,50,000 number of jobs (can
change with salesforce updates).
3. Synchronous WebService callouts are not supported in schedulable Apex.

public class SchedulableApexDemo implements Schedulable


{
public void execute(SchedulableContext sc)
{
List<account>accs=[SELECT id,name from Account where Active__c='Yes'];
for(Account acc:accs)
{
acc.Name='Created Today' + acc.Name;
}
update accs;

}
}

String cronexp='0 30 12 12 5 ?';


System.schedule('Queueable Apex', cronexp, new SchedulableApexDemo());
12-May-2022
Deployment using Change sets
Apex annotations
Aura component framework

Deployment using Change sets


Project Manager - the live Application to you.. or Production environment…

Will you get access to the production environment for developing the Application?
Application is already on live … go live

Similar copy of Application is also available with the Dev team- in Sandbox…
Deployments on Weekends.

Sandbox - Sandbox is the copy or replica of Production environment.


Playground – Developer and Tester can code it and test it properly

You need to purchase the Sandbox from Salesforce…


Clients will purchase the sandbox…

You need to know what are the different types Sandboxes available in Salesforce..
Four Sandboxes
Developer
Developer Pro
Partial Copy
Full Sanbox

SDLC -
Plan
Analyse
Design
Build
Test
Deploy / Production

Application Life Cycle Management

Your live Salesforce instance, or your production org, is a critical tool for your
business and your customers. Without governance and management, it's easy to
lose or duplicate data, create errors, or cause large, overarching issues for your
users. As a way to help your team prevent these types of issues from popping up
around your production org, Salesforce created their own version of the Application
Lifecycle Management (ALM) framework.
Many organizations find themselves making updates to their software on an almost
daily basis. Implementing an ALM framework helps your team maintain organization
and outline how you oversee updates and track changes as they move from the
planning stage to retirement.
Application Lifecycle Management (ALM) on the other hand, is the way a Salesforce
owner or admin rolls out changes and enhancements to their Salesforce instance
(otherwise known as an org). Having a solid ALM process ensures the org continues
to work properly and delivers the most value to end-users.
Application Lifecycle Management is a combination of software engineering and
integrated requirements management. ... Efficient progression of application through
development, testing, and production.

How many ways we can do the deployment process in Salesforce?

1) Change Sets
2) Eclipse with Force.com IDE (Deprecated)
3) Force.com Migration Tool – ANT/Java based
4) VSCode
Salesforce CLI software as to be installed local machine
Install VSCode
Install Salesforce Extension Pack in VSCode
5) Salesforce Code Builder

Salesforce Deployment Tools:-


Recently many deployment tools available either Free/Paid services, such as:
Eclipse, ANT, Gearset, Pipeline, ClickDeploy, AutoRABIT, Flosum, Jenkins for
continus deployment.

Scenario 58:
How to Create an App in Sandbox and how to deploy this App in Production?

Change sets - Deployment Process

Setup a communication process between Production Env and with Sand Box
Production ---→ Sandbox

What is Change Sets


Collection of Components
Objects
Metadata
Records
Tabs
Apps
Apex Classes
Apex Triggers
Aura
LWC

Two types of Change sets

An outbound change set contains customizations that you want to send from this organization to
another organization. These customizations can include new components or modifications to
existing components, such as apps, objects, reports, or Apex classes and triggers. An outbound
change set can't be used to delete or rename components in another organization.

Out bound Change set in Sandbox


Add the components
Added the dependencies
Add the Profile

Push – to Prod Org

Inbound Change Sets


Validated to check if any errors are there in change set
Deployed the Change sets in Prod Org
Successful.
You can view the App in Production Org..

Apex Development
Apex Classes
Apex Triggers
Asynchronous Classes
Recommended in Sandbox rater writing directly Prod Environment

• Apex Trigger
• Apex Class – Handler/Helper, WebService, Apex REST, SOAP
• VF Page
• Apex Batch/Queueable/Future Method
• Custom Controllers

Need to tested.. test classes..


****** If you code coverage is not >=75%...
Salesforce will not allow your code to deploy. ***********************
Apex Annotations

@isTest
@Future

Aura …

RestAPI – Webservice

WebService? –

An Apex annotation modifies the way a method or class is used similar to


annotations in Java. 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.
The main use of annotation is to instruct the compiler that the class is to be used as
the specific class as defined by the annotation. Annotations are defined with an
initial @ symbol, followed by the appropriate keyword.

The @AuraEnabled annotation enables client- and server-side access to an Apex


controller method. Providing this annotation makes your methods available to your
Lightning components (both Lightning web components and Aura components).
Only methods with this annotation are exposed.
@Deprecated:
Use the deprecated annotation to identify methods, classes, exceptions, enums,
interfaces, or variables that can no longer be referenced in subsequent releases of
the managed package in which they reside. This is useful when you are refactoring
code in managed packages as the requirements evolve. New subscribers cannot
see the deprecated elements, while the elements continue to function for existing
subscribers and API integrations.
@Future:
Use the future annotation to identify methods that are executed asynchronously.
When you specify future, the method executes when Salesforce has available
resources.
To test methods defined with the future annotation, call the class containing the
method in a startTest, stopTest code block. All asynchronous calls made after the
startTest method are collected by the system. When stopTest is executed, all
asynchronous processes are run synchronously.
@IsTest:
Use the isTest annotation to define classes or individual methods that only contain
code used for testing your application. The isTest annotation is similar to creating
methods declared as testMethod.
@SuppressWarnings
This annotation does nothing in Apex but can be used to provide information to third
party tools.

@ReadOnly:
The @ReadOnly annotation allows you to perform unrestricted queries against the
Force.com database. All other limits still apply. It’s important to note that this
annotation, while removing the limit of the number of returned rows for a request,
blocks you from performing the following operations within the request: DML
operations, calls to System.schedule, calls to methods annotated with @future, and
sending emails.
@RemoteAction:
The RemoteAction annotation provides support for Apex methods used in
Visualforce to be called via JavaScript. This process is often referred to as
JavaScript remoting.
@TestVisible:
Use the TestVisible annotation to allow test methods to access private or protected
members of another class outside the test class. These members include methods,
member variables, and inner classes. This annotation enables a more permissive
access level for running tests only.

Apex REST annotations:


1. @RestResource(urlMapping=’/yourUrl’)
2. @HttpDelete
3. @HttpGet
4. @HttpPatch
5. @HttpPost
6. @HttpPut

End to Platform Developer-1

Aura - Building lightning components and


some overview of LDS
Aura - Lightning Components-Controllers
Aura - Ligtning Events
Introduction to VS Code and its extensions/Online Editor
Why Salesforce Introduce Aura Framework ?
At the beginning of the Salesforce Development times, before Aura Framework,
developers used Visual Force, which is an HTML Tag-based mark-up language to
develop their Visual Force web pages and Apex to control the internal logic.
But this HTML based Visual Force standards were not compatible to build large
scale enterprise solutions and complex applications. So, developers needed
something that could support the ongoing huge demand for web-based applications
with complicated business logic.
In 2014, Salesforce launched the Lightning Component Framework and it changed
the Salesforce Programming way forever. Lightning Component Framework brought
Aura Framework which used a component-driven model that was brilliant in
developing large-scale enterprise applications.
Since the time the web technology is being changed every day, seeing an
unprecedented change in JavaScript Frameworks, redefined way of creation of a
web page, and more. Lightning Component also has to become Lightning web
components to accommodate the newest technologies in Salesforce Development.

13-May-2022

› It uses JavaScript on the client side and Apex on the server side.
› In other words,
“Lightning Components is a framework for developing web apps.”
“Web apps for mobile and desktop devices.”
What is aura framework?

› Aura is a UI framework for developing dynamic web apps for mobile and desktop
devices. Aura provides a scalable long-lived lifecycle to support building apps
engineered for growth.
› Aura supports partitioned multi-tier component development that bridges the client
and server. It uses JavaScript on the client side and Java / Apex on the server side.
› The framework intelligently utilizes your server, browser, devices, and network so
you can focus on the logic and interactions of your apps

HTML 5.0
CSS
Modern Java Script

https:// NalandatechUniversity.com

https://Nalandartech/University/signup.apx
https://Nalandartech/University/CourseDetails.apx

https://Nalandartech/University/facultydetails.jsp

https://Nalandartech/University/placementdepartment.apx

https://Nalandartech/University/innovationteam.apx

Scenario 1 : Create a Lightning component to display “HelloWorld Welcome to the


world of Lightning” and execute this component on an App.

Extension .cmp

<aura: component>
</aura:component>

HelloDemo1Aura.cmp

<aura:component > <br/><br/>


<h1>
HelloWorld Welcome to the world of Lightning <br/><br/>
</h1>
<p>
Application: To run the Lightning component, the application is important.
Here, include the component in the application to use. <br/><br/>
This is the top-level component that contains all other components.
</p>
<!-- <c:SecondCompAura/> -->

</aura:component>

App Code:

<aura:application >
<c:HelloDemo1Aura/>
<c:SecondCompAura/>
</aura:application>

Scenario 2: Create an another Component called Heading.cmp and call that component
into the CognizantApp.

SecondCompAura.cmp
<aura:component >
This is my Second Component Created !!! <br/><br/>
<h1>
My Intern's batch students are from Loverly Proffesional University <br/>
Welcome Team !!
</h1>
</aura:component>

Scenario 3: Add css to the Component 2 and execute on the Cognizant App

SecondCompAura.css

.THIS {
}
h1.THIS{
background-color:DodgerBlue;
text-align:center;
font-size:30px;
color:red;
}

/////////////////////////////////////////////////////////////////////////

Before we can really build components that do something, we need to learn about
attributes, types, values, and expressions.

Component Attributes

we need to learn two things. First, we need to learn how to enable a component to
accept input when it’s created. That is, we need to set values on the component. We
do this using attributes.
The second thing we need to learn is how to actually use these values to change a
component’s behavior and output.

Attributes on components are like instance variables in objects


<body bgcolor=”red”/>
<href link=www.yahoo.com, Alt=”Yahoo”/>

<apex:CommandButton value=”Save” action=”{!Save}”/>

<aura:attribute>

Important attributes of <aura:attribute> component


› name –> Name of the attribute, must have at least 2 characters
› type -> Data type, can be any basic type, collections, array, standard or custom
object type
› access -> can be global, public, private
› default -> will be considered if we do not provide any value explicitly
› required -> Makes this attribute mandatory.
› Description→

Scenario 4: Write an attribute component and display on App using view port to access the
component message attributes values..

<aura:component >
<aura:attribute name="Message"
type="String"
default="Hello Team"/><br/>

{!v.Message} <p>Welcome to Cognizant !! </p>

</aura:component>

Scenario 5: Implement Div class and Style attribute of CSS in an aura:component

<!-- Learn Div Class and Style attribute for CSS-->


<aura:component > <br/><br/>
<h1>
This is Inline CSS
</h1>
<div style="background-color:black ; margin:4px">
<p style="color:white"> White text with Black Backbround</p> <br/>
<p style="color:Yellow">Text with Black background</p>
</div>

</aura:component>

Scenario 6:
Create a Lightning Component called CalculatorComp , define 2 attributes
and perform arithmetic operations
Create a Lightning Application called CalculatorCompApp and refer
CalculatorComp by setting.

CalculatorAuraComp
<aura:component ><br/><br/>
<h1>
Calculator
</h1><br/><br/>
<aura:attribute name="Number1"
type="Integer"
default="30"/>

<aura:attribute name="Number2"
type="Integer"
default="60"/> <!-- if you don't pass the values in the Name attributes
the defalt value will be
considered for calculation-->

<div class="myStyle">
Addition : {!v.Number1 + v.Number2}<br/><br/>
Substartcion: {!v.Number1 - v.Number2}<br/><br/>
Multiplication: {!v.Number1 * v.Number2}<br/><br/>
Division: {!v.Number1 / v.Number2}<br/><br/>
Modulous: {!v.Number1 % v.Number2}<br/><br/>
</div>

<aura:application >
<c:CalculatorAuraComp Number1="100" Number2="88"/>
</aura:application>

Scenario 7: Add CSS style selector to the above program and execute on an App

CalculatorAuraComp.css

.THIS {
}

h1.THIS{
color:blue;
font-size:20px;
}

/*myStyle is a selector, which can be refered using <div>tag inside the


component*/

.THIS.myStyle
{
text-align:Center;
color:Blue;
border:5px RED SOLID;
Width:20%;

}
Static Resource

1. Next to the File text box, click Browse to navigate to a local copy of the resource
that you want to upload.
– A single static resource can be up to 5 MB in size, and an organization can
have up to 250 MB of static resources, total.
2. Set the Cache Control:
– Private specifies that the static resource data cached on the Salesforce
server shouldn’t be shared with other users. The static resource is only stored
in cache for the current user’s session.
– Public specifies that the static resource data cached on the Salesforce server
be shared with other users in your organization for faster load times.
3. Click Save.

Scenario 8:
Add a Calc Image by using a Static Resource concept and add it to the Calculator
Component and execute it on Lightning Page App

<img src="{!$Resource.MyNalandaCal}" width="200" height="100" alt="Nalanda


Calcultor"/>

<aura:if >

How to use Conditional statements IF, Else in Lightning components?

Actions: function (component, event, helper)

Scenario 9: Handling Events with Client Side controllers

Create a Calculator Component with addition, Substraction, Multiplication and Division


buttons and handle these actions with event handlers in the Client Side Controller
(JavaScript) and Create an App and execute the calculator components on App

Actions - Addition
Event- onClick
ActionHandle – Need to handle the Events – onclick

Solution for Scenario: 9


ClientCalculatorAura.cmp

<aura:component >
<aura:attribute name="Number1"
type="Integer"/>

<aura:attribute name="Number2"
type="Integer"/>

<aura:attribute name="Result"
type="double"/>

<div class="myStyle">
<img src="{!$Resource.MyNalandaCal}" width="200" height="100" alt="Nalanda
Calcultor"/>

<!-- We could directly bind the attribuutes with inpt components-->


<lightning:input label="Enter FirstNumber" value="{!v.Number1}"
name="fn"/><br/><br/>
<lightning:input label="Enter SecondNumber" value="{!v.Number2}"
name="ln"/><br/><br/>

Result is :{!v.Result} <br/><br/>

<!-- Need to create buttons Add,Sub,Mul and Division-->


<lightning:button label="Addition" onclick="{!c.addition}"/> <!-- onclick is an event
is an action addition-->
<lightning:button label="Substraction" onclick="{!c.substraction}"/>
<lightning:button label="Multiplication" onclick="{!c.multiplication}"/>
<lightning:button label="Division" onclick="{!c.division}"/>
</div>
</aura:component>

ClientCalculatorAura.js

({
addition : function(component, event, helper)
{
var number1=component.get("v.Number1") ;
var number2=component.get("v.Number2");
var result=parseInt(number1)+parseInt(number2);
component.set("v.Result",result);
alert("Addition " +result);
},
substraction:function(component,event,helper)
{

}
}),

ClientCalculatorAura.CSS

.THIS {
}

.THIS.myStyle
{
border:5px RED SOLID;
width:50%;
}

<aura:application >
<c:ClientCalculatorAura/>
</aura:application>

Scenario 10: Example fetching Data from a Server Side Controller


This use case shows a dynamic iteration that displays data from a Standard
Opportunity object when user clicks on the button..

1) Server Side controller


2) Opportunity Component.
I need to create a UI.. need to create a button where can I retrieve the opp
records on a App Page

OpportunityServerSideController.apxc

public class OpportunityServerSideController


{
@AuraEnabled
public static List<Opportunity>getOpportunities() // method return type
List<Opp>
{
List<Opportunity>opplist=[SELECT Name,Amount from Opportunity];
return opplist;
}
}

ServerOppAura.cmp

<aura:component controller="OpportunityServerSideController"
implements="force:appHostable,flexipage:availableForAllPageTypes"
access="global" >
<aura:attribute Name="opplistAttr"
type="Opportunity[]"/>
<ui:button label="Get Opportunities" press="{!c.getOpps}"/>
<!--Iterates over a collection of items/records and renders the body of the tag for
each item -->
<aura:iteration var="opt" items="{!v.opplistAttr}">
<br/> {!opt.Name} <br/>
<br/> {!opt.Amount} <br/>
</aura:iteration>
</aura:component>

ServerOppAura.js

({
getOpps:function(component) {

//1 get a refernece to the Server-side method

var oppt=component.get("c.getOpportunities");

// 2 Register the callback function to gather the Asynchronous responses

oppt.setCallback(this,function(response)
{
alert('Tested');
var state=response.getState();
if(state=="SUCCESS")
{
///3 Please process that response ...
component.set("v.opplistAttr", response.getReturnValue());
}
});

// 4.. put the method call in a Queue usingg $A.enequeAction() to send a


request
// to the client to Sever
$A.enqueueAction(oppt);
}
})

ServerOppAura.App

<aura:application >
<c:ServerOppAura/>
</aura:application>

16-May-2022

Salesforce Lightning Design System


Introduction to VS Code and its extensions/Online Editor
Aura - Lightning Events
Component Event
Application Event
AppExchange Overview, Release Updates, Recap & Reinforced Learning

Salesforce Lightning Design System

.house__window
.house - > block which represents the component

__window / __door - > Element

.house_gray -> Modifier

Utility Classes

For example, margin and padding are indicated with the formula
.slds-m-top_medium (margin, top, medium).

Introduction to VS Code and its extensions/Online Editor


Aura - Lightning Events
Component Event
Application Event

<apex:CommandButton value=”Click Here” action=”{!Save}”/>

• Events are mode of interaction between the user and the web page
• JavaScript is used to react to the events
• Example of an event can be:
o An HTML Page is loaded
o A field value is changed
o An HTML button is clicked
• Specific HTML elements have event handler attributes for supported events
• When the event is triggered corresponding script is executed

What is an Event ? Generally an event is a thing that happens or takes place. When
we talk about events in JavaScript, they are simply a thing that happen to HTML
element. There can be various types of events when we talk about HTML.
For example:-
1. Web page loaded is an event
2. Clicking of a button is an event
3. Changing text in an input field is also an event.
So, we can say that any kind of interaction that happen in a webpage either
automatically or by human interaction is an event.

Event – Button Click – Action – Registered – Event has to be handled - > Event
Handler will handle it- > Where it is handled in JS (Java Script)

Supper Market – Visual Basic

<aura:InputField>

What is an Event ? Generally, an event is a thing that happens or takes place. When
we talk about events in JavaScript, they are simply a thing that happen to HTML
element. There can be various types of events when we talk about HTML.
For example:-
1. Web page loaded is an event
2. Clicking of a button is an event
3. Changing text in an input field is also an event.
So, we can say that any kind of interaction that happen in a webpage either
automatically or by human interaction is an event.
Event-driven programming is used in many languages and frameworks, such as
JavaScript and Java Swing. The idea is that you write handlers that respond to
interface events as they occur. Salesforce Lightning is a component based
framework for the application development. Component is the core part of the
lightning framework. The communication between components are handled by
events.
There are two types for events:
1. Component Event
2. Application Event

Component events can used to communicate between related components

When we have two components (or multiple) in the hierarchy and when we need to
send information from child to parent then we will be using Component Events.

Salesforce recommends to use component events whenever possible as they have


a limited scope. Application Events are handled at the application level and can be
used to communicate between different components that are not related to each
other. Usually, we deal with the events that are fired when the user interacts with the
browser. Such events are known as browser events. There are another type of
events that are called system events that automatically trigger during the
component life cycle.

When we have two components (or multiple) in the hierarchy and when we need to
send information from child to parent then we will be using Component Events.
Application Events
When we have multiple components which are not in the hierarchy and if were to
send info from one component to a different component altogether (which is not
within the hierarchy) then we will be using Application Events.
It's always suggested to use Component Events first before we use Application
Events because when we have multiple Application Events we need to extremely
careful, as something is misconfigured then the event listeners in the other
Components also(which is not required) also gets trigged.

A component event in the lightning component is an event that is fired by another


lightning component. A component event can either be managed by the component
itself or it can be managed by any of another component that is already present in
the hierarchy that gets that particular event. The component events can only be
registered in the child components and handled by the parent component.

1) Create an Event
2) Register that Event
3) Fire an Event Component - child
4) Handle that Event Parent Component which is present in the hierarchy.
Or by the Same Component.

When do you want to use Component Events?


You need Component Events when you have to pass values from child
component to parent. In this case, the sender will be the child component
and the receiver will be the parent component.
Parent Component which is present in the hierarchy Or by the Same
Component.

Events doesn’t have bundles


Components and Application will have Aura Bundles

Component Event

Step 1: Create the event with the event type as Component

<aura:event type="Component" description="Event template" access="global">


<aura:attribute name="Parameters" type="String"/>
<!-- declare the string attribute that you want to pass-->
</aura:event>

Step 2: Register the event in the sender component (child) and fire the
event using the below code

<!--Register the event in the sender component (child) and


fire the event using the below code-->

<aura:RegisterEvent name="ChildEvent" type="c:ChildEvent"/> <!-- Register that


event-->
<h1>No of Missiles getting fired on Chinna</h1> <br/><br/>
<button onclick="{!c.passParameter}"> Fire </button> <br/>
<!--call the JS controller method to fire the event when the button is clicked-->
Step -3

<aura:attribute name="noofmissiles" type="Integer" default="0"/>


<p>{!v.Paramters}</p>
<p>Number of Missiles fired : {!v.noofmissiles}</p>

An application event is generally like a broadcast message. Like if you send a


broadcast, then all the receivers that are configured to accept that broadcast
message receive that message. Application Events helps in passing values
between two independent events (without parent child relationship).
It means that in case of Application Events, any component with the handler
statement defined for the event can receive the fired event.
Imagine you have two independent components, say A which takes User Name
as the input from the user and passes the value to another component, say B,
which will receive the value for doing some logic.

When you have two independent events (meaning without parent child
relationship) and you want to pass values between them, then “Application
Events” are the way to achieve it. Imagine you have two independent
components, say A which takes User Name as the input from the user and
passes the value to another component, say B, which will receive the value for
doing some logic. Here are the steps:

18-May-2022
AppExchange Overview, Release Updates, Recap & Reinforced Learning
Revise all the contents
Admin 201 Certification / Platform App Builder Certification
or
Platform Developer 1- Certification Exam Preparation
Add few more Trailhead Modules
Super Badges-

AppExchange - Play store - collection of Apps

Android- PlayStore
iPhone – App Store

Salesforce – App Exchange


Consists of

Built in Apps
Built in Components
Developers
Consultants
Market Place

Free
Paid Apps

Categories / Industries

Financial Group
Capital Markets
Insurance
Banking

Communication and Technology


Health & Public Service
Consumer able & Good Services…

Automobile - Industry
BMW
Merc
Toyata
Nissan

Enfield
Java

It’s simple, actually. AppExchange is the leading enterprise cloud marketplace. Find proven apps
and experts to help you solve business challenges fast and extend your Salesforce Customer 360
from anywhere — across every industry, department, and product. With more than 117,000
customer reviews and 9 million installs, you know you can confidently choose the right solution for
your business needs.

Two types of Packages

Managed Package - Downloading from App Exchange are Managed Packaged


Un Managed Package – Apps that are built by developers are called Unmanaged Package

PHASE-2 Training

30-May-2022
55 to 100 Trailhead badge ranges will focus on 1x Ranger -
Workshops - At least Daily-2
Super Badge (Trailhead, locate them and complete)
▪ Business Administration Specialist
▪ Process Automation Specialist
Recruitment Application (Trailhead Project, locate the below in order and
complete)
▪ Build a Data Model for a Recruiting App
▪ Customize the User Interface for a Recruiting App
▪ Improve Data Quality for a Recruiting App
▪ Keep Data Secure in a Recruiting App

As a team you will complete below Recruitment Projects

Main Topic Type Topic Link


Recruitment Build a Data Model https://trailhead.salesforce.com/en/content/learn/p
Project Project for a Recruiting App rojects/build-a-data-model-for-a-recruiting-app
Customize the User
Recruitment Interface for a https://trailhead.salesforce.com/en/content/learn/p
Project Project Recruiting App rojects/customize-the-ui-for-a-recruiting-app
Improve Data
Recruitment Quality for a https://trailhead.salesforce.com/en/content/learn/p
Project Project Recruiting App rojects/improve-data-quality-for-a-recruiting-app
Automate Business https://trailhead.salesforce.com/en/content/learn/p
Recruitment Processes for a rojects/automate-business-processes-recruiting-
Project Project Recruiting App app
Recruitment Keep Data Secure https://trailhead.salesforce.com/en/content/learn/p
Project Project in a Recruiting App rojects/keep-data-secure-in-a-recruiting-app

Created Groups
****** Each Group has to implement atleast 5 different scenario’s or complex
business requirements on Recruitment Application as a team…..
Preferred - Apex or Aura or LWC
Second Preferred Declarative Concepts

Micro Project :: Auto Response Templates, Lead Auto Response Rule, W2L, Lead Assignment
Rule, Queue
MICRO PROJECT :: To decide whether to allow Sales Agents to Upsell
Opportunities
Micro Project - Flows - Auto Launched Flow (Record Triggered Flow) + Logging
Fault Messages
MICRO PROJECT Simple Approval Process + Auto Submit For Approval via a
Process Builder

Data Quality Standards

Email Id- @ - a X

01-June-2022

Collaborative way of working


Application on Knowledge
Knowledge(Learnings) vs Skill (Practical Implementation)

Basic- Intermediate – Complex Knowledge and Skills

Product – or an App Recruitment…


Implementation
03-June-2022

1) Complete all Workshops Scenarios


2) Complete below trailheads

Flow
Concepts: https://trailhead.salesforce.com/en/content/learn/modules/
62 Flows Module Quick Look flow-concepts-quick-look
https://trailhead.salesforce.com/en/content/learn/modules/
63 Flows Module Flow Builder flow-builder
https://trailhead.salesforce.com/en/content/learn/modules/
64 Flows Module Flow Basics flow-basics
Screen Flow https://trailhead.salesforce.com/en/content/learn/modules/
65 Flows Module Distribution screen_flow_distribution
Build a
Discount https://trailhead.salesforce.com/en/content/learn/projects/f
66 Flows Project Calculator low_calculate

3) Try to share additional workshop scenarios - Please complete that as well


4) Ensure that your VSCode properly configured for LWC topics
5) Complete two Trailhead batches by Monday
6) Complete all four Recruitment Project Trailhead links
7) Complete all Apex Hours…

Javascript

Dim X
X=10
X=’shiva’
X=’A’

Browsers use their own JavaScript Engines to execute the JavaScript code. Some
commonly used browsers are listed below:
• Chrome uses a V8 engine.
• Firefox uses the SpiderMonkey engine.
• Microsoft Edge uses the ChakraCore engine.
• Safari uses the SquirrelFish engine.

JavaScript Array is also like a data type that is used to store one or more than one value
of a similar type together. It's like a container which is used to store values in a single
variable. We can use an array to store values of string type, or integer type, or an object or
any other valid data type in JavaScript.
JavaScript does not have a specific array datatype for defining arrays. But, there is a
predefined Array object and its methods to work with arrays. Arrays also have properties in
JavaScript like length which is not a function but a property.
We can create JavaScript array either by using the new keyword or using the array literal
notation i.e. [](square brackets).

07-June-2022
Rest of the Javascript (BOM, DOM)
Introduction LWC
Bundle, Data Binding, CSS, Rendering, Loops, Iteration
JS Properties, Component Lifecycle and Composition
Events - Component Communication
Accessing Salesforce Data, Navigation Service
Custom Settings & Metadata Types

BOM- three functions


Alert() Simple to display in the information
Prompt() user has to enter value interact with Browser
Confirm() Receive the confirmation yes or no

DOM
• What is the DOM?
DOM stands for Document Object Model. It is a programming interface that allows us to
create, change, or remove elements from the document. We can also add events to these
elements to make our page more dynamic.
• Document Object Model or DOM is an interface to access HTML elements
• It is platform and language neutral
• DOM allows the control of the following:
• HTML Elements or tags
• Attributes of an element
• Form Methods and Events
• JavaScript uses the DOM objects to retrieve and manipulate HTML tags
programmatically

<HTML>
<TITLE>
<HEAD>
<BODY bgcolor=>
<font size=
<a href=
Form Elements

The HTML <form> element can contain one or more of the following form elements:

• <input>
• <label>
• <select>
• <textarea>
• <button>
• <fieldset>
• <legend>
• <datalist>
• <output>
• <option>
• <optgroup>

The HTML Events


*************With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

DOM - two types


Document – It is an Object – Object will contain attributes / properties and Methods
Methods
Properties
Document.write()
Array is list of similar or homogenous items
It is a container

LWC
Why are we moving from VF to Aura to LWC? Why Lightning or LWC?
1) At the beginning of the Salesforce Development times, before Aura Framework,
developers used Visual Force, which is an HTML Tag-based mark-up language
to develop their Visual Force web pages and Apex to control the internal logic.
But this HTML based Visual Force standards were not compatible to build large
scale enterprise solutions and complex applications. So, developers needed
something that could support the ongoing huge demand for web-based
applications with complicated business logic.

2) Why Did Salesforce Launch Lightning Web Components?


After Google has released Web Components to the Google Chrome browser,
all the major web browsers like Firefox, Safari, or Edge started to adopt it
faster. Salesforce Development had to keep up the pace and standardizations
of the Web Components according to the huge demand of the web
Components across the internet.
3) Visualforce was created before mobile apps on phones became a thing. While
you can develop mobile apps with Visualforce, none of the built-in components
are mobile-savvy. Which means you write more code. Lightning Components,
on the other hand, is specifically optimized to perform well on mobile devices.

4) In the modern electronic age, businesses are moving towards using different
devices, such as Laptop, Smart Phones, and Tablets for their business
processes. One of the major challenges these businesses have been facing is
handling device compatibility.

5) Salesforce has introduced Lightning Component framework– a UI framework for


developing dynamic web apps for mobile and desktop devices.

6) Lightning includes the Lightning Component Framework and some exciting tools
for developers. Lightning makes it easier to build responsive applications for any
device.

7) As of Spring ’19 (API version 45.0), you can build Lightning components using
two programming models: The Lightning Web Components model, and the
original Aura Components model. Lightning web components are custom
HTML elements built using HTML and modern JavaScript. Lightning web
components and Aura components can coexist and interoperate on a page.

8) Using Lightning Components, Lightning App Builder and Experience Builder you
can seamlessly customize and easily deploy new apps to mobile devices
running Salesforce. In fact, the Salesforce mobile app and Salesforce Lightning
Experience are built with Lightning components.

9) Lightning Components is a UI framework for developing web apps for mobile


and desktop devices.

10) It’s a modern framework for building single-page applications with dynamic,
responsive user interfaces for Force.com apps.

11) It uses JavaScript on the client side and Apex on the server side.
In other words,
12) “Lightning Components is a framework for developing web apps.”

13) “Web apps for mobile and desktop devices.”


14) Aura supports partitioned multi-tier component development that bridges the
client and server. It uses JavaScript on the client side and Java / Apex on the
server side.

15) The framework intelligently utilizes your server, browser, devices, and network
so you can focus on the logic and interactions of your apps

In LWC- you can use Aura and Aura you can use LWC both are interoperability….
Lightning Web Components and Aura Components Working Together
An interoperability layer enables Lightning web components and Aura components to work
together in an app.
, Lightning Web Components utilize standard tech like CSS, HTML, and updated
JavaScript without requiring a set framework, incorporating the latest innovations in
JavaScript, including Shadow Document Object Model(DOM), custom elements, and web
components (ECMAScript 7 is specifically the updated JavaScript language used).
<apex:Page>
<apex:Form>
<apex:PageBlock>
<apex:PagebBockSection>
{!Account.AccountType}
{!$User.UserName}
“{!Save}”

<Aura: Component>
<Aura:Attribute name=”message”
Type = “number”
Default= “89”>
<Ui>
<Aura:Event>
view port or value provider
{!v.Number + v.Number2}
<template>
<div class=”Head”>
<Lightning-card name=”Enter your Name”/>
@track message=”Hai Welcome”

<html>
<head>
<title=”Welcome”>
<font size=10 color=’red’/>
Standard HTML
Custom HTML Elements
CSS
DOM
Basic Java Script and Modern JavaScript
Shadow DOM
Aura Components - Trailhead link –
Migrate VFPages, Aura Components to LWC

Aura Component bundle having 8 different files


LWC Component bundle will have only four files
HTML
CSS
Java Script
.xml Configuarion file

LWC -
Install VSCode
Salesforce CLI software
Created a Folder
Salesforce Extension Packs are installed in VS Code
Select SFDX: Create Project.
Select SFDX: Authorize an Org (Salesforce Org)

Ensure you get below message

Scenario 1: Create a LWC and display a simple message “Welcome to the World of
Lightning Web Components” and display this LWC on Lightning Home Page
Add css to <p> and <input> element
JavaScript files in Lightning web components are ES6 modules. By default, everything
declared in a module is local—it’s scoped to the module.
Contains the Metadata values for the component. How to deploy a component on
Salesforce Org.

Scenario 2: Create LWC with various Buttons and also write a handler while you click on
each button to display a message
Scenario 3 : To the above Scenario 2 LWC add various Button Types
Neutral
Brand
Destructive
Destructive Text
Success
Scenario 4: Create a LWC combo box and it should enable you to select only one option.
Use onChange event handler to capture what’s selected

<template>
<h1 class="comb">Created a New Combo box called Movie></h1>
<lightning-combobox
name="Progress"
label="Select a Movie"
value={value}
placeholder="Select Combobox"
options={options}
onchange={handlerChange}></lightning-combobox>

<p class="actor">Selected Actor Name is :{value}</p>

</template>

import { LightningElement } from 'lwc';

export default class CogCombobox extends LightningElement {


value='in Progress' // default value

get options() //get property


{
return[
{label:'KGF', value:'Yash'},
{label:'Pushpa', value:'Allu Arjun'},
{label:'Radhee', value:'Salman'},
{label:'Gabbar', value:'Akshay'},

handlerChange(event)
{
this.value=event.detail.value;
}

.comb{
background-color: greenyellow;
}

.actor{
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
font-weight: bold;
}
08-June-2022
Scenario 5 : Create a LWC with two input boxes..
Scenario 6: Create a LWC and display an Enfield Bike on Home Page
<template>
<h1>Royal Enfield Bike</h1>
<div class="bike">
<div>Name : {name} </div>
<div>Description : {description} </div>
<div>Category : {category}</div>
<div> Model No : {modelNo} </div>
<div> Price : {price}</div>
<div> <img src={bikePicture}/></div>
</div>
</template>

import { LightningElement } from 'lwc';

export default class CogRoyalEnfieldDemo extends LightningElement {


name = 'Royal Enfield Meteor 350';
description = 'Watch 106 Royal Enfield Meteor'
category = 'Bullet';
modelNo = 'Meteor 350 Model';
price = '₹ 2,05,769'
bikePicture='https://mskapplication-dev-ed--
c.visualforce.com/resource/1654667879000/Royal_Enfield?';

.bike{
font-weight: bold;
color: blue;
background-color: aqua;
}

Data Binding
{!v.name} hook to access the value of an attribute
v is called as view port
{name}
How many ways you do DataBinding?
1) {name} accessing the attribute value from JS by using {} curly braces
2) @track decorator

Scenario 7: Create a LWC to use private properties @track for data binding and reflecting
on the screen. In this scenario I am also creating lightning-card
<template>
<lightning-card title="Data Binding Type 2">
<div class="slds-p-around_medium">
<p style="font-size:20px;font-weight:bold;color:crimson;">Hello Team !!
My Name is {name}</p>
<p>This is the second type of Data Binding</p>
<br>
<lightning-input name="Your Name" label="Enter your Name"
value={name} onchange={handleChange}></lightning-input>

</div>

</lightning-card>
</template>

import { LightningElement,track } from 'lwc';

export default class CogDataBindingDemo2 extends LightningElement {


//@track decorator
@track name="SHIVA KUMAR";
handleChange(event)
{
this.name=event.target.value;
}
}
//@track in front of name variable so that whenever the input value will change it
wll
//track the updated value.
//when user handle the handleChange(event){}
// this.name=event.target.value; it means from the onchange event i want the targted
// value of value from <lightning-input value={name}.. wheatever that is there in
this value get me that value
//this.name means the variable name which we have defined at the begining @track
name
//we are ust recalling it in a function to assigned the Changed value//

3) Java Script Getter Property


Get()

Scenario 8: Create a LWC which will display name and company of an employee by
using Java Script getter property

******When do we se get()?
Whenever we want to dynamically calculate the value of property used in HTML
templates.. then we use get()… **********

<template>
<lightning-card title="Data Binding Type 3 with get property of JS">
<p style="font-size:20px;font-weight:bold;color:crimson;">Hello Team !! My
Name is {name}</p>
<p>This is the third type of Data Binding</p><br/>
<div class="name">
Your Name and Company that you work for: {blogName}
</div>
</lightning-card>
</template>

import { LightningElement } from 'lwc';

export default class CogDataBindGetDemo3 extends LightningElement {


name='ASHWIN KUMAR';
companyname='COGNIZANT';

get blogName() // get is get() method from JS blogName() is the method


{
const completeName=`${this.name} ${this.companyname}`;
return completeName.trim().toLowerCase();
// the above line code will return the completename value which was
concatenated and
//will convert the value into lowercase()...
}
}
//In get blogName() method or function we have defined completeName as a constant
variable
//`${this.name} ${this.companyname}` is the conactenation synatx in Modern Java
Script
.name{
font-size: 20px;
color: deeppink;
font-weight: bold;
}

Scenario 9 : Create a LWC where user enters first name and last name. A Javascript
computes a new value and called “UpperCaseFullName should display and the template
should renders it as ASHWIN KUMAR(get Method())
<lightning-input> firstName
<lightning-input> Last Name
Event Name is onChange {handlerchange}

Call this handlerChange or define in the JS..

<template>

<lightning-input name='firstName' label="Enter your FirstName"


onchange={handlechange}></lightning-input>

<lightning-input name='lastName' label="Enter your LastName"


onchange={handlechange}></lightning-input>

<p class="upper">
UpperCased Full Name is :{upperCasedFullName}
</p>

</template>

import { LightningElement } from 'lwc';

export default class CogFullNamegetDemo extends LightningElement {


firstName='';
lastName='';

handlechange(event)
{
const field=event.target.name;
if(field==='firstName')
{
this.firstName=event.target.value;
}
else if (field==='lastName')
{
this.lastName=event.target.value;
}
}

// handlechange handler is an handler of onchange event which is going to


through the
//input values called first and last name...
get upperCasedFullName()
{
//get method is conerting the first and last name values into an upper case
// get method is one of the powerful method in modern JS..
return `${this.firstName} ${this.lastName}`.toUpperCase();
}
}

.upper{
font-size: 10px;
color: hotpink;
font-weight: bold;
}

Rendering
Loading a Page
Refreshing the Page

Will allow the component to update themselves this will reload some of fields or sections of
an HTML page after the operation is performed…
PageReference P=new PageReference();

Render a list of items or records for a Accounts..


I have two directive
for:each -
use for:item=”currentitem” – access the current item value..
to access this current item should know
Index 0 Index 1 Index 2 Index 3 Index 4 Index 5
Current:item is goind to use for:index=”index”
Key –Unique value – identify the record

101 - Ashwin
102 - Srija

Key={uniqueid};
List must have a Key..

Scenario 10:

Create LWC where you can display the list of the contact list with ID, Name and Title Fields
with for:each directive, use for:item="currentItem"
renderList.HTML

Above Example iterates over an array called contacts, which are defined in the component
Javascript class.

<template>
<lightning-card title="Hello For:Eac" icon-name="custom:cutom20">
<ul class="sldes-var-m-around_medium">
<template for:each={contacts} for:item="contact"> <!-- each lineitem-->
<li key={contact.id}> <!-- with Key:unique id record-->
{contact.id}, {contact.Name}, {contact.Title}
</li>
</template>
</ul>
</lightning-card>
</template>

import { LightningElement } from 'lwc';

export default class CogforeachRenderDemo extends LightningElement {


contacts=[ // contact is an array which stores list of items
{
id:1,
Name: 'Aditya Raj',
Title: 'Senior Vice President',
},
{
id:2,
Name: 'Ashwin Kumar',
Title: ' Vice President',
},
{
id:3,
Name: 'Srija',
Title: 'HR Vice President',
}
]
}

Scenario 10:
Add or Apply CSS to Scenario 09 Component..

<template>
<lightning-card title="Hello For:Each Displaying Contact Details"
icon-name="custom:custom20" class="myfont">
<b class="myTitle">For:Each List of Records</b>
<ul class="slds-var-m-around_medium">
<template for:each={contacts} for:item="contact"> <!-- each lineitem-->
<li key={contact.id} class="mypad"> <!-- with Key:unique id record-->
{contact.id}, {contact.Name}, {contact.Title}
</li>
</template>
</ul>
</lightning-card>
</template>

.myfont{
font-family: sans-serif;
font-weight: lighter;
font-size: 14px;
color: brown;
}

.mypad{
padding:10px;
background-color:rgb(0, 255, 30);
margin-top: 3px;
border-radius: 02cm;
}

.myTitle{
font-size: 20px;
font-weight: bold;
position: relative;
left:20%;
color: blue;
}
import { LightningElement } from 'lwc';

export default class CogforeachRenderDemo extends LightningElement {


contacts=[ // contact is an array which stores list of items
{
id:1,
Name: 'Aditya Raj',
Title: 'Senior Vice President',
},
{
id:2,
Name: 'Ashwin Kumar',
Title: ' Vice President',
},
{
id:3,
Name: 'Srija',
Title: 'HR Vice President',
}
]
}

Scenario 11: Create LWC where you can display the list of the Movies list with Movie Name,
Movie Hero, and Villan Fields with for:each directive, use for:item="currentItem" …. Add
appropriate CSS wherever it is required
renderList.HTML (Workshop)

Iterator - iterate over an Array of records


First and Last Properties
It will fetch first and last items of an Array
The iterator directive has first and last properties that let you apply special behaviors to
the first and last items in an array.
To apply a special behavior to the first or last item in a list, use the iterator directive,
iterator:iteratorName={array}. Use the iterator directive on a template tag.

Scenario 12 : Create LWC where you can display the list of the contact list with ID, Name
and Title Fields with iterator directive and also use first and last properties of The iterator
directive in that list… with if:true directive

<template>
<lightning-card title="Iterator Directive Displaying Contact Details"
icon-name="custom:custom14">
<p>Iterator Directive if:true Directive</p>
<ul class="slds-var-m-around_medium">
<template iterator:it={contacts}>
<li key={it.value.id}>
<div if:true={it.first} class="list-first"></div>
{it.value.Name},{it.value.Title}
<div if:true={it.last} class="list-last"></div>
</li>
</template>
</ul>
</lightning-card>
</template>

.list-first{
border-top: 1px solid black;
padding-top: 5px;
}

.list-last{
border-bottom: 1px solid rgb(7, 228, 11);
padding-bottom: 5px;
}

import { LightningElement } from 'lwc';

export default class CogIteratordirectiveDemo extends LightningElement {


contacts=[ // contact is an array which stores list of items
{
id:1,
Name: 'Aditya Raj',
Title: 'Senior Vice President',
},
{
id:2,
Name: 'Ashwin Kumar',
Title: ' Vice President',
},
{
id:3,
Name: 'Srija',
Title: 'HR Vice President',
}
]
}
09-June-2022

If I want to render a dom element eg: (Check box) (true or false) I need to use
if:true|false

To render HTML conditionally, add the if:true|false directive to a nested <template> tag that
encloses the conditional content.
TIP Directives are special HTML attributes. The Lightning Web Components programming model
has a few custom directives that let you manipulate the DOM using markup.
The if:true|false={property} directive binds data to the template and removes and inserts DOM
elements based on whether the data is a truthy or falsy value.
Let’s look at some code.
The template contains a checkbox labeled Show details. When a user selects or deselects the
checkbox, the handleChange function sets the value of the areDetailsVisible property. If the
areDetailsVisible property is true,
the if:true directive renders the nested template, which displays “These are the details!.”

Scenario 13:
Render DOM Elements Conditionally

Create a LWC component with a checkbox, if the user selects or deselects the checkbox
the handle change function sets the value of the Property either true or false

<template>
<lightning-card title="Conditional Rendering" icon-name="custom:custom20">
<lightning-input type="checkbox" label="Show Details"
onchange={handleChange}></lightning-input>
<template if:true={areDetailsVisible}>
<div class="detail">
These are the details after selecting!!
</div>
</template>

</lightning-card>
</template>
<template>
<lightning-card title="Conditional Rendering" icon-name="custom:custom20">
<lightning-input type="checkbox" label="Show Details"
onchange={handleChange}></lightning-input>
<template if:true={areDetailsVisible}>
<div class="detail">
These are the details after selecting!!
</div>
</template>
</lightning-card>
</template>

import { LightningElement } from 'lwc';

export default class CogdomRenderCond extends LightningElement {


areDetailsVisible=false;
handleChange(event)
{
this.areDetailsVisible=event.target.checked;
}
}

.detail{
font-weight: bold;
color: blueviolet;
}

Properties in LWC
Decorator
@track
@api
@wire

The Lightning Web Components programming model has three decorators that add
functionality to a property or function.
The ability to create decorators is part of ECMAScript, but these three decorators are
unique to Lightning Web Components.

HTML template

{contacts} calling them as attributes

{name}

{city}

JS file

Calling them as properties defined by assigning values to the properties…

Contacts=[ ‘amit,’ashwin’]
Name=’shiva kumar
City=’hyderabad
Properties are divided into two types

1) Reactive Properties
Public Property

Public Property: If you want to make the property to be called from other
component, you need to declare this property with @api decorator in the calling
component. Along with this, if the value changes on this property, component will be
re-rendered automatically. That’s why, it’s reactive.

Class - fields
Object – fields

@api contacts
@api name
@apt city

These properties are publicly available for other componetnts these are Reactive

Scenario 13:
Implement @api decorator which is a Reactive Property

<template>
<lightning-card title="Cognizant Salesforce Team using @api decorator">
<div>
<p>Hello Team !! {SalesforceDecorator}!!</p>
<!--SalesforceDecorator is a attribute in HTML template and will get
the value from JS @apiSalesforceDecorator decorator-->
</div>
</lightning-card>
</template>

import { LightningElement,api } from 'lwc';

export default class CogReactiveapiDemo extends LightningElement {


//to expose the public property, decoarte a filed with @api

@api SalesforceDecorator='I am learning LWC and from Cognizant Company';

JS - property
Tracked Property
Boolean Property

Track Property: If you want to track the property’s value, you need to declare this
property with @track decorator. Along with this, if the value changes on this
property, component will be re-rendered automatically. That’s why, it’s reactive.
Track property is also called private reactive property. Because, caller component or
component A can not call with @track decorator property to the calling component or
component B.

2) Private Properties

Scenario 14: Create a LWC to display an account details like


Account Name
Phone
Email
Mailing City
Use @track private reactive property for above attributes and display on a
LWC.

<template>
<lightning-card title="Displaying Account Details with @track Decorator" icon-
name="custom:custom28">
<div class="account">
<p>{accountName}</p>
<p>{phone}</p>
<p>{email}</p>
<p>{mailingcity}</p>
<!-- the above attributes in the currly braces are bound to the properties of
the same
name in the corresponding Javascript file or class-->
</div>
</lightning-card>
</template>

import { LightningElement, track} from 'lwc';

export default class CogtrackDemo extends LightningElement {


@track accountName = 'Mahindra Automobiles';
@track phone='83838383';
@track email='mahindra@automobiles.com';
@track mailingcity='Hyderabad';

}
Scenario 15- Create an Employee form where user input the values and display
those values on the component and use @track property.
Employee Name
Age
Designation
Salary
And these values should display on change event handler…
<template>
<lightning-card title="Employee Details with @track">
<div class="slds-m-around_medium">
<p>Employee Name : {employeename}</p>
<p>Employee Age : {employeeage}</p>
<p>Employee Designation : {designation}</p>
<p>Employee Salary : {salary}</p>

<!--Input the values from a user in input box component-->


<lightning-input label="Enter your Name" value={employeename}
onchange={namehandler}></lightning-input>
<lightning-input label="Enter your Age" value={employeeage}
onchange={agehandler}></lightning-input>
<lightning-input label="Enter your Designation" value={designation}
onchange={designationhandler}></lightning-input>
<lightning-input label="Enter your Salary" value={salary}
onchange={salaryhandler}></lightning-input>
</div>
<!-- All these properties are defined in JS as these are reactive
properties-->
</lightning-card>
</template>

import { LightningElement, track } from 'lwc';

export default class CogEmptrackDecora extends LightningElement {


@track employeename;
@track employeeage;
@track designation;
@track salary;

// Now we need to define the handlers which we have declared in HTML template

namehandler(event)
{
this.employeename=event.target.value;
}

agehandler(event)
{
this.employeeage=event.target.value;
}

designationhandler(event)
{
this.designation=event.target.value;
}

salaryhandler(event)
{
this.salary=event.target.value;
}
}

Scenario 16- Create a Books details LWC where user will input the values and
display those values on the component and use @track property
Book Name
Book Author
Book Type (Combo box) (Fiction, Detective, Drama, Thriller)
Price
And these values should display on the component with on change event Handler

Boolean Property: By default, Boolean Property has the value of false. If you call
the component with just Boolean Property name, the Boolean value would be true
and component will also be re-rendered due to @api decorator. That’s why, it’s
reactive.
Private Property
Private Property can be used only by the JS class in JS file. If the value changes on
private property, the component doesn’t re-render. So, it’s not reactive. You should
not put any decorator (@api, @track) for declaration of private property.

@wire
To read salesforce data, the lwc uses a reactive property called as
wire service…@wire. this service provisions data, the component rerenders…
Components use @wire in their Javascript file or class to specify a wire adaptor or
an Apex method
Salesforce Data it is in Server…

Serverside scripting -
@wire decorator is implemented in three ways

We can call the apex class in Lightning web component using these different ways:
• Wire a property
• Wire a function
• Call a method imperatively

*************Lightning web components can import methods from Apex classes into
the JavaScript classes. Once after importing the apex class method you can able
call the apex methods as functions into the component by calling either via the wire
service or imperatively. The Apex Method should be marked with @AuraEnabled.
Before you use an Apex method, make sure that there isn’t an easier way to get the
data. ******************************

Scenario 16- Create a LWC where you can display the list of Account records.
Use @wire property or function and invoke the Apex method from JS file and
ensure the Apex method is annotated with @AuraEnabled and import apexmethod
@salesofrce/apex/namespace.classname.apexmethod file..

1) Apex Class with a method to retrieve the Account Records


2) Create a LWC where you can display the list of accounts
For:each directive to loop the records
3) Import apexmethod
@salesofrce/apex/namespace.classname.apexmethod file.. into JS
file and invoke getAccountsList() method with @wire function

Apex Class

public class WireAccount {


@AuraEnabled(cacheable=true)
public static List<Account> getAccountList()
{
return [SELECT Id,Name,Type,Rating,Phone from Account];
}
}

<template>
<lightning-card title="Display Account List with @wire a method" icon-
name="custom:custom33">
<div class="slds-m-around_medium">
<template if:true={accounts.data}></template>
<template for:each={accounts.data} for:item="acc">
<p key={acc.Id}>{acc.Name},{acc.Phone},{acc.Type}</p>
</template>
<template if:true={accounts.error}>{accounts.error}</template>
</div>
</lightning-card>
</template>

import { LightningElement, wire } from 'lwc';


import getAccountList from '@salesforce/apex/WireAccount.getAccountList';

export default class CogWireAccount extends LightningElement {


@wire(getAccountList) accounts;
//@wire a method

Scenario 16- Create a LWC where you can display the list of contact records.
Use @wire property or function and invoke the Apex method from JS file and
ensure the Apex method is annotated with @AuraEnabled and import apexmethod
@salesofrce/apex/namespace.classname.apexmethod file..

1) Apex Class with a method to retrieve the Account Records


2) Create a LWC where you can display the list of accounts
For:each directive to loop the records
3) Import apexmethod @salesofrce/apex/namespace.classname.apexmethod
file.. into JS file and invoke getContactList() method with @wire function

Fetch the records by clicking on a Lightning Button

Composition of Components

Combining the components


Nested components

Composition : Let's consider an example of Car, we all know Car is a product which
consists of a car wheel, car body, car glasses etc. Now they all are manufactured or
created in a different company.
Similarly, In our lightning application, we create such small-small reusable components
separately and install them (compose them) inside another component. this concept is
called as component composition.
Now, the obvious question is why to use other components inside the main component ?
So there are many advantages to this Like:
- No need to re-write the code again.
- Easy to call other components.
- Reduce code size.
Now let's understand how we can create a composition in the lightning web component.
Basic Idea is we create the main component (parent component) and call other reusable
child components inside main component.

<parentComponent>
<child1Component>
<child2Component>
</parentComponent>

Syntax in the Lightning web component :

<childComponent> <wireAccount>

<template>
<lightning-card title=”Composition”></lighting-card>
<c-child-component>
<c-wire-Account>

Scenario 16- Create a child component and compose this child component into
Parent component

Child Component

<template>
<!--Child Component-->

<lightning-card title="Properties with Child" class="child">


<p > Hey !! You know that I am Child Component</p>
Your Birthday is : {TrackedProperty} : {inputDate} <br/>
</lightning-card>

</template>

import { LightningElement, api} from 'lwc';

export default class CogCompComponent extends LightningElement {


@api inputDate='01 Jan 0000';
@api TrackedProperty='Born in Thretayug';
}

.child
{
font-size: 20px;
color: blue;
}

Parent Component

<template>
<!-- Parent Component-->
<p class="parent"> See !! I am Parent Component</p>
Parent Component Example:
New Year is :{TrackedProperty} : {year}
<!-- Calling the Child Component-->
<c-cog-Comp-Component></c-cog-Comp-Component>
</template>

import { LightningElement, track } from 'lwc';

export default class CogParentComp extends LightningElement {


@track year = 2023;
@track TrackedProperty='Born in Kalyug';
}

.parent{
font-size: 40px;
color: blueviolet;
}

Scenario 17-

<template>
<p>Child Component</p>
<p class="child"> We will listen and Follow India they are our neighbouring
Countries</p>
<div class="pakistan">
<img src="https://www.worldometers.info/img/flags/pk-flag.gif"/>
</div>
<div class="Srilanka">
<img src="https://www.worldometers.info/img/flags/ce-flag.gif"/>
</div>
</template>

.child{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
color: darkmagenta;
}
.pakistan{
max-width: 50%;
height: auto;
}
.Srilanka{
max-width: 50%;
height: auto;
}

Parent
<template>
<p class="child"> LWC Component Composition I am Parent Component</p>
<p class="india"> India will lead neighbouring countries and support them</p>
<div class="indian">
<img src="https://www.worldometers.info/img/flags/in-flag.gif"/>
</div>
<c-cog-Followig-India></c-cog-Followig-India>
</template>

.child{
font-size: 40px;
font-family: Arial, Helvetica, sans-serif;
color: blue;
}
.india
{
font-size: 40px;
font-family: Arial, Helvetica, sans-serif;
color:rgb(247, 247, 11);
}
.Indian
{
max-width: 100%;
height: auto;
}

Custom Settings
Custom settings are similar to custom objects. The concept of custom setting in Salesforce
is similar to that of custom objects. Just like a developer or operator could create custom
objects if the existing Salesforce objects are not enough for the requirements of the
business, custom settings can be created to facilitate application developers in building
custom data sets associate all necessary custom data according to customized and
specific requirements of a profile, a user, an account or the organization as a whole.
However, custom settings have relatively fewer types of fields, which include:

1. Checkbox
2. Date/time
3. Number
4. Percent
5. Text
6. Text area
7. Phone
8. Currency
9. URL

very critical benefits.


1. The data pertaining to custom settings are stored in the application cache.
2. This allows sufficient access to the users, saving them the cost of making several
queries to access the database.
3. Also, using custom settings helps the users in getting rid of Governor Limits almost
completely.
4. Provided the user is employing GET methods and not SOQL to query the settings,
they will be able to extract all the necessary values with absolutely no impact on the
count kept by the governor regarding the number of queries performed by the user.

List Custom Setting


Hierarchy Custom Setting

Use custom settings to create and manage custom data at the organization, profile, and user levels. Custom
settings data is stored in the application cache. This means you can access it efficiently, without the cost of
repeated queries. Custom settings data can be used by formula fields, Visualforce, Apex, and the Web Services
API.

Custom Metadata

10-June-2022

1) Update your Trailhead, Super batches data in the share point excel sheet
2) We will cover below topics in LWC
1)Component Life Cycle
2)Event – Component Communication
Parent to Child communication
Child to Parent communication
3) Salesforce Lighting Data Service
Lightning Record form
Lightning Record View form
Lightning Record Edit Form
Introduce about WebServices

Monday we will have assessment on


Aura and LWC concepts

Component Communication
Component Composition – yesterday we have seen
We have called some of the child components into Parent Component

Parent to Child Component Communication

The primary purpose of using component-based development is performance and


reusability. If you are creating lightning web components, you must come across the
scenario where you need to communicate between them. Communication refers to
passing data between two or more components. There can be two cases. Either
components are connected to each other via some sort of relationship like a Parent-Child
Relationship, or they are independent of each other, i.e., unrelated.
salesforce lightning Aura components where we pass value from parent to child thought
an attribute and then again we need to define that attribute in our child component to
access the passed value.
Also, when we want to pass the value from child to parent component we have used
events in that case.
in LWC, we have to use the @api decorator to make the children properties/method public
available so a parent can be able to call it directly using JavaScript API

Scenario 17 -
How we can pass the value from our parent component to the child component by
using reactive property i.e. @API (which is a public property)

<template>
<lightning-card title="Child Component Data" icon-name="standard.contact">
<p>{myname}</p>
<!-- we will pass the value for myname property from Parent Component-->
</lightning-card>
</template>

import { LightningElement, api } from 'lwc';

export default class CogChildComponent extends LightningElement {


@api myname='first number';
//@api decorator in the child component exposes a property myname to public
}

<template>
<c-cog-Child-Component myname = {parentValue}></c-cog-Child-Component>
<!--Assigning a new property called parentValue-->
<!-- first name which is there in child component is getting overrited by
parent component attribute (parentValue)-->
</template>

import { LightningElement,track } from 'lwc';

export default class CogParentComponent extends LightningElement {


@track parentValue='Second Value passed from Parent Component';
//
}

Scenario 18 - How we can pass the value from our parent component to the child
component by Event communication…I want to pass the value by clicking some
button… event will get registered…
By Event communication I want to pass the values from Parent child when the user
clicks on a button

Where do I need to create an Event…

Update the Scenario 17 ParentComponent.html and JS

<template>
<c-cog-Child-Component myname = {parentValue}></c-cog-Child-Component>
<!--Assigning a new property called parentValue-->
<!-- first name which is there in child component is getting overrited by
parent component attribute (parentValue)-->

<div>
<lightning-button label="Change Value" onclick={changehandler}></lightning-
button>

</div>
</template>

import { LightningElement,track } from 'lwc';

export default class CogParentComponent extends LightningElement {


@track parentValue='Second Value passed from Parent Component';

changehandler()
{
this.parentValue='Third Value passing by Event Click';
}
}

***** Implement pass or communicate from child to parent you can do it by creating
Custom Events (User defined Events)..

But this time because of LWC's modern framework there is no more struggle for that, In
LWC we just have to use CustomEvent() constructor in child component and then handle it
in the parent component.

Event Dispatcher which is responsible for carrying data from child to parent.

Parent Component - <template>


<JS> <css>
<css>

> Event Dispatcher - Passing data


from Child to Parent

Child Component - <template>


Custom Event
<JS> <css>
<css>

>
Scenario 19 Child to Parent Communication with Custom Events

Step-1 Create a Child Event Component I will create one button with an handler

Step-2 In child event component S I will create test variable assign some value.
(Refer childEventComponent.js

Step-3 Its time to handle the event in our parent component


<template>
<span style="margin-left:1em;">
<lightning-button label =" I am Child" variant="brand"
onclick={handlecheck}></lightning-button>
</span>
</template>

import { LightningElement,track } from 'lwc';

export default class CogCustomEventChild extends LightningElement {


@track test='Value received from child';

handlecheck(event)
{
//passing a paramter called event in handlecheck(event)
//defined a const called storeEvent variable to store the event that we
//created and a new instance of CustomEvent with event paramer myevent..
// we are passing this.test which is property contains the value ' Value
received from child'
const storeEvent=new CustomEvent('myevent', {detail:this.test});

this.dispatchEvent(storeEvent);

}
}

<template>
<lightning-card>
<div>
<h1 style='font-size:1.5em;margin-left:45%;' class="slds-text-title">
This is a Parent Component Screen;
</h1>
<br/>
<span style="font-size:2em;margin-left:30%;">
This is the response from the child
<span style="color:blue;">
{response}
</span>
</span><br/>
</div>
<h1>
<c-cog-Custom-Event-Child onmyevent={handleresponse}>
</c-cog-Custom-Event-Child>

</h1>
</lightning-card>
</template>

export default class CogCustParentEvent extends LightningElement {


@track response='';

//here I am going to handle my custom event with {handleresponse} handler

handleresponse(event)
{
// handled the event in handleresponse method where every time
// when user will click on child component button the resonse will
// be captured by child component
this.response=event.detail;
console.log('Event ==>' +JSON.stringify(event));
}
}

Lightning Data Service using LWC

LDS it is a Service for developer who can built LWC componers on LDS
LDS is a framework. specifically designed for Salesforce data

Below are 3 base Lightning components built on Lightning Data Service (LDS)
lightning-record-form
Use the lightning-record-form component to quickly create forms to add, view, or update a
record.
Using this component to create record forms is easier than building forms manually with
lightning-record-edit-form or lightning-record-view-form.
lightning-record-view-form
Use the lightning-record-view-form component to create a form that displays Salesforce
record data for specified fields associated with that record. The fields are rendered with
their labels and current values as read-only.
lightning-record-edit-form
Use the lightning-record-edit-form component to create a form that’s used to add a
Salesforce record or update fields in an existing record on an object. The component
displays fields with their labels and the current values, and enables you to edit their
values.
Scenario 20: Display or view or Load a Record from an Account object onto a LWC
component

Scenario 21: Use Lightning Record Form component to edit a specific record from an
Account Object.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy