Salesforce: Connected Apps

A connected app is a framework that enables an external application to integrate with Salesforce using APIs and standard protocols, such as SAML, OAuth, and OpenID Connect.

Connected apps use these protocols to authenticate, authorize, and provide single sign-on (SSO) for external apps.

The external apps that are integrated with Salesforce can run on the customer success platform, other platforms, devices, or SaaS subscriptions.

For example, when you log in to your Salesforce mobile app and see your data from your Salesforce org, you’re using a connected app.

By capturing metadata about an external app, a connected app tells Salesforce which protocol—SAML, OAuth, and OpenID Connect—the external app uses, and where the external app runs. 

How Can My Salesforce Org Use Connected Apps?

There are several ways in which your org can benefit from using connected apps. Let’s introduce you to these use cases.

Access Data with API Integration

When developers or independent software vendors (ISV) build web-based or mobile applications that need to pull data from your Salesforce org, you can use connected apps as the clients to request this data. To do so, you create a connected app that integrates with Salesforce APIs.

For example, if you want to build a web-based app that pulls in order status from your Salesforce org, you can create a connected app for it. The connected app, with the help of OAuth 2.0, integrates the web-based app with your Salesforce API, giving it authorized access to the defined data.

Integrate Service Providers with Salesforce

When Salesforce acts as your identity provider, you can use a connected app to integrate your service provider with your org. Depending on your org’s configuration, you can use one of these methods.

Use a connected app with SAML 2.0 to integrate a service provider with your org. Salesforce supports SAML single sign-on (SSO) when the service provider or the identity provider initiates the flow.

For example, you’ve built a custom Your Benefits web app that implements SAML 2.0 for user authentication. You want your users to be able to log in to this app with their Salesforce credentials. To set up this SSO flow, configure the Your Benefits web app as a connected app. Because your org implements the SAML protocol, your Salesforce org is already configured as the identity provider. Your users can now log in to the Your Benefits web app with their Salesforce credentials.

You can also use a connected app with OpenID Connect to integrate a service provider with your Salesforce org. To use this option, the service provider must accept OpenID Connect tokens.

For example, you want your users to sign on directly from your Salesforce org to an external Wellness Tracker app that accepts OpenID Connect. To set up this SSO flow, configure the Wellness Tracker app as a connected app with the OpenID Connect scope. This configuration enables the SSO flow for your Wellness Tracker app by integrating the service provider with your Salesforce org.

Provide Authorization for External API Gateways

Salesforce can act as an independent OAuth authorization server to protect resources hosted on an external API gateway. Using OpenID Connect dynamic client registration, resource servers can dynamically create client apps as connected apps in Salesforce. Salesforce can then authorize these connected apps to access protected resources hosted by the third-party service.

For example, Salesforce can act as the OAuth authorization server for API gateways that are hosted on MuleSoft’s Anypoint Platform. MuleSoft’s Anypoint Platform, which is the resource server, can dynamically create client apps as connected apps. These connected apps can send a request to Salesforce asking for access to data protected by the API gateways. Salesforce can then authorize and authenticate the connected apps, granting them access to the data protected by the API gateways.

Manage Access to Third-Party Apps

If your org uses third-party apps, such as a third-party app from the AppExchange, admins can set security policies to control what data the third-party app can access from your org. Admins can also define who can use the third-party app.

For example, you install a third-party app that allows your org’s users to make travel reservations. By selecting the option “Admin approved users are pre-authorized” for the connected app, you can assign specific user profiles to the app. Only the users with this user profile can access the app. You can also set a refresh token policy to revoke the travel reservation app’s access to your Salesforce data after a set amount of time.


Reference resources

Salesforce Help: Connected Apps

Trailhead module: Identity Basics

Salesforce Developers website: Identity Developer Center

Salesforce: Elastic Load Balancing

What Is Elastic Load Balancing?

Elastic Load Balancing automatically distributes traffic across multiple targets to ensure optimum performance in the event of a traffic spike.

Elastic Load Balancing can detect unhealthy targets, stop sending traffic to them, and then spread the load across the remaining healthy targets.

It provides integrated certificate management and Secure Sockets Layer (SSL) decryption, allowing you the flexibility to centrally manage the SSL settings of the load balancer and offload CPU-intensive work from your application.

Types of load balancers.

Elastic Load Balancing offers three types of load balancers.

  • Application Load Balancer
  • Network Load Balancer
  • Classic Load Balancer

Application Load Balancer

An Application Load Balancer can be used to make intelligent routing and load-balancing decisions for HTTP and HTTPS traffic.

For example, suppose that you have broken up a monolithic legacy application into smaller microservices, hosted under the same domain name. You can use a single Application Load Balancer to route requests to the correct target service.

The key difference between the Application Load Balancer and other types of load balancers is that it reads the HTTP and HTTPS headers inside packets and uses this information to intelligently spread the load to targets.

