Saturday, 24 November 2018

Rest Integration With Postman



Step: 1

  • For Rest Integration with using POSTMAN tool first you need to create the Connected app in your org.like shown in the below Image.





Step :2


  • After saving the connected app you will be getting a Consumer key And Consumer Secret.





Step:3

  • Now you need to install/ add postman chrome extension and register with your Google account.
  • Then you need to copy Callback URL From connected app then paste the URL in postman url section as shown in below pic.
  •  we need to write body section under Grant type
  • syntax: grant_type=password&client_id=your_clientid_here&client_secret=your_client_secret_here&username=your_username&password=your_password_hereWithsecuritytoken 
  • Client_id = Consumer Key, client_secret = Consumer secret,password = your password with securitytoken 
  • Ex:  grant_type=password&client_id=3MVG9YDQS5WtC11rG9SGkhKCagCn2tK1zutzAjxjg0FiN9jt97YDsyW27HbUS2gjxWClYumtI7DrKYmZ5MFVy &client_secret=4464276243039650923&username=malleshmyakala@developer.com&password=Mallesh@25s2TZJjF8P9zLx1RAwTtNYNABD
  • URL type should be POST, Then click on send.






  • After hitting the send button you will be seeing the authentication code.
  • when status code =  "200 ok" it means executed successfully 
  • here we will get Access Token                                                                                 authentication code:                                                                                                                   {                                                                                                                                           "access_token":"00D6F000001O0Y4!ARAAQLbZ0_vR.ijv3sdsKAu6d5xF7Aj2Mmt2_nXQDNf1aPgfICSrIynLsqdlebVRY0de0bZTxspSFmhXYv0o6ftnzAIn8Mpd",                "instance_url": "https://manuyadav-dev-ed.my.salesforce.com",                                              "id": "https://login.salesforce.com/id/00D6F000001O0Y4UAK/0056F000006j2ohQAA", "token_type": "Bearer",                                                                                                 "issued_at": "1542617533665",                                                                                   "signature": "k8yPqZ9WRAzBGAiVLdsBrnmz8ZRN44wi26m5tlZl0BA="                              }
  • Now we need to setup Content Type = "application/json" and Authentication= "Bearer access_token" in Headers Tab.                                                                                         Ex:Bearer 00D6F000001O0Y4!ARAAQLbZ0_vR.ijv3sdsKAu6d5xF7Aj2Mmt2_nXQDNf1aPgfICSrIynLsqdlebVRY0de0bZTxspSFmhXYv0o6ftnzAIn8Mpd


Step:4

 write the code for Rest API like below.

@RestResource(urlMapping='/AccountService/*')
Global class RestServiceTest {
    
    
    @httpPost
    global static string dopost(string accName, string Phone){
        Account acc = new Account();
      acc.Name = accName;
        acc.Phone=Phone;
        insert acc;
        
        return'Post method called successfully'+Acc.Id; 
    }
    
       @httpGet
    global static List<account> doGet(){
        
        RestRequest request = RestContext.request;
        
        string AccId=request.requestURI.substring(request.requestURI.lastindexOf('/')+1);
        system.debug('====accId===='+accId);
        list<account> lstAccs= [select id,name,phone from account where id=:accId];
        return lstAccs;
        
        }
    }

After writing the Code for Rest API then we need to create URL.

EX: https://manuyadav-dev-ed.my.salesforce.com/services/apexrest/AccountService
  • https://manuyadav-dev-ed.my.salesforce.com/(This is your org URL)
  • services/apexrest/(this is common service for postman)
  • AccountService(this is urlMapping name in your Rest class @RestResource)      


enter  (Postman URL)  in post section in postman tool. write the JSON code in the body section. then hit send button.
.
If Status is "200 ok" then you will find  created account Id. as shown in the below pic
this is the process for creating the record using REST API service through POSTMAN tool.



  • Now coming to GET process 
  • Under the get type enter the URL
  • EX: https://manuyadav-dev-ed.my.salesforce.com/services/apexrest/0016F00002zmISH                     https://manuyadav-dev-ed.my.salesforce.com (Your Org URL )                                                       /services/apexrest/   (Common service)                                                                                            0016F00002zmISH (This is account ID)
  • Then just hit send button now you will be getting the particular account details as shown in below pic.




This is the process for getting the record details using REST API Service through Postman.



Tuesday, 20 November 2018

How to stop recursive trigger in salesforce



What is a Recursive Trigger :

A recursive trigger is one that performs an action, such as an update or insert, which invokes itself owing to,  say something like an update it performs.

How to avoid Recursive Trigger:

To avoid recursive triggers you can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.

Example:

Apex Code:
public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
 }
    }
}

 Trigger Code:

trigger updateTrigger on anyObject(after update) {
    if(checkRecursive.runOnce())
    {
    //write your code here            
    }
}


Example2: Scenario: There is an after update trigger on account object. In the trigger, there is a date field we are checking the date is changed or not if it is changed we are doing some process.The trigger is executed five times in the transaction. ​
Apex Code:
public class ContactTriggerHandler
{
     public static Boolean isFirstTime = true;
}
Trigger Code:
trigger ContactTriggers on Contact (after update)
{
    Set<String> accIdSet = new Set<String>(); 
    if(ContactTriggerHandler.isFirstTime)
    {
        ContactTriggerHandler.isFirstTime = false;
         for(Contact conObj : Trigger.New)
  {
            if(conObj.name != 'Test') 
     {
                accIdSet.add(conObj.accountId);
            }
         }
   // any code here
    }
}

=====================================================================================

Apex Class Code:
public class checkRecursive {
     public static Set<Id> SetOfIDs = new Set<Id>();
}
Trigger Code:
trigger TestTrigger on Account (before insert) {
    if (Trigger.isAfter && Trigger.isInsert) {
        List<Account> accList = new List<Account>();
      for (Account test: Trigger.new) {
          If(!checkRecursive.SetOfIDs.contains(test.Id)){
              test.Name = 'helloworld'; 
              accList.add(test);
            checkRecursive.SetOfIDs.add(test.Id);
          }
      }
      insert  accList;
    }
}

Monday, 8 October 2018

SFDC scenario based interview Questions

1) Consider this scenario
I  have a profile  by name 'ProvideReadAccess' and two users U1 and U2 assigned to it. And I have object X.
My Question is I want to have ReadWrite access for U1 and ReadOnly access for U2  for the object X.
How do I do this?

Answer:
Read Access for both users is common hence in the Profile settings give 'Read' access for the object 'X'
By doing this User U2 will be able to read all the records( One condition satisfied) but U1 will also be able to only read the records(Second condition not satisfied).

So next what do we do is we create a permission set say 'GrantWriteAccess' and in this permission set we give the object 'X' the Write access and assign the user U1 to this permission set.(2nd condition satisfied).

Explanation about when and where to use permission set and profile


2) Consider a scenario
I have not given any CRUD permission in the profile 'P1' for an object O1, yet I'm able to create records for object 'O1'. How could this be possible?

Answer:  Any permission with respect to creation /deletion/Updating/viewing of object is possible only through permission set or Profile.
Meaning If we are able to create records in a object then the Create Permission in either Profile or in Permission Set should be enables. If its not enabled in the Profile then it has be in the Permission set.

So check for the permission set.

3)Consider a scenario

I have two un related objects Obj1 and Obj2. Now I want to create a Master Detail relation between these objects how do I do this?
One tow
Answer: First  choose which object has to be a Parent object(Master) and Child Object(Detail).
For our understanding lets say for now we decide Obj1 to be Master object and Obj2 to Detail object.

First lets under stand what's a Master Detail relation ? Every child should have  a parent. Which means every record in Obj2 should have a related parent record in Obj1. Also One child can have only one parent. But One parent can have multiple children.

Scenario 1: if there are pre existing records in the Obj2 then?
With the above understanding on Master Detail relation we have to be sure that every record in Obj2 has a related record in Obj1.
And in our scenario Obj1 and Obj2 are not related to each other. So first we have to create a basic Look up relation between these two objects so that we can establish a relation between these two objects.
So we follow below steps
 1st we create a Lookup field in the Child Object Obj2 pointing to Obj1 as parent.
2nd Update the Lookup field of all the records in Obj2 with a  value from the Obj1 (Related field)
3rd Then we convert the Look up field to Master Detail relation.


Scenario2: If there are no pre existing records in the Obj2 then?


4)Consider a scenario
I'm trying to implement Pagination. Initially i want to dispaly 50 records and when user click on Next button, the records stating from 51 to 100 should get displayed. How do I accomplish this.

Answer: The key question here is how do we fetch next 50 records when user clicks on 'Next'?
                   One possible way to implement this is to have 'OFFSet' used in SOQL which fetches the records.
                   Eg:   SELECT Name from Merchandise__c 
                            where Price__c > 5
                            Order by Name Limit  100
                             OFFSET 50

5) I have 2 workflow Rules and two Fields F1 and F2
When ever F1 is updated to value= 10,  WF1 fires and updates F1 value to 20 and F2  value to 30
When ever F1 values=  20 there is another Workflow W2 fires which will update F1 to 10 and F2 to 20
What will be the outcome of this Workflow rule.


Answer: This scenario will cause  recursive Workflow rule
                   This will exhaust the governor limit and result in error

6)I have a User, Who will leave the organization tomorrow. He is basically a manager and there are 15 users below him.
Now when this user leaves the organization i would generally inactivate the User.
But now my concern is if I inactivate this user What happens to the Role hierarchy? the assignment rules, Approval processes, the records created by him and records to which he is the default owner like leads and cases. And what would be best possible solution to keep this application intact and running and yet have this user de activated?

Answer: To prevent users from logging into your organization while you perform the steps to deactivate them, you can freeze user accounts. [Spring Summer 14]
So in this way untill you find ways to remove this User from Role hierarchy/assigenment rules/update the Owner of the records created by him / from any place where this user is used, we can make use of FREEZE button on the USer record.
Note:
1. When we click on FREEZE button, the user will not be able to login  to the application any more.
2. Freezing user accounts doesn't frees the user licenses available for use in your organization. We have to      de activate the user to free the license.

7) I want to delete 20000 records and I dont want them to be recovered from recycle bin.
OR
I want to do a mass delete on set of records and dont what them getting into recycle bin.
What possible options do I have?

- Yes this is possible, Use Hard Delete Option

8)Let say I have a page which displays the set of records from Account object and I'm using a standard controller.  Now I have two users belonging to same Profile. When they login and view this page, they get  a message "Insufficient privileges". What could be the reason for this? Or who would u arrive at a solution?
- Notice below points:
- Question speaks about standard Object and Standard Controller.
 - Also remember permission to a object is given by Profile.
So we need to check if the user has pemssion to read data of this Object.
Only if the permission is given to the user,he'll be able at access them else he will get an error message as "Insufficient privileges"


9)I have Stadard Controller and Controller Extension. You can write all that logic in Controller Extension which can be written in Custom Controller. Also both Controller Extenstion and Custom controller execute in System Mode. So Why do we need Custom Controller ?

Answer:
 1st point Controller Extension cant exist on its own. It has to be implemented on a Standard Controller or a custom controller.
So keeping the above point in mind, Lets say certain methods needs to be executed in User Mode and certain in System Mode. In this scenario it makes absolute sense to User Standard Controller with Custom Extenstion. Where in using  Standard Controller provides all pre existing features of Force.com platform.
But note that When we use Standard Controller All the Sharing rules, permissions of a user are respected.
So if this what we wanted then we should go for an implementaiton of this sort.

Other wise if we are building all features on own like Save Edit Update and delete then we should be using Custom Controller.

10) Let say I have a page which displays the set of records from Account obkect and i'm using a standard controller. Now I have two users belonging to same profile. When they login and view this page, they get a message "Insufficient privileges" . What could be the reason for this? Or who would u arrive at a solution?

-Notice below points:

==> Quetion speak about standard Object and Standard Controller.
==> Also remeber permission to a object is given by profile.
So we need to check if the user has permission to read of this Object.
Only of the permission is given to the user, he'll be able at access them else he will gwt an error messages as "Insufficient privileges".

Some Realtime Interview Quetions



     
1) Salesforce provides two WSDL files, what are the differences?

Resolution:
     
Salesforce provides a WSDL (Web Service Description Language) files. They are called "Enterprise WSDL" and "Partner WSDL". A WSDL is an XML-document which contains a standardized description on how to communicate using a web service (the Salesforce API is exposed as a web service). The WSDL is used by developers to aid in the creation of Salesforce integration pieces. A typical process involves using the Development Environment (eg, Eclipse for Java, or Visual Studio for .Net) to consume the WSDL, and generate classes which are then referenced in the integration.

The primary differences between the two WSDL that we provide are:

Enterprise WSDL:
a) The Enterprise WSDL is strongly typed.
b) The Enterprise WSDL is tied (bound) to a specific configuration of Salesforce (ie. a specific organization's Salesforce configuration).
c) The Enterprise WSDL changes if modifications (e.g custom fields or custom objects) are made to an organization's Salesforce configuration.

For the reasons outlined above, the Enterprise WSDL is intended primarily for Customers.

Partner WSDL:
a) The Partner WSDL is loosely typed.
b) The Partner WSDL can be used to reflect against/interrogate any configuration of Salesforce (ie. any organization's Salesforce configuration).
c) The Partner WSDL is static, and hence does not change if modifications are made to an organization's Salesforce configuration.

For the reasons outlined above, the Partner WSDL is intended primarily for Partners.

To download a WSDL file when logged into Salesforce:

1. Click Setup | Develop | API

2. Click the link to download the appropriate WSDL. It will be something like: "Generate <type_of_wsdl> WSDL"

3. Save the file locally, giving the file a ".wsdl" extension.



 

2) I have created a batch process. Let say I have thousands of records to process. Now what i want is when there is an error

encounter or some problem found in the data during the batch process, I want to stop or abort the batch process. Is it possible ?

ANS: public void execute(Database.BatchableContext bc, List<SObject> scope) {
   
      try {
       
            ...
   
            }
      catch (Exception e) {
      
             // Report errors here
      
             System.abortJob(bc.getJobId());
   
            }
}


3) If Run a Batch classe some records would be failed Now how to recover that failed records.?

 
using below method we can.
Database.SaveResult[] SaveResultList = Database.insert(accts,false); 

4) Schedule apex to run every 10 Min..??

You have to schedule your batch for 6 times, if you want to run batch for every 10 mints.
System.schedule('Scheduled Job 1', '0 0 * * * ?', new scheduledTest());

System.schedule('Scheduled Job 2', '0 10 * * * ?', new scheduledTest());
 
System.schedule('Scheduled Job 3', '0 20 * * * ?', new scheduledTest());
 
System.schedule('Scheduled Job 4', '0 30 * * * ?', new scheduledTest());

System.schedule('Scheduled Job 5', '0 40 * * * ?', new scheduledTest());
 
System.schedule('Scheduled Job 6', '0 50 * * * ?', new scheduledTest());



 

5) The difference between regular (non-static) and static methods


Java is a Object Oriented Programming(OOP) language, which means we need objects to access methods and variables inside of a class. However this is not always true.
While discussing static keyword in java, we learned that static members are class level and can be accessed directly without any instance.
In this article we will see the difference between static and non-static methods.

Static Method Example
class StaticDemo
{
  
public static void copyArg(String str1, String str2)
   {
       //copies argument 2 to arg1
       str2 = str1;
       System.out.println("First String arg is: "+str1);
       System.out.println("cond String arg is: "+str2);
   }
  
public static void main(String agrs[])
   {
      /* This statement can also be written like this:
       * StaticDemo.copyArg("XYZ", "ABC");
       */
     
copyArg("XYZ", "ABC");
  
}
}
 