Network Load Balancer

Network Load Balancer can handle volatile workloads and can scale to millions of requests per second. 

Network Load Balancers preserve the source address of connections, making their use transparent to applications and allowing normal firewall rules to be used on targets.

Network Load Balancers support Transmission Control Protocol (TCP) or User Datagram Protocol (UDP) traffic to targets for the life of the connection, making them a great fit for Internet of Things (IoT), gaming, and messaging applications.

For example, you can use a Network Load Balancer to automatically route incoming web traffic across a dynamically changing number of instances. Your load balancer can act as a single point of contact for all incoming traffic to the instances in your Auto Scaling group.

You can automatically increase the size of your Auto Scaling group when demand goes up and decrease it when demand goes down.

Network Load Balancer features include:

  • The ability to handle tens of millions of requests per second while maintaining high throughput at ultra-low latency, with no manual effort
  • Routing connections to targets (for example, Amazon EC2 instances, containers, and IP addresses) based on IP protocol data
  • API-compatibility with an Application Load Balancer
  • Optimization for handling sudden and volatile traffic patterns while using a single static IP address per Availability Zone.

Classic Load Balancer

The Classic Load Balancer provides basic load balancing across multiple Amazon EC2 instances and operates at both the request level and connection level.

It is the legacy Elastic Load Balancing tool intended for applications that were built within the EC2-Classic network.

Unlike the Classic Load Balancer, the Application Load Balancer and Network Load Balancer are purpose-built and offer more robust features to meet specific needs.


Additional Resources

Pardot vs Marketing Cloud

PardotMarketing Cloud
ModelPardot is positioned as a B2B platform.Salesforce Marketing Cloud is B2C platform. 
ChannelEmail and SocialEmail, Social, SMS, display advertising
Pardot is primarily an email marketing platformMarketing Cloud has other functions like Advertising Studio and Mobile Studio
ProductSalesforce product Salesforce product
Supported BySalesforce team Salesforce team
IndustryNon-specificAutomotive, Retail, FMCG, travel, health,Pharma.
Consideration ifSmaller databases with higher value salesLarger databases with smaller value sales 
ComparePardot enables greater marketing and sales alignment for B2B teamsSalesforce Marketing Cloud is great for 1:1 customer journey communications with mixed communication channels
KeywordsLead generation, lead scoring, lead assignment, sales enablement, email nurture campaigns, content marketing, webinar marketingReal-time messaging, cross-channel marketing, mobile marketing, social media, display advertising, e-commerce.
PricingSimple pricing modelRelatively higher price.
Certifications Salesforce provideSalesforce provide

WordPress and Pardot Using Salesforce SSO

Step 1: Download the Pardot Plugin in WordPress

  1. Log into WordPress.
  2. Navigate to the Plugins section.
  3. Click on ‘Add New’.
  4. Search for ‘Pardot’.
  5. It should look like the below, and you’ll see an install button where it says active.

6. Once you click install, navigate to the Plugins tab, locate Pardot, and click activate.

Step 2: Configure your Salesforce Connected App in Salesforce

  1. log into Salesforce and navigate to the set up. Search for App Manager.
  2. On the top right corner click ‘New Connected App’ . Try in classic for better to view all connected apps.
  3. Fill the Connected App name and Email id.
  4. Under the API (Enable OAuth Settings) section.
  5. Check: Enable OAuth Settings
  6. Enter your call back URL. The call back URL points users back to the Pardot plugin. Navigate back to the tab with the Pardot plugin open and copy that URL. It should look something like this: https://<<your wordpress domain name >>/wp-admin/options-general.php?page=pardot.

7. Under Selected OAuth Scopes be sure to select: Access Pardot Services (pardot_api) and Perform requests on your behalf at any time (refresh_token, offline_access)

8. Check the box to Require Secret for Web Server Flow.

Once you complete this step, click save. Upon saving the new app the consumer key and customer secret will be generated.

Step 3: Complete the configuration into Pardot Plugin.

  1. Navigate back to your WordPress tab with the Pardot plugin.
  2. Change the authentication type to SSO.

3. For Business unit id. You can find this by going to Pardot > Pardot Account Setup > Business unit id.

4. Then click authenticate with Salesforce. If you aren’t already logged into your Salesforce org, you’ll be prompted to enter your credentials.

5. Once it successfully authenticates, you’ll see the authentication status turn green and it should say “Authenticated with Salesforce SSO”.

Once you have completed the installation above, a blue Pardot button will be added to your text editor. From here you’ll be able to add forms and dynamic content from your Pardot instance to your website without the use of code.


Ref :

Pardot : marketing automation platform

What is Pardot ?

Pardot is Salesforce’s B2B marketing automation solution. If you’re a business with marketing and sales teams that work to drive pipeline and grow revenue, Pardot can automate your marketing activities and unite your marketing and sales departments so that they can work better together.