Output:

First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t use any object. It can be accessed directly or by using class name as mentioned in the comments.

Non-static method example
class JavaExample
{
   public void display()
   {
       System.out.println("non-static method");
   }
   public static void main(String agrs[])
   {
         JavaExample obj=new JavaExample();
         /* If you try to access it directly like this:
          * display() then you will get compilation error
          */
       obj.display();
   }
}
Output:

non-static method
A non-static method is always accessed using the object of class as shown in the above example.

Notes:
How to call static methods: direct or using class name:

StaticDemo.copyArg(s1, s2);
OR copyArg(s1, s2);
How to call a non-static method: using object of the class:

JavaExample obj = new JavaExample();
Important Points:

Static Methods can access static variables without any objects, however non-static methods and non-static variables can only be accessed using objects.
Static methods can be accessed directly in static and non-static methods. For example the static public static void main() method can access the other static methods directly. Also a non-static regular method can access static methods directly.


6) Best Practices for Improving Visualforce Performance

>> Cache any data that is frequently accessed, such as icon graphics.

>> Avoid SOQL queries in your Apex controller getter methods.

>> Reduce the number of records displayed on a page

>> “Lazy load” Apex objects to reduce request times.

>> Consider moving any JavaScript outside of the <apex:includeScript> tag and placing it in a <script> tag



28. What are the Best Practises for Improving Visualforce Performance ?
Answer:
1) The view state size of your Visualforce pages must be under 135 KB. By reducing your view state size, your pages can load quicker and stall less often.
2) Large page sizes directly affects load times. To improve Visualforce page load times:
· Cache any data that is frequently accessed, such as icon graphics.
· Avoid SOQL queries in your Apex controller getter methods.
· Reduce the number of records displayed on a page by adding filter condition in SOQL
3) Reduce Multiple Concurrent Requests: use <apex:actionpoller>

4) By using the with sharing keyword when creating your Apex controllers, you have the possibility of improving your SOQL queries by only viewing a data set for a single user.


see More: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_best_practices_performance.htm


7)I need to ascending order of following strings based on first name manu yadav, ann reddy, paa goud how can you achive this.

list<string> str = new list<string>();
 
str.add('manu yadav');
str.add('ann reddy');
str.add('paa goud');
 
str.sort();
 
system.debug('the list of names'+str);


 

8) Below is the Salesforce Order of Execution:


System Validation rule (required field, field format) (SV)
 
Before Triggers are executed (BT)
 
Custom Validation rules are checked (CV)

After Triggers are executed (AT)

Assignment Rules are executed (AR)

Auto-Response Rules are executed (ARR)

Workflow Rules are executed (WR)
 
Before and after triggers are executed one more time if the workflow rule updates a field (BT & AT)
 
Escalation Rules are executed (ER)
 
Parent Rollup Summary Formula or Cross Object Formula fields are updated in the respective objects. (RSF, COF)

(These parent records also goes through the entire execution order)

Criteria Based Sharing rules are evaluated (CBS)

Any Post-Commit Logic is executed (PCL) 
(like sending an email)

Below will help you to remember Order of Execution in Salesforce:

SV -> BT -> CV -> AT -> AR -> ARR -> WR (BT, AT) -> ER -> RSF, COF -> CBS -> PCL

 

Saturday, 29 September 2018

Trigger Scenario Questions


Trigger Scenario 1:
Create “Top X Designation” custom object which is related list to Opportunity (Look up Relationship). In the Top X Designation object, create the fields
·                                              Type (Picklist),
·                                               Document Attached (Checkbox)
Create one field Handoff Attached with picklist type with values are Yes, No on Opportunity Object.
Logic :-  If Type (Top X Designation) = “Contract Flow Down/Handoff”, and “Document Attached” = True then “Handoff Attached” = True, otherwise false.
Code:-
triggerUpdateHandoffAttached on Top_X_Designation__c(after insert, after update,
after delete) {
 List<Opportunity>listoppUpdate=new List<Opportunity>();
 List<Opportunity>listopp=new List<Opportunity>();
 Set<Id>setOppId=new Set<Id>();
 Set<Id>setOppDelete=new Set<Id>();
map<id,id>mapDocAttchTrue = new map<id,id>();
map<id,id>mapDocAttchFalse = new map<id,id>();
map<id,id>mapDelete = new map<id,id>();
if(Trigger.isInsert || Trigger.isUpdate){
for(Top_X_Designation__cada:Trigger.New){
if(ada.Document_Attached__c==True &&ada.Item_Type__c=='Contract Flow
 Down/Handoff'){
mapDocAttchTrue.put(ada.Opportunity,ada.id);
setOppId.add(ada.Opportunity);
 }
else
mapDocAttchFalse.put(ada.Opportunity,ada.id);
setOppId.add(ada.Opportunity);
 }
 }
if(Trigger.isDelete){
for(Top_X_Designation__cada:Trigger.old){
mapDelete.put(ada.Opportunity,ada.id);
setOppId.add(ada.Opportunity);
setOppDelete.add(ada.Opportunity);
 }
 }
listopp = “select id,Handoff_Attached__c from Opportunity where id in: setOppId”;
if(listopp.size()>0 &&listopp !=null){
for(Opportunity opp:listopp){
if(mapDocAttchTrue.containskey(opp.id)){
opp.Handoff_Attached__c='Yes';
 }
if(mapDocAttchFalse.containskey(opp.id)){
opp.Handoff_Attached__c='No';
 }
if(setOppDelete.contains(opp.id)){
opp.Handoff_Attached__c='';
 }
listoppUpdate.add(opp);
 }
 }
if(listoppUpdate.size()>0 &&listoppUpdate!=null){
updatelistoppUpdate;
system.debug('LLLLLLLLLLLLLLL'+listoppUpdate);
 }
 }
Trigger Scenario 2:-
The following Trigger will fires when we try to create the account with same name i.e Preventing the users to create Duplicate Accounts
triggerAccountDuplicateTrigger on Account (before insert, before update)
{
for(Account a:Trigger.new)
 {
 List<Account>acc=“Select id from Account where Name=:a.Name and Rating=:a.Rating
 “;
if(acc.size()>0)
 {
acc.Name.addError('You Cannot Create the Duplicate Account');
 }
 }
 }
Trigger Scenario 3:-
The following trigger updates the field called “Hello” by the value “World”whenever we are creating an account or updating an account record. Create the field called “Hello” on the Account Object (Data Type = Text)
triggerHelloWorld on Account (before insert, before update)
{
 List<Account>accs = Trigger.new;
MyHelloWorld my= new MyHelloWorld(); //creating instance of apex class
my.addHelloWorld(accs); // calling method from the apex class
 }
Class:
public class MyHelloWorld
 {
public void addHelloWorld(List<Account>accs)
 {
for (Account a:accs)
 {
if (a.Hello__c != 'World')
 {
a.Hello__c = 'World';
 }
 }
 }
 }
Trigger Scenario 4:-
The following trigger describes about when the leads are inserted into the data base it would add Doctor prefixed for all lead names. This is applicable for both inserting and updating the lead records.
triggerPrefixDoctor on Lead (before insert,before update)
{
 List<Lead>leadList = trigger.new;
for(Lead l: leadList)
 {
l.firstname = 'Dr.'+ l.firstname;
 }
 }
Trigger Scenario 5:-
The following trigger adds the Opportunity Owner into the sales team automatically whenever the Opportunity is created.
triggerOppTeam on Opportunity (after insert) {
 List<OpportunityShare>sharesToCreate = new List<OpportunityShare>();
 List<OpportunityTeamMember>oppteam = new List<OpportunityTeamMember
> ();
OpportunityShareoshare = new OpportunityShare();
oshare.OpportunityAccessLevel = 'Edit';
oshare.OpportunityId = trigger.new”0”.Id;
oshare.UserOrGroupId = trigger.new”0”.createdbyid;
sharesToCreate.add(oshare);
OpportunityTeamMemberot = new OpportunityTeamMember();
ot.OpportunityId = trigger.new”0”.Id;
ot.UserId = trigger.new”0”.OwnerId;
ot.TeamMemberRole = 'Account Manager';
oppteam.add(ot);
if(Oppteam!=null &&Oppteam.size()>0)
 {
insertOppteam;
 }
if(sharesToCreate!=null &&sharesToCreate.size()>0)
 {
list<Database.SaveResult>sr = Database.insert(sharesToCreate,false);
}
 }
Trigger Scenario 6:-
Create the object called “Books” and create field “Price”(data type is Currrency) under this object.
Whenever we enter some amount of money in the Price field and once we click on save
button, the value we entered in the Price field is 10% less than the actual price. This is
applicable for while both inserting and updating records.
triggerDiscountTrigger on Book__c (before insert, before update) {
 List<Book__c> books = Trigger.new;
PriceDiscount.applyDiscount(books);
 }
 [1]
Class
public class PriceDiscount {
public static void applyDiscount(List<Book__c> books) {
for (Book__c b :books){
b.Price__c *= 0.9;
 }
 }
 }
Trigger Scenario 7:-
The following trigger will prevent the users from deleting the Accounts. This is because System Administrator has all the permissions, we cannot change the permissions.
triggerAccountDelete on Account (before delete) {
for(Account Acc:trigger.old)
 {
acc.adderror('You Cannot Delete the Account Record');
 }
 }
Trigger Scenario 8:-
Create Custom field called “Number of Locations” on the Account Object (Data Type=Number)
The following trigger creates the number of contacts which are equal to the number which we will enter in the Number of Locations field on the Account Object
Code:
triggerContactsCreation on Account (after insert) {
list<contact>listContact = new list<contact>();
map<id,decimal>mapAcc=new map<id,decimal>();
for(Account acc:trigger.new){
mapAcc.put(acc.id,acc.Number_of_Locations__c);
 }
if(mapAcc.size()>0 &&mapAcc!=null){
for(Id accId:mapAcc.keyset()){
for(integer i=0;i<mapAcc.get(accId);i++){
contactnewContact=new contact();
newContact.accountid=accId;
newContact.lastname='contact'+i;
listContact.add(newContact);
 }
 }
 }
if(listContact.size()>0 &&listContact!=null)
insertlistContact;
 }
Trigger Scenario 9:-
Create the object called “Customer Project” and create Status field under this object with picklist data type (Values=Active, Inactive). Create the relationship between this custom object and Opportunity so that Customer Project is related list to the Opportunity.
Create  Active Customer project‑ field on Opportunity object (Data Type=Checkbox)
The logic is when we create Customer Project for an Opportunity with the Status=Active, then Active Customer project check box on the Opportunity detail page is automatically
checked.
Code:-
triggerUpdateCPActivenOnOppty on Customer_Project__c (after insert)
 {
 List<Opportunity>opps=new List<Opportunity>();
for(Customer_Project__ccp:Trigger.New){
if(cp.Status__c=='Active'){
 Opportunity opp= new Opportunity(id=cp.Opportunity__c);
opp.Active_Customer_Project__c = True;
opps.add(opp);
 }
 }
updateopps;
 }
Trigger Scenario 10:-
Description:
We have Stakeholder object that is related list to Opportunity and Contact. On Contact detail page, we have NPS ID field on the Contact detail page that is look up to the Voice of NPS object (Customer Object). The following code will get the NPS ID field value from the Contact detail page in the Stackholder’s page which we can able to clickable.
Create NPS Id 1 field on the stackholder object which is the look up to the Voice of NPS object (Customer Object)
Note:-
‑we can also get the NPS Id 1 on the Stakeholder’s page using the formula field but will not able to clickable.
Code Single Record:-
triggerUpdateNPSid on Stakeholder__c (before insert, before update){
 List<id>ConList=new List<id>();
for(Stakeholder__csh:Trigger.New){
ConList.add(sh.Contact_Name__c);
 }
 List<Contact>lc=“Select NPS_Id__c From Contact Where id IN :ConList”;
for(Stakeholder__csh:Trigger.New){
 sh.NPS_Id1__c=lc”0”.NPS_Id__c;
 }
 }
Code Bulk Records:-
triggerUpdateNPSid on Stakeholder__c (before insert, before update){
 List<id>ConList=new List<id>();
map<id,id>map_NPS_Cont = new map<id,id>();
for(Stakeholder__csh:Trigger.New)
 {
if(sh.Contact_Name__c!=null)
ConList.add(sh.Contact_Name__c);
 }
 List<Contact>lc=“Select Id,NPS_Id__c From Contact Where id IN : ConList”;
if(lc!=null &&lc.size()>0)
 {
for(Contact c:lc){
If(c.NPS_Id__c!=null){
map_NPS_Cont.put(c.Id,c.NPS_Id__c);
 }
 }
for(Stakeholder__csh:Trigger.New){
if(sh.Contact_Name__c!=null)
 sh.NPS_Id1__c = map_NPS_Cont.get(sh.Contact_Name__c);
else
 sh.NPS_Id1__c = null;
 }
 }
 }
Trigger Scenario 11:-
Create “Sales Rep” field with data type (Text) on the Account Object. When we create the Account record, the Account Owner will be automatically added to Sales Rep field. When we update the Account owner of the record, then also the Sales Rep will be automatically updated.
triggerUpdateSalesRep on Account (Before insert,Before Update){
 Set<Id>setAccOwner=new Set<Id>();
for(Account Acc: trigger.new)
 {
setAccOwner.add(Acc.OwnerId);
 }
 Map<Id,User>User_map = new Map<Id,User>(“select Name from User where id
in:setAccOwner”);
for(Account Acc: Trigger.new)
 {
 User usr=User_map.get(Acc.OwnerId);
 Acc.sales_Rep1__c=usr.Name;
 }
 }
Trigger Scenario 12:-
Create the field called “Contact Relationship” checkbox on the Contact Object and Create the object called “Contact Relationship” which is related list to the Contacts.(Look Up Relationship).
Now logic is when we create contact by checking Contact Relationship checkbox, then Contact Relationship will be created automatically for that contact.
Code:
triggerCreateCRonContactCreation on Contact (after insert) {
if(trigger.isAfter)
 {
if(trigger.isInsert)
 {
ContactMasterHandlerConIns = New ContactMasterHandler();
ConIns.createContactRelationshipByContact(trigger.New);
}
 }
 }