Pardot gives you a central location to manage your marketing initiatives and report on their success. Not only that, but it tracks prospects as they interact with your company marketing channels, like your website, emails, and forms, so your marketing and sales teams can deliver a personalized experience.

Marketing automation terms :

Funnel Stages : Marketing automation terms

Lead (or demand) generation: The act of creating interest in your products or services through marketing efforts.

Visitor: An anonymous person who visits your website and is now tracked in Pardot. 

Conversion: Once a visitor gives you their contact information, such as an email address, by submitting a Pardot landing page or form, they are converted to a prospect.

Prospect: An anonymous visitor that has converted and is now identified. A record of the prospect will exist in Pardot, similar to a lead record in Sales Cloud or other CRMs.

Lead nurturing: Sending targeted messages at specific intervals based on a prospect’s actions and whether or not they’ve met certain qualifying criteria. 

Lead qualification: You probably have thousands (or even hundreds of thousands) of people interacting with your organization. Your sales teams can’t contact each of them, so as marketers it’s your job to help send them the best prospects. This process of finding the gold needles in the haystack of prospects is called lead qualification. You decide the threshold for when a prospect is ready to be assigned to a salesperson for them to follow up.

Pardot uses two metrics for lead qualification: score and grade. 

  • Prospect score: A prospect’s score is a numerical value indicating how interested they are in your product or service. A prospect’s score can increase or decrease based on how they interact with your marketing materials.
  • Prospect grade: A prospect’s grade is represented by a letter (A, B, C, D, etc.).  It indicates how closely a prospect fits the profile of your ideal prospect.

You can leverage score and grade to determine which prospects are ready to reach the end of the funnel and have a salesperson follow up with them. With the help of Pardot automation, you can quickly assign qualified prospects to the appropriate salesperson.

Campaigns: Campaigns help you understand how your marketing initiatives are performing. Campaigns are used a few different ways in Pardot.

For example, every prospect in Pardot has an assigned campaign that tells you the first marketing-related contact they had with your company. You can also use campaigns to group relevant marketing materials together. And most importantly, you can use Pardot automation with campaigns to track all the marketing touchpoints in a prospect’s journey, which opens the door to better ROI reporting.

When to use Pardot ?

Pardot is a great fit when you want to: 

  • Generate more leads and move them quickly through the pipeline
  • Engage buyers on their terms with dynamic, personalized campaigns
  • Understand each step from click to close, capturing true marketing ROI
  • Remove silos across organizations that lead to disjointed customer experiences
  • Make data driven decisions
  • Strengthen or build your account-based marketing (ABM) strategy

Reference : Salesforce Trailhead

Salesforce Best Practices

Data Model Design

  • Reuse the maximum standard objects of the platform.
  • Be aware of the behavior for these objects, especially on Lead (that becomes an Account and a Contact) and Opportunity (stage, probability…).
  • Be careful of relationship type you want to implement, sometimes lookup is enough but try to identify future needs to select the right relation (for example when a field of the parent object should be updated -by workflow- when the child changes, it’s only possible with a master-detail relationship…).
  • Be careful when choosing the right field type and name as when they’re deployed it’s a high risk to modify them.
  • Consider making a field required when he’s updatable by both the UI and web service or other apex code.
  • Identify the different kinds of users/actors, their relation (visibility of records), their rights (profile).
  • Field API Name should be as short as possible. Avoid using underscores, use a capital letter for each word, and abbreviate words.
  • Create a default record type when creating an object. This will prevent data migration later when you will need to manage record types
  • Ensure you have Field Level Securities giving access to all fields for a technical profile, to be able to backup all your data
  • Custom Settings: Optimize the length of your text fields. You have limited storage, even if you put data with a shorter length it will really be estimated with full length.
  • Visibility: Think twice before defining Org Wide Defaults for external users as “public” on an object.
  • When defining an existing field as required, ensure (or migrate) existing records have no empty value for that field
  • If “Strictly enforce picklist values” option enabled, picklist values must be aligned with your data

Integration Design

  • Identify the volume of data exchanged.
  • Identify the direction: inbound, outbound.
  • Identify the type: sync / async.
  • Identify the integration process: batch, oneshot.
  • Favor inbound message using the standard Enterprise / Partner API as custom inbound or outbound are expensive to develop (except for outbound call using the workflow).

Logic Design

  • Match each need with available technology to build the logic (Validation Rule, Workflow, Approval Process…).
  • Manage configuration limits: number of workflows, of filtered lookups…
  • Use Apex code in a last consideration.
  • Any item configured should have comments in the description attribute
  • Enforce naming conventions