Class:
Public Class ContactMasterHandler {
public void createContactRelationshipByContact(list<Contact>List_Contacts)
 {
list<Contact_Relationship__c>ConList= new list<Contact_Relationship__c>();
for(Contact newconts:List_Contacts)
 {
if(newconts.Contact_Relationship__c== true)
 {
Contact_Relationship__c CR = new Contact_Relationship__c();
CR.Name=newconts.Lastname;
CR.Contact__c= newconts.id;
ConList.add(CR);
 }
 }
insertConList;
 }
Trigger Scenario 13:-
When we change the Owner of the Contact Relationship, then the Owner name will be automatically populated in the Contact Relationship Name field.
Trigger:
triggerContactRelationshipMasterTrigger on Contact_Relationship__c(before update)
 {
if(trigger.isBefore)
 {
if(trigger.isUpdate)
 {
 //call the handler for the before update trigger event
updateCROwnerNameConRelUpd = New updateCROwnerName();
ConRelUpd.updateContactRelationshipNameByOwner(trigger.New);
 }
 }
 }
Class:
Public Class updateCROwnerName{
public void updateContactRelationshipNameByOwner(list<Contact_Relationship__c> co
nt_Rel)
 {
map<Id,Id>map_Id_Own = new map<id,id>();
map<Id,string>map_id_Name = new map<id,string>();
set<id>Idset = new set<id>();
for(Contact_Relationship__cList_recs:cont_Rel)
 {
Idset.add(List_recs.Ownerid);
 }
list<user> u=“select id,Name from user where id in:Idset”;
for(user list_users:u)
 {
map_id_Name.put(list_users.Id,list_users.Name);
 }
if(u!=null &&u.size()>0)
 {
for(Contact_Relationship__cList_recs:cont_Rel)
 {
if (List_recs.Ownerid!=null)
 {
List_recs.Name = map_id_Name.get(List_recs.Ownerid);
 }
 }
 }
 }
 }
Trigger Scenario 14:-
Create the field called “Contact Relationship” checkbox on the Contact Object and Create the object called “Contact Relationship” which is related list to the Contacts.(Look Up Relationship).
Trigger Scenario 12 logic will says that when we create contact by checking Contact Relationship checkbox, then Contact Relationship will be created automatically for that contact.
No this logic will for when we delete the Contact, Then Contact Relationship will be deleted automatically
 triggerDeleteCRonContactDeletion on Contact (before delete) {
if(trigger.isBefore)
 {
if(trigger.isDelete)
for(Contact c:Trigger.old)
 {
Contact_relationship__c CR=new Contact_relationship__c();
 CR=“Select Id from Contact_Relationship__c where Contact__cIN:GlobalUtility.getUni
queIds(Trigger.Old)”;
delete CR;
 }
 }
 }
 }
Global Utility Classs:
public static set<Id>getUniqueIds(list<SObject> sobs)
 {
set<Id> Ids = new set<Id>();
for (SObject sob : sobs) {
Ids.add(sob.Id);
 }
return Ids;
 }
Trigger Scenario 15:-
Create the field called “Contact Relationship” checkbox on the Contact Object and Create the object called “Contact Relationship” which is related list to the Contacts.(Look Up Relationship).
Trigger Scenario 14 will says that when we delete the Contact, Then Contact Relationship will be deleted automatically
Now the Logic is when we undelete the Contact, then Contact Relationship will be undeleted automatically
Triggser:
triggerUnDeleteCRonContactUnDeletion on Contact (After Undelete) {
if(trigger.isUndelete)
 {
//call the handler for the after undelete trigger event
ContactMasterHandler_UndeleteConIns = New ContactMasterHandler_Undelete(
 );
ConIns.undeleteContactRelationshipsByContact(Trigger.New);
 }
 }
Class
Public Class ContactMasterHandler_Undelete{
public void undeleteContactRelationshipsByContact(list<Contact>List_Contacts)
 {
set<Id>ContactIds = New set<Id>();
if(List_Contacts!=null &&List_Contacts.size()>0)
 {
list<Contact_Relationship__c>List_ConRels= new list<Contact_Relationship__c>(
 );
List_ConRels= “select id from Contact_Relationship__c where isDeleted=TRUE and Co
ntact__c in: GlobalUtility.getUniqueIds(List_Contacts)”;
undeleteList_ConRels;
 }
 }
 }
Trigger Scenario 16:-
Create field called “Count of Contacts” on Account Object. When we add the Contacts for that Account then count will populate in the field on Account details page. When we delete the Contacts for that Account, then Count will update automatically.
Inclined towards the profession of the Salesforce?
Then what is the waiting for..study the blog post on Salesforce Training to master the skill.
Note:
The above logic will be applicable when we have look up relationship. But When we have the Master – Detail relationship, then we can create Rollup Summary field to get the count of child records using “Count” function.
triggerCountOfContacts on Contact (after insert,after delete) {
set<id>accid=new set<id>();
list<contact>contactlist =new list<contact>();
list<contact>listcon=new list<contact>();
list<account>acclist=new list<account>();
list<account>listAcc=new list<account>();
map<id,integer>mapCount=new map<id,integer>();
if(trigger.isinsert){
for(contact con:trigger.new){
accid.add(con.accountid);
 }
 }
if(trigger.isdelete){
for(contact con:trigger.old){
accid.add(con.accountid);
 }
 }
acclist=“select id,name from account where id in:accid”;
contactlist = “select id,name,accountid from contact where accountidin:accid”;
for(account acc:acclist){
listcon.clear();
for(contact c:contactlist){
if(c.accountid==acc.id){
listcon.add(c);
mapCount.put(c.accountid,listcon.size());
 }
 }
 }
if(acclist.size()>0){
for(Account a:acclist){
if(mapCount.get(a.id)==null)
a.Count_Of_Contacts__c=0;
else
a.Count_Of_Contacts__c=mapCount.get(a.id);
listAcc.add(a);
 }
 }
if(listAcc.size()>0)
updatelistAcc;
 }
Trigger Scenario 17:-
Create the object called “Customer” and create the Master-Detail Relationship on Customer object so that Customer will be the related list to Account record. Create the field called “Account Manager” on Customer object which is lookup to the user object.
Now Logic is when we create Customer record for account record, then the user in Account Manager field will be automatically added to Account Team of that associated account.
Code:
triggerInsertAccountTeam on Customer__c (after insert) {
 List<AccountTeamMember>atm_list=new List<AccountTeamMember>();
AccountTeamMemberatm = new AccountTeamMember();
 List<AccountShare>newShare = new List<AccountShare>();
if(trigger.isInsert)
 {
For(Customer__c c:Trigger.new)
 {
if(c.Account_Manager__c!=null){
atm = new AccountTeamMember();
atm.accountid=c.Account__c;
atm.teamMemberRole='Account Manager';
atm.UserId=c.Account_Manager__c;
AccountShare shares = new AccountShare();
shares.AccountId=c.Account__c;
shares.UserOrGroupId = c.Account_Manager__c;
shares.AccountAccessLevel='Read/Write';
shares.OpportunityAccessLevel = 'Read Only';
shares.CaseAccessLevel='Read Only';
newShare.add(shares);
atm_list.add(atm);
 }
 }
if(atm_list!=null)
insertatm_list;
if(newShare!=null &&newShare.size()>0)
 List<Database.saveresult>sr=Database.insert(newShare,false);
 }
 }