Code – general

  • Keep the right visibility. Use “with sharing” for your class, or document why you would run without sharing
  • Don’t code if you can configure it. Allowed exception is related to performance.
  • Comment your code
  • Do not hard code IDs. If you need some invariant Ids in some circumstance you can put them in a System Label
  • Keep your code small. This will better manage the 3Mb limit, make you think on an optimized algorithm, and most of the time make your code faster. Ex: is it necessary to define a temporary variable that will be used only once?
  • Always code for performance.
  • Ensure system.debug() is consistent to the context (ex: do not log “after insert” if you are in a “before insert” trigger)
  • Avoid multi-line tests. This could have negative impact on code coverage if part of the test is false.
  • Remove commented code to have clean classes
  • Never use try..catch when the purpose is only to hide errors (with no code in the catch, or just a system debug). The user or admin should be notified by the error
  • Do not have a different behavior when testing vs when running (spaghetti code using if(System.Test.isRunningTest())
  • Apex Callouts – Do not hard code credentials in the code. Use named credentials as endpoints to simplify authenticated Apex callouts and manage credentials through the Setup user interface.
  • Do not hardcode email addresses
  • Put outside the FOR loops invariants. Ex: Contact.sObjectType.getDescribe() or Schema.SObjectType.Contact.fields.getMap();
  • Do not call @future methods inside FOR loops. These methods should be bulkified and called after the loop.
  • Use only one return statement par method.
  • Remove unnecessary local variables, empty blocks and empty methods

SOQL in Apex

  • Avoid SOQL queries statements inside loops (for, while..)
  • Leverage SOQL capability to reduce Apex code
    • Capability to order results, filter, query multiple objects in 1 query through relationships
    • Capability to aggregate date and do computation (select SUM()…)
    • Put the result directly in a map instead of doing this in a for..loop
    • Nested for..loop with a SOQL query in the container loop can implicitly manage batch records, reducing heap consumption and increasing speed (because of smaller lists). for(Account[] accs:[Select Name from Account limit 10000])for(Account a:accs){do something}
  • Make efficient SOQL queries. Ex: [select Name from Profile where id in (select ProfileId from User where Id=:UserInfo.getUserId())] could be rewritten as [select Name from Profile where Id=:UserInfo.getProfileId()]
  • Limit returned records. If a query is returning multiple records, you must add “limit xxx” at the end of the query to manage governor limits
  • Whenever it is possible, try to use 1 query for multiple records on the same object, instead of 1 query per record.
  • Do not query on fields that you will not use
  • When querying users, don’t forget to filter on the isActive field
  • To filter your query, use the DeveloperName field instead of the Name field when the queried object has both (i.e.: Group, RecordType…)
  • When doing a query on RecordType object, filter on SObject name as you can have the same recordType developerName across multiple objects
  • Reduce joins in queries. If you need an id of the record from a lookup, do not code select from theObject__c. Prefer this one: select theLookup__c from theObject__c


  • Use a DML for a list of records instead of 1 DML per record (bulk)
  • Do not perform DML inside of loops


  • Don’t forget that trigger handle up to 200 records per execution.
  • Don’t put the logic (incl. SOQL or DML) in the trigger, use a handler class.
  • Don’t push trigger.New to the handler class method, you should filter on records that are in related scope. You will increase performance, reduce governor limits consumption, and limit regression risks when updating the class.
  • Create 1 trigger per event and per object. Multiple triggers for the same event of an object would not ensure that the execution order would always be the same, giving unpredictable behavior in production. Managing multiple events in the same trigger would reduce maintainability with spaghetti code.
  • Put bypass logic in the trigger for each handler class. This would prevent running some code for some users. For instance, a technical user doing data migration will have improved performance if some business logic is not triggered. For this purpose, you should use PAD framework. Ensure that each bypass keyword used in triggers is defined in the bypass multi-picklist definition.
  • Always optimize. Even if you think it is not needed, as your trigger can be run from another trigger, which can reach governor limits.
  • Beware of over optimization side effects; when optimizing SOQL queries and DMLs, you will probably use structured maps indexed by IDs. This consumes a lot in memory as triggers are limited in heap size and each trigger in the transaction can consume much heap. Free memory if such structures are not needed after usage.


  • Bind your pages with the code using “Page.VisualforcePageName” instead of “new PageReference(‘/apex/VisualforcePageName’)”. Impact and dependencies will be better managed (ex: when renaming the page), and this is the only way to be compatible with CRSF protection.
  • Reduce ViewState to get better performance.
  • Secure your code (SOQL injection, etc.). If you leverage an URL parameter you should make sure that it is of the expected type with a correct value.

Test Classes

  • Prefer creating multiple testMethods in a test class instead of one big method. Benefit is maintainability
  • Avoid using seealldata=true in test classes to avoid conflict (locking contention) with real production data
  • Always assert() in test methods
  • Leverage a @testSetup method to reduce execution time and increase maintainability
  • Test the limits (bulk)
  • Use test.startTest() after data preparation and test.stopTest() before asserts
  • It is better to do Test Driven Development. It is more productive development.
  • Prefer target 85% code coverage per class


  • Keep you page light (few fields, simple DOM, avoid frameworks), for performance and usage.
  • Remove commented code (<!– … –>) to increase maintainability and improve server parsing performance
  • Do not hardcode access to Visualforce Pages (value=”/apex/PageName”) as it will break when CRSF is enabled. Use either {!$Page.PageName} or {!URLFOR($Page.PageName)}
  • Reduce frameworks usage to keep the page light and performant (RAM footprint, network impact, CPU consumption…)
  • Manage errors. An error can still occure, warn the user with putting one of the following tags on the top of your page: <apex:pageMessages /> or <apex:messages />


  • Keep the number of profiles low. Use permission sets if one profile as a few more permissions than another existing profile.
  • Remove unused custom profiles
  • Profiles should not be API enabled, except when really necessary, for security reasons.


  • Keep your role hierarchy simple. If you have one role per user, and some roles without users, you probably have a design issue

Validation Rules

  • Don’t use hard coded IDs
  • Put a bypass system in the logic
  • When adding a Validation Rule, migrate existing records that don’t match this rule.
  • Keep the quantity of VR low to manage performance
  • Define the error message at the field location instead of at the top of the page.
  • Remove inactive Validation Rules

Workflow rules and actions

  • Don’t use hard coded IDs
  • Put a bypass system in the logic
  • Don’t create multiple workflows with the same rule
  • Remove Workflow actions that are not used by workflow rules
  • Remove rules that have no actions
  • Keep the quantity of WR low to manage performance
  • Remove inactive workflows
  • Don’t update fields if the current value is already correct

Process Builder

  • Put a bypass logic within each test
  • Don’t update fields if the current value is already correct

Static Resources

  • Do not host credentials (security risk)
  • Use the description field to tell where the resource is being used
  • Optimize picture compression and size. Use the appropriate file format.

Custom Labels

  • Avoid duplicate labels with the same value

Naming conventions

  • Avoid using underscores
  • Classes: Use UpperCamelCase
  • Variables and methods: use camelCase with the first letter in lowercase
  • Test classes: Append “Test” to the name of the covered class
  • Trigger: [ObjectName][Event]. Example: AccountBeforeInsert

Salesforce Best Practice For Test Class

Please follow below salesforce Best Practice for Test Classes.

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can’t be a interface or enum .
15. Test method code can’t be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock
19. You can’t  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,’ResourceName’).
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI, IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .

Salesforce Admin and Development Scenario Based Questions -1

1.When ever a record is inserted to the account automatically inserted to the contact.

trigger SCENARIO1 on Account (after insert) {
list c=new list();
contact b=new contact();
insert c;


2.When ever a record is inserted to the contact automatically inserted to the account.

trigger scenario2 on Contact (after insert) {
lista=new list();
account a1=new account();


insert a;


3.How to avoid recursive trigger in salesforce ?

public class Recursive {
public static boolean flag=true;


3.When ever a created opportunity object record, update total opportunities and total amount in account object.

trigger scenario24 on Opportunity (after insert) {
setids=new set();
listac=[select Total_opportunities__c,Total_Amount__c,(select id,Amount from Opportunities ) from account where id=:ids];
for(account a:ac)
decimal sum=0;
for(opportunity p:a.opportunities)

update ac;

4.On contact object ,when ever department equal to cse automatically insert email on email field.

trigger scenario4 on Contact (before insert) {


5.When ever we modifying inputout__c object doctor name automatically update on droppoff__c object text field on relationship.

trigger SCENARIO32 on Inputout__c (after update) {
listd=[select id,name,Text__c from Dropoff1__c where Text__c=’naveen’];
string name;
for(Dropoff1__c dp:d)
update d;


6.Limit reached the records.

trigger SCENARIO6 on Account (before insert,before update) {
integer count=0;
lista=[select id,name from account where createddate=today or lastmodifieddate=today];
ac.adderror(‘reached limit today’);


7.can not insert/update/delete that user account object records

trigger scenario30 on Account (before insert,before update,before delete) {
user u=[select id,name from user where username=’’];
for(account a:trigger.old)
a.adderror(‘cant delete record’);







            b.adderror(‘can not update’);







            c.adderror(‘can not insert’);





8.Already existing records display an error message.

trigger scenario8 on Contact (before insert) {
listst=new list();



   list<contact>a=[select id,name,Email,lastname from contact where Email=:c.Email];



        c.Email.adderror(‘already existing’);




9.for loop without query.

trigger duplicatetrigger on Inputout__c (before insert) {
sets=new set();
listd=[select id,Doctor_Name__c from Inputout__c where Doctor_Name__c=:s];
setdupids=new set();
for(Inputout__c don:d)
c.Doctor_Name__c.adderror(‘already existing record’);

9.count of related contacts and accounts field display size

public class rollupsummery {

public static void increment(list<contact>con)


    set<id>ids=new set<id>();

    for(contact c:con)




    list<account>a=[select id,name,NumberOfEmployees,(select id,lastname from contacts) from account where id=:ids];

    for(account ac:a)




    update a;



trigger scenario11 on Contact (after insert) {
rollupsummery.increment(; }

  1. when ever opportunity stagename =closedwon automatically update the account field rating=hot.

trigger scenario12 on Opportunity (after insert,after update) {
setids=new set();
listac=new list();

ac=[select id,name,rating from account where id=:ids];

    if(op.StageName==’Closed won’)


        for(account a:ac)




        update ac;




11.when ever account name is “SFDCForum” automatically update the contact all lastnames.

trigger scenario13 on Account (after update) {

    string names;

    list<contact>c=[select id,lastname,firstname from contact where lastname=:names ];




for(contact con:c)




update c;


12.When ever a opportunity created record amount field is calculated by account total field

trigger scenario21 on Opportunity (after insert,after update,after delete) {
setids=new set();
mapopp=new map();
Decimal oldVal;
Decimal newVal;



        opp.put(op.AccountId, op);


    list<account> acc=[select id,Total_Amount__c from account where  id=:ids];

    for(account a:acc)


        if(a.Total_Amount__c==null )






        a.Total_Amount__c= a.Total_Amount__c+opp.get(a.Id).amount;



    update acc;







        opp.put(op.AccountId, op);



    for(Opportunity  ops:trigger.old){



    list<account> acc=[select id,Total_Amount__c from account where  id=:ids];

    for(account a:acc)


        if(a.Total_Amount__c==null )






        a.Total_Amount__c= a.Total_Amount__c+opp.get(a.Id).amount-oldVal;



    update acc;



13.when ever a create a lead object automatically converted account ,contact,opportunity.

trigger scenario19 on Lead (after insert) {
listacc=new list();
listcon=new list();
listop=new list();
account a=new account();
contact c=new contact();


    opportunity o=new opportunity();


    o.StageName=’closed won’;



insert acc;

insert con;

insert op;


14.when ever create a contact automatically update opportunity fields.

trigger scenario17 on Contact (after insert) {
listop=[select id,name,stagename,Description,amount from opportunity limit 50];
for(opportunity o:op)






    update o;




  1. What is Action poller in salesforce.

public class actionpoller1 {
public datetime dateandtime{get;set;}
public void datetimemethod()

Visualforce page :

<apex:page controller=”actionpoller1″>


        <apex:pageBlock id=”pb”>

            <apex:actionPoller action=”{!datetimemethod}” reRender=”pb” interval=”5″ />


                refresh 5 mins




16. What is Action : status

public class actionstatus {

Integer count = 0;
public PageReference incrementCounter() {


return null;


public Integer getCount() {

return count;



visualforce page:

<apex:page controller=”actionstatus”>

<apex:form >

<apex:outputpanel id=”counter”>

<apex:outputText value=”Click Me!: {!count}”/>

<apex:actionSupport event=”onclick” action=”{!incrementCounter}” rerender=”counter” status=”counterStatus”/>


<apex:actionStatus id=”counterStatus” startText=” (processing…)” stopText=”(completed)”/>



17.What is Aggregate functions in salesforce?

public class aggregatefunctions {
public listac{get;set;}
public integer count{get;set;}
public decimal sum{get;set;}
public decimal min{get;set;}
public decimal max{get;set;}
public aggregatefunctions()
ac= [select id,name,AnnualRevenue from account where name=:’naveen’];
count=[select count() from account];
aggregateresult res=[select sum(AnnualRevenue)sumt,min(AnnualRevenue)mint,max(AnnualRevenue)maxt from account ];


Visualforce page:

<apex:page controller=”aggregatefunctions” >

    <apex:form >

        <apex:pageBlock >

            <apex:pageBlockSection >

                <apex:pageBlockTable value=”{!ac}” var=”n”>

                    <apex:column value=”{!}”/>

                    <apex:column value=”{!n.AnnualRevenue}”/>









18.Sending email outbound email message

public class emailprogramme1 {
public void myemails()
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
string[] toadd=new string[]{‘’};
string[] tocc=new string[]{‘’};
m1.setPlainTextBody(‘this is interview call letter’);[] m2=new messaging.Email[]{m1};



emailprogramme1 v=new emailprogramme1();

18.Outbound message pdf file.

public class emailprogramme2 {
public void emailbody()
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
string[] toadd=new string[]{‘’};
m1.setSubject(‘Pdf file’);
m1.setPlainTextBody(‘THIS IS BILL OF TELEPHONE’);
messaging.EmailFileAttachment m2=new messaging.EmailFileAttachment();
pagereference p=page.page1;
blob body=p.getContentAsPDF();
messaging.EmailFileAttachment[] eft1=new messaging.EmailFileAttachment[]{m2};
messaging.Email[] m3=new messaging.Email[]{m1};


Output :

emailprogramme2 v=new emailprogramme2();

19.sending email template to outbound message

public class emailprogramme3 {
public void emailmethod()
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
emailtemplate et=[select id from emailtemplate where name=’doctor’ ];
contact c=[select id,lastname,phone from contact where phone=’999′];
Inputout__c D=[select id,Doctor_Name__c from Inputout__c limit 1];
messaging.Email[] m2=new messaging.Email[]{m1};



emailprogramme3 v=new emailprogramme3();

20.Sending email trigger.

trigger sendingmailtrigger on Inputout__c (before insert) {
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
string[] toadd =new string[]{‘’};
m1.setPlainTextBody(‘this is interview call letter’);
messaging.Email[] mail1=new messaging.Email[]{m1};




Salesforce Lightning and LWC Interview Questions

1.How to call a controller method in javascript?

var action=component.get(“methodname”)

2.What is the use of do init method?

It will be loaded on loading of lightning applicationIt  is pretty much similar to constructor.

3.What is the use of attribute?

Attribute is like a variable. If you want to store the datathen we should go with attribute.

4.What is bounded expression?

We will able to get the new value. syntax: {!v.attribute name}

5.What is unbounded expression?

we will not able to get the new value. syntax:{#v.attributename}

6.What is the use of AuraEnabled annotation?

if you want to access the data in the lightning applicationthen we should write AuraEnabled annotation->we will not able to access the data in lightning application without auraEnabled

7.What is the use of global action in the controller?

$A.enqueueAction(action)It’s used to execute the server side logic

8.Can we write void method in lightning?


9.How to get the response from callback?


10.How to  get the state in controller?


11.Why helper method is a best practice in lightning?

It’s used for re usability.

12.What is reusability in lightning?

We will able to access the value from one method to other method.

function(component){var name=’sfdcscenarios’;this.method2(name);


function(name){//reusabilityconsole.log(‘name from method1 is’+name);}

13.Does it happens in the controller?

No. It will happens in the helper.

14.what framework lightning will follow?

aura framework.

15.How many tags we have in lightning?

ui tagsLightning tags.

16.What is exends=”force:slds”?

It will acquire the properties of lightning design system?

17.What happens if you don’t put exends=”force:slds”  in lightning application?

It will look like normal html file.

18.What is v in attribute?

It’s a value provider. If you want to access the value from the attribute then we willuse {!v.attrname} or{#v.attributename}

19.When we should go with unbounded expression?

If you are simply dealing with read operation then we should go withunbounded expression

20. Does reusability is possible in  controller?


21.What is Lightning component bundle?

component controller helper design svg Documentation style renderer.

22.What is renderer?

If you want to override the standard rendering mechanism in salesforce lightningthen we should go with renderer.

23.What are the events in salesforce lightning?

1.component event
2.application event
3. system events

24..Which interface should you use if you want to get the id of the record from the record Detail page?


25. can we call one component to another component?

Yes,we can call. to call lightning component in visual force page?

<aura:application access=”GLOBAL” extends=”ltng:outApp”>
    <aura:dependency resource=”c:FlipCard”/>
*Add the <apex:includeLightning /> component to your Visualforce page.
*Reference a Lightning app that declares your component dependencies with $Lightning.use().
*Write a function that creates the component on the Visualforce page with $Lightning.createComponent(). to pass the parameters in controller?


28.How to  Navigate From One Lightning Component to Another Lightning Component?


29. How to go from one lightning page to another lightning page through a click?

 var urlEvent = $A.get(“e.force:navigateToURL”);

30.Best practices for lightning?

1.Do not put so many console logs.
2.Make the use of Salesforce lightning design system for consistent ui design.
3.Make the use of Lightning data services to avoid server calls for Dml operations.2.
4.Use unbounded expressions if the data across components are not required to be in synch.
5.Before you decide to use a third-party library in a Lightning component, you should reevaluate if you really need that library. DOM manipulation libraries (like jQuery) and UI libraries (like Bootstrap or jQuery UI) in particular may no longer be needed when working with the Lightning Component Framework.
6.When possible, use the (sprite-based) Lightning Design System icons (using <lightning:icon> and <lightning:buttonIcon>) instead of custom icons.
7.Salesforce is slower for users who have debug mode enabled. So, do not enable in Production.
8.When appropriate consider passing the data in different components(using attributes,events or methods) rather than retrieving the same data in different components.
9.When making a call to the server limit the columns and rows of the result set. Only select the columns you need.
10.Set a limit on the query and provide paging mechanisum if needed. Don’t return huge number of rows at once.
11.Consider combining several requests(actions) in a single composite request.
Cache the data when possible.
12.Caching the data at the client side can significantly reduce the number of server round trips and improve the performance tips. A storable action is a server action whose response is stored in the in the client cache so that subsequent requests for the same server method with the same set of arguments can be accessed from that cache.
13.Try to limit number of event handlers in your Lightning component. As you can guess, multiple event handler means your component would be busy in listening event changes resulting in performance overload.
14.Always try to use a component event instead of an application event, if possible. Component events can only be handled by components above them in the containment hierarchy so their usage is more localized to the components that need to know about them. Application events are best used for something that should be handled at the application level, such as navigating to a specific record. Application events allow communication between components that are in separate parts of the application and have no direct containment relationship.
15.Use helper methods.
16.To improve runtime performance, set @AuraEnabled(cacheable=true) to cache the method results on the client. To set cacheable=true, a method must only get data. It can’t mutate data.

30. Where we can use Lightning Components?

We can use Lightning Components in the following places:
1.Drag-and-drop Components in the Lightning App Builder and Community Builder.
2.Add Lightning Components to Lightning Pages.
3.Add Lightning Components to Lightning Experience Record Pages.
4.Launch a Lightning Component as a Quick Action.
5.Override Standard Actions with Lightning Components.
6.Create Stand-Alone Apps.

31. Which interface should you use if you want your component to be available for all pages?

You can use the flexipage:availableForAllPageTypes interface.

32. Which interface should you use if you want to override a standard action?

You will need to use the Lightning:actionOverride interface.

33.Which interface should you use if you want your component to be available only on the record home page?

You will need to use the flexipage:availableForRecordHome interface.

34.Which interface should you use if you want your component to be used a tab?

You will need to use the force:appHostable interface.

35.Which interface should you use if you want your component to be used a quick action?

You will need to use the force:lightningQuickAction interface.

36.How can you call the controller method based on a component load?

“<aura:handler  name=”init” value=”{!this}” action=”{!c.doInitialization}”/

37. What are component events?

Component events are events which are fired by child components and handled by the parent component. We can make use of this event when we need to pass a value from a child component to parent component.

38. What are application events?

Application events can be fired from any component and can be handled by any component. They do not require any kind of relationship between the components, but these components must be a part of a single application.

39. What is force:recordData, and what are its advantages?

force:recordData is a standard controller of a Lightning Component. We can perform an operation such as creating a record, editing a record,deleting a record using force:recordData. If we are using force:recordData, it identifies and eliminates the duplicate request going to the server if they are requesting for the same record data (which in turn improves performance).

40.What are the phases in component events propagation?

There are two phases in component event propagation.
1.Bubble Phase
2.Capture Phase

41.  What are the phases in application events propagation?

1.Bubble Phase
2.Capture Phase
3.Default Phase

42.How do the bubble phase and the capture phase propagate?

Bubble phase: propagates from Bottom to Top.
Capture phase: propagates from Top to Bottom.

43.What is Aura:method in Salesforce Lightning component?

we can directly call a child component controller method from the parent component controller method using Aura:method. This method is used to pass value from parent component controller to the child component controller.

44.What is Lightning:overlayLibrary in Salesforce Lightning component?

To create a modal box we use Lightning:overlayLibrary. To use Lightning:overlayLibrary in component we need to include tag <lightning:overlayLibrary aura:id=”overlayLib”/> in component, here aura:id is unique local id. Modal has header,body and footer which are customizable.

45. what are the lightning webcomponent bundle?

LWC bundle contains an HTML file, a JavaScript file, and a metadata configuration file and these files are created once we create a Lightning web component.We can also create a .css file for styling purpose and We can also create SVG file for the purpose of displaying icon.

46.What are the types of decorators in lightning web components?

We have 3 Decorators in Lightning Web Components.
1) @api

2) @track

3) @wire

47.  Is there any limit on how many component to have in one Application ?

There is no limit.

48. Is Lightning Components replacing Visualforce ? 


49. What are the advantages of lightning ?

The benefits include an out-of-the-box set of components, event-driven architecture, and a framework optimized for performance.
Out-of-the-Box Component Set -: Comes with an out-of-the-box set of components to kick start building apps. You don’t have to spend your time optimizing your apps for different devices as the components take care of that for you. Rich component ecosystem-: Create business-ready components and make them available in Salesforce1, Lightning Experience, and Communities.
Performance – :Uses a stateful client and stateless server architecture that relies on JavaScript on the client side to manage UI, It intelligently utilizes your server, browser, devices, and network so you can focus on the logic and interactions of your apps.
Event-driven architecture -: event-driven architecture for better decoupling between components
Faster development – : Empowers teams to work faster with out-of-the-box components that function seamlessly with desktop and mobile devices.
Device-aware and cross browser compatibility – : responsive design,supports the latest in browser technology such as HTML5, CSS3, and touch events.

50. How can we  deploy components to production org ?

we can deploy component by using managed packages, IDE, Migration Tool or Change Sets.

51. How we can access Custom Label in Lightning?

Syntax : $A.get(“$Label.namespace.labelName”)

52. How we can use component in the community builder?

Implements “forceCommunity:availableForAllPageTypes” interface on the component.