Trigger Scenario 18:-
The above trigger(Trigger Scenario 17) Logic is when we create Customer record for account record, then the user in Account Manager field will be automatically added to Account Team of that associated account.
Now the following trigger logic is when we update the user in the “Account Manager”, the Account team will be updated automatically.
Code:
triggerUpdateAccountTeam on Customer__c (before update) {
 List<AccountTeamMember>atm_list=new List<AccountTeamMember>();
AccountTeamMemberatm = new AccountTeamMember();
 List<AccountShare>newShare = new List<AccountShare>();
if(trigger.isupdate)
 {
if(trigger.isbefore)
 {
 Set<Id> setAccIds1=new Set<Id>();
 Set<Id>setDelATM=new Set<Id>();
 Map<id,Set<Id>>mapAccMgrs=new Map<id,Set<Id>>();
for(Customer__c c:Trigger.new)
 {
if(trigger.oldmap.get(c.Id).Account_Manager__c!=c.Account_Manager__c
&&c.Account_Manager__c!=null )
 {
setAccIds1.add(c.Account__c);
 }
 }
 List<Customer__c>listPLAccMgrs=“select id,Account_Manager__c,Account__c
fromCustomer__c where Account__c in:setAccIds1 and id not
in:trigger.newmap.keyset()”;
if(listPLAccMgrs!=null &&listPLAccMgrs.size()>0)
 {
for(Customer__c c:listPLAccMgrs)
 {
 Set<Id>idMgrs=mapAccMgrs.get(c.Account__c);
if(null==idMgrs){
idMgrs=new set<Id>();
mapAccMgrs.put(c.Account__c,idMgrs);
 }
idMgrs.add(c.Account_Manager__c);
 }
 }
 Map<id,List<AccountTeamMember>>mapStdAccTeam=new
 Map<id,List<AccountTeamMember>>();
 List<AccountTeamMember>listStdAcc Team=“select id,UserId,AccountId from
AccountTeamMember where AccountId in:setAccIds1 “;
if(listStdAccTeam!=null &&listStdAccTeam.size()>0){
for(AccountTeamMemberrecAccTeam :listStdAccTeam)
 {
 List<AccountTeamMember>
listStdAccTeamMap=mapStdAccTeam.get(recAccTeam.AccountId);
if(null==listStdAccTeamMap){
listStdAccTeamMap=new List<AccountTeamMember>();
mapStdAccTeam.put(recAccTeam.AccountId,listStdAccTeamMap);
 }
listStdAccTeamMap.add(recAccTeam);
 }
 }
system.debug('***********'+mapAccMgrs);
for(Customer__c c:Trigger.new)
 {
if(trigger.oldmap.get(c.Id).Account_Manager__c!=c.Account_Manager__c
&&c.Account_Manager__c!=null )
 {
 List<AccountTeamMember>
listAccTeam=mapStdAccTeam.get(c.Account__c);
 Set<Id>idMgrs=mapAccMgrs.get(c.Account__c);
if(listAccTeam!=null &&listAccTeam.size()>0 )
{
if(idMgrs!=null &&idMgrs.size()>0 &&
!(idMgrs.Contains(trigger.oldmap.get(c.Id).Account_Manager__c)))
 {
for(AccountTeamMemberrecATM:listAccTeam)
 {
if(recATM.UserId==trigger.oldmap.get(c.Id).Account_Manager__c)
setDelATM.add(recATM.Id);
 }
 }
else if(idMgrs==null)
 {
for(AccountTeamMemberrecATM:listAccTeam)
setDelATM.add(recATM.Id);
 }
 }
atm = new
AccountTeamMember(accountid=c.Account__c,teamMemberRole='Account
 Manager',UserId=c.Account_Manager__c);
AccountShare shares = new AccountShare();
shares.AccountId=c.Account__c;
shares.UserOrGroupId = c.Account_Manager__c;
shares.AccountAccessLevel='Edit';
shares.OpportunityAccessLevel = 'None';
newShare.add(shares);
atm_list.add(atm);
 }
 }
List<AccountTeamMember>listDelATM=“select id from AccountTeamMember
whereidin:setDelATM”;
if(listDelATM!=null &&listDelATM.size()>0 )
deletelistDelATM;
if(atm_list!=null)
insertatm_list;
if(newShare!=null &&newShare.size()>0)
 List<Database.saveresult>sr=Database.insert(newShare,false);
 }
 }
Trigger Scenario 19:-
The trigger scenario 17 Logic is when we create Customer record for account record, then the user in Account Manager field will be automatically added to Account Team of that associated account.
Now the following trigger gives the logic about when we delete the “Customer” of that account, then the user will deleted automatically from the Account Team of that account.
triggerDeleteAccountTeam on Customer__c (before delete) {
 List<AccountTeamMember>atm_list=new List<AccountTeamMember>();
AccountTeamMemberatm = new AccountTeamMember();
 List<AccountShare>newShare = new List<AccountShare>();
if(trigger.isdelete)
 {
set<id>setAccids = new set<id>();
 Set<Id>setDelATM=new Set<Id>();
 Map<id,Set<Id>>mapAccMgrs=new Map<id,Set<Id>>();
for(Customer__c c:Trigger.old)
 {
setAccids.add(c.Account__c);
}
 List<Customer__c>listPLAccMgrs=“select id,Account_Manager__c,Account__c from
Customer__c where Account__cin:setAccids and id not in:trigger.oldmap.keyset()”;
if(listPLAccMgrs!=null &&listPLAccMgrs.size()>0)
 {
for(Customer__c c:listPLAccMgrs)
 {
 Set<Id>idMgrs=mapAccMgrs.get(c.Account__c);
if(null==idMgrs){
idMgrs=new set<Id>();
mapAccMgrs.put(c.Account__c,idMgrs);
 }
idMgrs.add(c.Account_Manager__c);
 }
 }
 Map<id,List<AccountTeamMember>>mapStdAccTeam=new
 Map<id,List<AccountTeamMember>>();
 List<AccountTeamMember>listStdAccTeam=“select id,UserId,AccountId from
AccountTeamMember where AccountIdin:setAccids”;
if(listStdAccTeam!=null &&listStdAccTeam.size()>0){
for(AccountTeamMemberrecAccTeam :listStdAccTeam)
 {
 List<AccountTeamMember>
listStdAccTeamMap=mapStdAccTeam.get(recAccTeam.AccountId);
if(null==listStdAccTeamMap){
listStdAccTeamMap=new List<AccountTeamMember>();
mapStdAccTeam.put(recAccTeam.AccountId,listStdAccTeamMap);
 }
listStdAccTeamMap.add(recAccTeam);
}
 }
for(Customer__c c:Trigger.old)
 {
 List<AccountTeamMember>
listAccTeam=mapStdAccTeam.get(c.Account__c);
 Set<Id>idMgrs=mapAccMgrs.get(c.Account__c);
if(listAccTeam!=null &&listAccTeam.size()>0 )
 {
if(idMgrs!=null &&idMgrs.size()>0 &&
!(idMgrs.Contains(trigger.oldmap.get(c.Id).Account_Manager__c)))
 {
for(AccountTeamMemberrecATM:listAccTeam)
 {
if(recATM.UserId==trigger.oldmap.get(c.Id).Account_Manager__c)
setDelATM.add(recATM.Id);
 }
 }
else if(idMgrs==null)
 {
for(AccountTeamMemberrecATM:listAccTeam)
setDelATM.add(recATM.Id);
 }
 }
 }
 List<AccountTeamMember>listDelATM=“select id from AccountTeamMember
whereidin:setDelATM”;
if(listDelATM!=null &&listDelATM.size()>0 )
deletelistDelATM;
 }
 }
Trigger Scenario 20:-
When we create the Opportunity with the Probability=20, then the opportunity owner will be automatically added to Account Team of the associated account for that Opportunity.
Code:
triggerUpdateATMwithOwneronOptyCreate on Opportunity (after insert,after update) {
 List<AccountShare>list_share= new List<AccountShare>();
 List<AccountTeamMember>list_atm=new List<AccountTeamMember>();
for(Opportunity opp:Trigger.New)
 {
if(opp.Probability==20)
 {
AccountTeamMemberatm=new AccountTeamMember();
atm.accountid=opp.accountid;
atm.teamMemberRole='Account Manager';
atm.UserId=opp.Ownerid;
AccountShare share = new AccountShare();
share.AccountId=opp.Accountid;
share.UserOrGroupId = opp.OwnerId;
share.AccountAccessLevel='Read/Write';
share.OpportunityAccessLevel = 'Read Only';
share.CaseAccessLevel='Read Only';
list_atm.add(atm);
list_share.add(share);
 }
 }
if(list_atm!=null)
insertlist_atm;
if(list_share!=null &&list_share.size()>0)
 List<Database.saveresult>sr=Database.insert(list_share,false);



========================================================================


Trigger Scenario 1:
Write a trigger to update a field(let it be city) in all related opportunities, when same field(city) is update in account.

trigger City_Opportunity on Account (after update) {
    list<opportunity> oppor = new list<opportunity>();
    for(opportunity opp: [select stagename, closedate, city__c from opportunity]){
    for(account a : trigger.old){
        if(a.city__c == 'Hyderabad'){
              opp.city__c = 'Mumbai';
                oppor.add(opp);
            }
        }
  }update oppor;
}

Trigger Scenario 2 : 
Apex trigger to update account rating when the opportunity stage equals closed won

trigger Opportunitystageclosedwon_updatesaccountrating on Opportunity (before insert) {
    list<account> accounts =  new list<account>();
    for(account acc : [select name, rating from account]){
    for(opportunity opp : trigger.new){
        if(opp.stagename == 'closed won'){
            acc.Rating = 'hot';
            accounts.add(acc);
        }
    }
  }update accounts;
}

Trigger Scenario 3 : 
Prevent an account from deleting with trigger, if it has 2 or more contacts.

trigger errordelete on Account (before delete) {
    set<id> acctid = new set<id>();
    for(account a : trigger.old){
        acctid.add(a.id);
    }
    map<id,account> accounts = new map<id,account>([select id, name, (select lastname, firstname from contacts) from account where id in : acctid]);
    for(account acc : trigger.old){
        if(accounts.get(acc.Id).contacts.size()>=2){
            acc.adderror('account records cannot be deleted');
        } 
    }
}

Trigger Scenario 4 :
When ever new account is created with annual revenue more than five lakhs then add wilson as account team member.

trigger accountteammemberexample on Account (after insert) {
    list<accountteammember> actteams = new list<accountteammember>();
    user u = [select id from user where alias='swethag'];
    for(account acc : trigger.new){
        if(acc.annualrevenue >500000){
            accountteammember actteam = new accountteammember();
            actteam.UserId = u.id;
            actteam.AccountId = acc.Id;
            actteam.TeamMemberRole = 'Account Manager';
            actteams.add(actteam); 
        }
    }insert actteams;
}

Trigger Scenario 5 : 
When ever the Account is created with Industry as Banking then create a contact for account, Contact Lastname as Account name and contact phone as account phone.

trigger accountafterhandler on Account (before insert) {
    list<contact> contacts = new list<contact>();
    for(account acc : trigger.new){
        if(acc.Industry == 'Banking'){
            contact con = new contact();
            con.LastName = acc.name;
            con.Phone = acc.Phone;
            con.AccountId = acc.Id;
            contacts.add(con);
        }
    }insert contacts;
}

Trigger Scenario 6 : 
When ever a case is created with origin as email then set status as new and Priority as Normal

trigger caseorigin on Case (before insert) {
    for(case c : trigger.new){
        if(c.origin == 'Email'){
            c.status = 'New';
            c.priority = 'Medium';
        }
    }
}

Trigger Scenario 7 : 
When ever lead is created with leadSource as Web then give rating as cold otherwise hot
trigger leadexample on Lead (before insert) {
    for(lead ld : trigger.new){
        if(ld.leadsource == 'web'){
            ld.Rating = 'cold';
        }
        else{
            ld.Rating = 'hot';
        }
    }
}

Trigger Scenario 8 : 
whenever a account phone is modified/updated then contact records with phone fields(otherphone with oldvalue and homephone with newvalue) associated with this account record gets updated as same as account phone field.
trigger accountupdatedexample on Account (before update) {
    map<id,account> accold=trigger.oldmap;
    map<id,account> accnew=trigger.newmap;
    set<id> keys=accold.keySet();
    list<id> myid=new list<id>();
    for(ID K : keys){
        account oldvalues = accold.get(K);
        account newvalues = accnew.get(K);
      if(oldvalues.phone!=newvalues.phone){
        myid.add(K);
      }
   }
    for(contact con : [select lastname, phone from contact where accountid in : myid]){
        account a = accold.get(con.accountid);
        account b = accnew.get(con.accountid);
        con.otherphone = a.phone;
        con.homephone = b.phone;
    }
}

Trigger Scenario 9 : 
When ever opportunity stagename is modifed to closed won then set closedate as today and type as new Customer.
trigger opporupdate on Opportunity (before update){
    Map<Id,Opportunity> oppold=Trigger.oldMap;
    Map<Id,Opportunity> oppnew=Trigger.newMap;
    Set<Id> keys =oppold.keySet();
    for(Id rid :keys){
        Opportunity oldopt=oppold.get(rid);
        Opportunity newOpt=oppnew.get(rid);
        if(oldopt.stagename!='Closed won' && newOpt.stagename=='Closed won'){
            newOpt.closeDate=System.today();
            newOpt.type='New Customer';
        }
    }
}

Trigger Scenario 10 : 
when a new opportunity is created with amount more than 50 lakhs add the wilson as opportunityteamMember.
trigger optamountteammember on Opportunity (before insert) {
      list<OpportunityTeamMember> teams = new list<OpportunityTeamMember>();
    user u = [select id from user where alias='schar'];
    for(opportunity opt : trigger.new){
        if(opt.amount > 5000000){
            OpportunityTeamMember atm = new OpportunityTeamMember();
            atm.OpportunityId = opt.id;
            atm.UserId = u.id;
            atm.TeamMemberRole = 'Opportunity Manager';
            atm.OpportunityAccessLevel = 'All';
            teams.add(atm);
        }
    }insert teams;
}

Trigger Scenario 11 : 
whenever the stagename is modified to closedwon then set the closedate as today
apex class:
public class optytriggerhandler {
    public void udpate(map<id,opportunity> oldmap, map<id,opportunity> newmap){
        for(id keys : oldmap.keySet()){
            opportunity oppold = oldmap.get(keys);
            opportunity oppnew = newmap.get(keys);
            if(oppold.Stagename!= 'closed won' && oppnew.Stagename == 'closed won'){
                oppnew.CloseDate = system.today();
            }
        }
    }
}
trigger class:
trigger OpportunityUpdate on Opportunity (before update) {
      optytriggerhandler.udpate(trigger.oldmap, trigger.newmap);
}

Trigger Scenario 12 : 
when a new lead is created with leadsource as web then make the other user as the owner of the record.
trigger leadownerassignment on Lead (before insert) {
    for(lead ld : trigger.new){
        if(ld.leadsource == 'web'){
            user u = [select id from user where alias = 'swethag'];
            ld.ownerid = u.id;
        }
    }
}

Trigger Scenario 13 : 
when a new contact is created for a existing account then set contact otherphone as account phone.
trigger contactaccountrelation on Contact (before insert) {

       list<account> acc = [select id, name from account];
    for(account a : acc){
    for(contact con : [select lastname, accountid from contact where accountid =: a.id]){
        con.OtherPhone = a.Phone;
    }
    }
}

Trigger Scenario 14 : 
Create “Top X Designation” custom object which is the related list to Opportunity (Look up Relationship). In the Top X Designation object, create the fields Type (Picklist), Document Attached (Checkbox) Create one field Handoff Attached with pick list type with values are Yes, No on Opportunity Object. Logic :- If Type (Top X Designation) = “Contract Flow Down/Handoff”, and “Document Attached” = True then “Handoff Attached” = True, otherwise false.
trigger updateHandoffattachedupdateHandoffattached on Top_X_Designation__c (after insert, after update, after delete) {
    map<id,Top_X_Designation__c> maptop = new map<id,Top_X_Designation__c>();
    set<id> oppid = new set<id>();
     map<id,Top_X_Designation__c> maptopfalse = new map<id,Top_X_Designation__c>();
    set<id> oppidfalse = new set<id>();
    list<opportunity> opplist = new list<opportunity>();
    list<opportunity> opptoupdate = new list<opportunity>();
    opportunity  opp = new opportunity();
    if(trigger.isafter){
        if(trigger.isinsert || trigger.isupdate){
            for(Top_X_Designation__c top : trigger.new){
                if(top.Document_Attached__c == true && ((top.Type__c=='Contract Flow Down') || (top.Type__c=='Handoff'))){
                   maptop.put(top.OppLookUp__c, top);
                    oppid.add(top.OppLookUp__c);
                }else{
                    maptopfalse.put(top.OppLookUp__c, top);
                    oppidfalse.add(top.OppLookUp__c);
                }
            }
            opplist = [select stagename, handoff_attached__c from opportunity where ID in : oppid and ID in : oppidfalse];
            for(opportunity opp : opplist){
                if(maptop.containsKey(opp.Id)){
                    opp.Handoff_Attached__c = 'yes';
                    opptoupdate.add(opp);
                }
                if(maptopfalse.containsKey(opp.id)){
                 opp.Handoff_Attached__c ='no';
                    opptoupdate.add(opp);
                }
            }
            if(opptoupdate.size()>0){
                update opptoupdate;
            }
            }
    }
}

Trigger Scenario 15 : 
The following Trigger will fires when we try to create the account with same name i.e. Preventing the users to create Duplicate Accounts
trigger AccountDuplicateTrigger on Account (before insert, before update) {
    map<string, account> accountmap = new map<string, account>();

    for(account acc : trigger.new){
     
        if((acc.name!=null) && (trigger.isinsert || (acc.name!= trigger.oldmap.get(acc.id).name))){
            if(accountmap.containsKey(acc.Name)){
                acc.name.adderror('account name already exists');
            }else {
                accountmap.put(acc.Name, acc);
            }
        }
    }
    for(account account : [select id, name from account where name IN : accountmap.keyset()]){
        account accountnewmap = accountmap.get(account.name);
        accountnewmap.Name.adderror('account with this name already exixts');
    }
}

Trigger Scenario 16 : 
Trigger to count the total number of contact records associated 
with that Account
trigger Accountcountcontacts on Contact (after insert, after update, after delete, after undelete) {
    set<id> acctids = new set<id>();

    list<contact> contacts = trigger.isdelete ? trigger.old : trigger.new;
    for(contact con : contacts){
        if(con.accountid != null){
          acctids.add(con.accountid);
        }
    }
    list<account> listaccounts = new list<account>();
 for(aggregateresult ar : [select accountid accid, count(id) contactcount from contact where accountid in : acctids group by accountid]){
                                  account a = new account();
                                  a.id = (id)ar.get('accid');
                                  a.Number_of_Contacts__c = (decimal)ar.get('contactcount');
                                  listaccounts.add(a);
                              }
    update listaccounts;
}

Trigger Scenario 17:- 
Create the object called “Customer” and create the Master-Detail Relationship on Customer object so that Customer will be the related list to Account record. Create the field called “Account Manager” on Customer object which is lookup to the user object. Now Logic is when we create Customer record for account record, then the user in Account Manager field will be automatically added to Account Team of that associated account.
trigger InsertAccountTeam on Customer__c (after insert) {
    list<accountteammember> atmlist = new list<accountteammember>();
    accountteammember atm = new accountteammember();
    list<accountshare> newshare = new list<accountshare>();
    if(trigger.isinsert){
    for(Customer__c c : trigger.new){
        if(c.Account_Manager__c!= null){
        atm = new accountteammember();
        atm.accountid = c.CustomerAccount__c;
        atm.teammemberrole = 'Account Manager';
        atm.userid = c.Account_Manager__c;
        AccountShare shares = new AccountShare();
        shares.AccountId = c.CustomerAccount__c;
        shares.AccountAccessLevel = 'Read/Write';
        shares.UserOrGroupId = c.Account_Manager__c;
        shares.OpportunityAccessLevel = 'Read Only';
        shares.CaseAccessLevel='Read Only';
        newshare.add(shares);
        atmlist.add(atm);
        }
        }
        if(atmlist!=null)
            insert atmlist;
        if(newshare!=null && newshare.size()>0)
            list<database.SaveResult> sr = database.insert(newshare,false);
    }
}

Trigger Scenario 18 : 
1. Set the OWD on the opportunity as private 2. Remove modify all permission on wilson's profile 3. whenever the opportunity stagename is modified to closed won and amount is more than 10 lacs share the record with wilson
Apex Class:

public class afterupdateopptrigg {
    public static void afterupdate(map<id,opportunity> oldmap, map<id,opportunity> newmap){
        list<opportunityshare> share = new list<opportunityshare>();
        user u = [select id from user where alias = 'swethag'];
        for(id key : oldmap.keyset()){
            opportunity oldopt = oldmap.get(key);
            opportunity newopt = newmap.get(key);
            if(oldopt.stagename!='closed won' && newopt.StageName == 'closed won'){
                if(newopt.Amount > 1000000){
                    opportunityshare os = new opportunityshare();
                    os.OpportunityId = key;
                    os.UserOrGroupId = u.id;
                    os.OpportunityAccessLevel = 'read';
                    os.RowCause = 'manual';
                    share.add(os); 
                }
            }
        }insert share;
    }
}

Trigger Class:
trigger afterupdateopptrigg on Opportunity (after update) {
    afterupdateopptrigg.afterupdate(trigger.old, trigger.new);
}

Trigger Scenario 19 : 
When a new Account record is inserted verify the industry field value, if industry field value is Education then assign the owner as karthic
Trigger :

trigger accountowner on Account (before insert) {
 User u=[select id from User where username='developer@batch0267.com'];
    for(Account a:Trigger.New){
        if(a.Industry=='Education'){
            a.ownerId=u.id;
        }
    }
}

TestClass :

@isTest
private class AccountOwnerTest {
 @isTest
    static void testme(){
        User u=[select id from User where username='developer@batch0267.com'];
        Integer count=[select count() from Account];
        Account a=new Account(Name='Test',Industry='Education');
        try{
            insert a;
        }catch(Exception e){
            System.debug(e);
        }
        Integer size=[select count() from Account];
        System.assertEquals(size,count+1);
        Account acc=[select id ,ownerId from Account where id=:a.id];
        System.assertEquals(acc.ownerId,u.id);
    }
}

Trigger Scenario 20 : 
When ever we are trying to delete the account record which has 
a contacts for it .,Then deletion has to fail
Trigger :
trigger accountDelete on Account (before Delete) {
 List<Account> accsList=[select id,name,(select id from Contacts) from Account where id in:Trigger.Old];
    for(Account a:accsList){
        if(a.contacts.size()>0)
            a.addError('We cannot delete this account');
    }
}

TestClass :
@isTest
private class accountDeleteTest {
 @isTest
    static void testMe(){
        Account a1=new Account(Name='Test');
        insert a1;
        Contact c1=new Contact(LastName='test',accountId=a1.id);
        insert c1;
        Account a2=new Account(name='Demo');
        insert a2;
        Integer myCount=[select count() from Account];
        try{
            delete a1;
        }catch(Exception e){
            System.debug(e);
        }
        Integer count=[select count() from Account];
        System.assertEquals(count,mycount);
        try{
            delete a2;
        }catch(Exception e){
            System.debug(e);
        }
        Integer size=[select count() from Account];
        System.assertEquals(size,mycount-1);
    }
}

Trigger Scenario 21 : 
When ever account record is deleted successfully send the email 
confirmation alert to the Account email addresss
Trigger :

trigger accountDeleteEmail on Account (after Delete) {
 List<Messaging.Email> emails=new List<Messaging.Email>();
    for(Account a:Trigger.Old){
        Messaging.SingleEmailMessage email1=new Messaging.SingleEmailMessage();
        email1.setToAddresses(new String[]{a.email__c});
        email1.setSubject('Account  Deleted');
        String body='<h1> Dear Cusomer<h1><p >Your Account with Accoutn Id:'+a.id;
        body=body+' is successfully deleted </p><br/><p> Thanks <br/>SalesTeam</p>';
        email1.setHtmlBody(body);
        emails.add(email1);
    }
    Messaging.sendEmail(emails);
}

Trigger Scenario 22 : 
1.Create two objects creditcard and Application . 2.Create lookup field on Application choosing Creditcard as parent 3.When we delete any creditcard record all corresponding application records also be deleted
trigger creditcardDeletion on CreditCard__c (before delete) {
 List<Id> cards=new List<Id>();
    for(CreditCard__c c:Trigger.Old){
        if(c.card_Type__c=='Platinum'){
            cards.add(c.id);
        }
    }
    List<Application__c> apps=[select id from Application__c where CreditCard__c in:cards];
     delete apps;
}