Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 84

string 

age;
if(age==' '){
system.debug('hellooooooooooo');
}
string  age;
if(age==null){
system.debug('hai::::::::::::::::');
}    
salesforce apex null check

whenever new student registered update the count in


respective trainer record
what to do? action? update trainer record --> i., 
when to do? event--> after insert-->student
student sobject
trainer sobject
create count (number type of field) in trainer object
in student object create lookup r/s type of field to link
with trainer.

trigger abcd on student__C(after insert){


list<string> trainerids = new list<string>();
for(student__C x:trigger.new)
{trainerids.add(x.lookupfield__c);}
list<trainer__C> myt=[select id,name,count__c from
trainer__c where id IN :trainerids];
list<trainer__C> dummy = new list<trainer__C>();
for(trainer__C k:myt){
k.count__C++;
dummy.add(k);}
update dummy;
update myt; //what happens if i write?  }

whenever student registered send email to respective


trainer
whenever trainer mobile number modified then send
email to respective students
whenever student changed his trainer  then decrease
count to previous trainer and increase count to new
trainer
if the student record deleted then decrease count in
trainer

custom-rollup summary
========================================
========================================
=========
1. When ever new Account is inserted  with Industry
as 'Banking ' then set the phone 
   as '888'
========================================
========================================
=========
Trigger:

trigger phoneUpdate on Account (before insert) {


    for(Account a: Trigger.New){
        if(a.industry=='Banking'){
            a.phone='888';
        }

    }
}

@istest 
public class edokati{
testmethod static void kkk(){
account obj = new account();
obj.name='gggg';
obj.industry='banking';
insert obj;
}
}
Test Class :

@isTest
private class PhoneTest {
    testmethod static void testme(){
        Account acc=new Account();
        acc.Name='capital';
        acc.Industry='Banking';
        try{
         insert acc;
        }catch(Exception e){
            
        }
        Account a=[select id,phone from Account where
id=:acc.Id];
        System.assertEquals(a.phone,'888');
    }
}

========================================
========================================
========
2. When ever new lead is created , calculate the
leadscore using before inserting

Field Name NOT NULL NULL


Email 10 0

Phone 10 0

Industry 20 0

Note : First Create a custom field LeadScore on


Lead object

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

Trigger :

trigger leadscoreTrig on Lead (before insert) {


    for(Lead ld: Trigger.New){
       Integer count=0;
        if(ld.email!=''&& ld.email!=null){
            count=count+10;
        }
        if(ld.phone!='' && ld.phone!=null ){
            count=count+10;
        }
        if(ld.industry!='' && ld.industry!=null){
            count=count+20;
        }
        ld.leadScore__c=count;
    }
}

Test Class :

@isTest
private class LeadScoreTest {
@isTest
    static void testme(){
        Lead ld=new Lead();
        ld.lastname='satish';
        ld.company='Capital';
        ld.phone='111';
        ld.email='javasfdc@gmail.com';
        ld.industry='Banking';
        try{
         insert ld;
        }catch(Exception e){
            
        }
Lead newLead=[select LeadScore__c from
Lead where id=:ld.id];

System.assertEquals(newLead.LeadScore__c,40);     
   
    }
}
========================================
========================================
========
3.Create a Queue on Lead object as Banking Queue 
with users ( satish) :

  Create a Queue on Lead object as Energy Queue


with Users

  Scenario: When a new Lead is inserted based on


the industry field value assign it 
    corresponding queue 

Industry-Banking--assing owner of the record


as Banking queue

Industry-Energy---Assign owner of the record


as Energy Queue

Industry other than Banking and Energy user


who ever has created the 
        record he should be the owner 
========================================
========================================
========

========================================
========================================
=======
4.When ever new Account is created with 
AnnualReneue  more than 50 Lacs and Industry 
  as Energy  then create a new opportunity for this
account with 

OpportunityName as AccountName

StageName as Prospecting

CloseDate as Today+30 days 


========================================
========================================
======
trigger AccountInsert on Account (after insert) {
List<Opportunity> optyList=new
List<Opportunity>();
    for(Account a: Trigger.New){
        if(a.industry=='Energy' && a.AnnualRevenue
>5000000){
            Opportunity op=new Opportunity();
            op.name=a.name;
            op.stageName='Prospecting';
            op.CloseDate=System.today()+20;
            op.accountId=a.id;
            optyList.add(op);
        }
    }
    insert optyList;
}
TestClass :

@isTest
private class AccountInsertTest {
@isTest
    static void testme(){
        Account a1=new Account();
        a1.name='Test';
        a1.Industry='Energy';
        a1.AnnualRevenue=9000000;
        try{
            insert a1;
        }catch(Exception e){
            
        }
        Integer count=[select count() from Opportunity];
        if(a1.Industry=='Energy' &&
a1.AnnualRevenue>5000000)
         System.assertEquals(count,1);
        else
          System.assertEquals(count,0);
    }
}

========================================
========================================
=======
5. When ever new Account record is created with
Industry as "Education ' and 
   annualRevenue as 10 Lacs then add  user karthic
as AccountTeamMember 

AccountTeamMember : 

 1.AccountId : Id of the record on which we are


creating teammember

 2.UserId   : Id of the user whom we are adding as


Teammember

 3.TeamMemberRole : choose some value pickList


field of TeamMemberRole

 4.AccountAccessLevel :  Type of Access you are


providing on Account for the team
  member

  Posible values are 'Read' ,'Edit','ALL'

 5. OpportunityAccessLevel:

 6. CaseAccessLevel   :

 7. COntactAccessLevel   :

Note : Before we implement this trigger enable the


AccountTeams
setup
  |----Build
|----Customize
  |------Accounts
    |------AccountTeams
1. Enable AccountTeam

2. Add the AccountTeams as related list on all the


pageLayouts

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

Trigger: 
trigger AccountTeamTrig on Account (after insert) {
List<AccountTeamMember> teams=new
List<AccountTeamMember>();
    User u=[select id from User where alias='knair'];
    for(Account a:Trigger.New){
        if(a.Industry=='Education' && a.AnnualRevenue
>1000000){
            AccountTeamMember atm=new
AccountTeamMember();
            atm.accountId=a.id;
            atm.userId=u.id;
            atm.TeamMemberRole='Account Manager';
            atm.AccountAccessLevel='Edit';
            teams.add(atm);
        }
    }
    insert teams;
}

TestClass :

@isTest
private class AccountTeamTest {
@isTest
    static void testme(){
        User u=[select id from User where alias='knair'];
        Account a=new Account();
        a.Industry='Education';
        a.name='capital';
        a.AnnualRevenue=1300000;
        try{
            insert a;
        }catch(Exception e){
            System.debug(e);
        }
        AccountTeamMember atm=[select
userId,AccountId,AccountAccessLevel from
AccountTeamMember where AccountId=:a.id];
        if(a.Industry=='Education' &&
a.AnnualRevenue>1000000){
            System.assertEquals(atm.userId,u.id);
            System.assertEquals(atm.AccountAccessLev
el,'Edit');
            System.assertEquals(atm.TeamMemberRole,'
Account Manager');
        }else{
            System.assertEquals(atm,null);
        }
    }
}

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

6. When ever new opportuntiy is created  with


StageName as 'closed Won ' then

  add karthic as OpportunityTeamMember

OpportunityTeamMember :

OpportunityId : 

UserId :

OpportunityAccessLevel  :

TeamMemberRole :
Note : Before we implement this enable
opportunityTeams

setup
  |----Build
|----Customize
  |------Opportunitys
    |------OpportunityTeams
1. Enable OpportuntiyTeam

2. Add the opportunitytTeams as related list on all


the pageLayouts

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

Trigger: 
trigger opptyTeamTrig on Opportunity (after insert) {
List<OpportunityTeamMember> teams=new
List<OpportunityTeamMember>();
    User u=[select id from User where alias='knair'];
    for(Opportunity op:Trigger.New){
        if(op.stageName=='closed Won'){
            OpportunityTeamMember otm=new
OpportunityTeamMember();
            otm.OpportunityId=op.id;
            otm.UserId=u.id;
            otm.TeamMemberRole='Account Manager';
            otm.OpportunityAccessLevel='Edit';
            teams.add(otm);
        }
    }
     insert teams;
}

TestClass :

@isTest
private class OpportunityTeamTrig {
@isTest
    static void testme(){
        User u=[select id from User where alias='knair'];
        Opportunity a=new Opportunity();
        a.name='Test';
        a.stageName='closed won';
        a.closeDate=System.today()+5;
        try{
            insert a;
        }catch(Exception e){
            System.debug(e);
        }
        OpportunityTeamMember atm=[select
userId,OpportunityId,OpportunityAccessLevel from
OpportunityTeamMember where OpportunityId=:a.id];
        if(a.stageName=='closed won' ){
            System.assertEquals(atm.userId,u.id);
            System.assertEquals(atm.OpportunityAccess
Level,'Edit');
            System.assertEquals(atm.TeamMemberRole,'
Account Manager');
        }else{
            System.assertEquals(atm,null);
        }
    }
}

========================================
========================================
=======
7. When ever new Account record is created  with
Account Type as 'prospect ' then

   create a new contact for this account with following


data 

Contact lastname as Account Name 

COntact Phone as Account Phone 


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

Trigger:

trigger example on Account( after insert ){

List<Contact> contacts=new List<Contact>();


for(Account a: Trigger.New){

if(a.type=='Prospect'){
Contact c=new Contact();
c.lastname=a.name;
c.phone=a.phone;
c.accountId=a.id;
contacts.add(c);
}
}
insert contacts;
}
Test Class :

@isTest

private class AccountTest{


@isTest
static void testme(){

Account a=new Account();


a.name='Test';
a.Type='Prospect';

try{

insert a;
}catch(Exception e){

}
Integer count=[select count() from
Contact];
if(a.Type=='Prospect'){

System.assertEquals(count,1);

}else{
System.assertEquals(count,0);

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

Sharing rules on the sobject are stored in thier


corresponding share objects 

Ex: 

Account ----AccountShare

Contact-----ContactShare
Opportunity---OpportuntiyShare

Customer__c-----Customer_Share 

Transaction _ _ c------Transaction_share

Q::When do you share a record ?

When OWD on a object is Private /Public Read and


user doesnt have read and write access
on a record 

Q:: When we want to share a record using apex  what


field are needed 

1. Which record     : OpportunityId

2. With whom     : UserOrGroupId

3. What type of access :OpportunityAccessLevel  

4. Reason for sharing  :RowCause

8. When ever a new Opportunity is created with


stageName 'closed won' share the record 
   with user karthic
========================================
========================================
========
  trigger opptyShareTrig on Opportunity (after insert) {
   List<OpportunityShare> share=new
List<OpportunityShare>();
     User u=[select id from User where alias='knair'];
     for(Opportunity op:Trigger.New){
         if(op.stageName=='Closed Won'){
             OpportunityShare os=new
OpportunityShare();
             os.OpportunityId=op.id;
             os.UserOrGroupId=u.id;
             os.OpportunityAccessLevel='Edit';
             os.RowCause='Manual';
             share.add(os);
         }
     }
    insert share;
  }

Test Class :

@isTest
private class OpptyShareTest {
@isTest
    static void testme(){
        Opportunity op=new Opportunity();
        op.stageName='closed won';
        op.closeDate=system.today();
        op.name='Test';
        try{
            insert op;
        }catch(Exception e){
            
        }
        user u=[select id from user where alias='knair'];
        OpportunityShare share=[select
OpportunityAccessLevel,OpportunityId,RowCause,Us
erOrGroupId FROM OpportunityShare where
OpportunityId=:op.id and UserOrGroupId=:u.id];
        if(op.stageName=='Closed Won'){
            System.assertEquals(share.OpportunityAcces
sLevel,'Edit');
            System.assertEquals(share.RowCause,'Manu
al');
        }else{
            System.assertEquals(share,null);
        }
    }
}

========================================
========================================
======
9. when ever new Case  is created with Priority as
'High' and origin as 'Email'  
   then share the record with karthic  with edit
permission 
========================================
========================================
======

Trigger:

trigger CaseShareTrig on Case (after insert) {


   List<CaseShare> share=new List<CaseShare>();
    User u=[select id from User where alias='knair'];
    for(Case c:Trigger.new){
        if(c.origin=='Email' && c.priority=='High'){
            CaseShare cs=new CaseShare();
            cs.caseId=c.id;
            cs.UserOrGroupId=u.id;
            cs.caseAccesslevel='Edit';
            cs.RowCause='Manual';
            share.add(cs);
        }
    }
    insert share;
}

Test Class :

@isTest
private class CaseShareTest {
@isTest
    static void testme(){
        Case c=new Case();
        c.status='New';
        c.Origin='Email';
        c.Priority='High';
        c.subject='Test';
        try{
            insert c;
        }catch(Exception e){
            
        }
        User u=[select id from User where alias='knair'];
        CaseShare cs=[select
CaseId,UserOrGroupId,CaseAccessLevel ,RowCaus
e from CaseShare where CaseId=:c.id and
userOrGroupId=:u.id]; 
        if(c.origin=='Email' && c.Priority=='High'){
          System.assertEquals(cs.CaseAccessLevel,'Edi
t');
          System.assertEquals(cs.RowCause,'Manual');
        }else{
            System.assertEquals(cs,null);
        }
    }
}

========================================
========================================
=======
10. Customer__c  : Customer_share 

    Loan__c : Loan_Share 
    Candidate__c : Candidate_share

Fields : 

ParentId : id of the record which we want to


share 

UserOrGroupId :  Id of the user / group with


whom the record need to shared

AccessLevel : Type of Access we want to


provide for the user

RowCause: Reason for sharing 

Note :RowCause=Schema.CustomObject_Share.Ro
wCause.Reason

Ex: Schema.Customer_Share.RowCause.Manual

Ex: Schema.Candidate_Share.RowCause.Owner

Example : 

Object :Customer__c 
Fields : Status : Approved
  Rejected

Name :  Text

Owd: Private 

10 .When ever new customer is created with status


Approved then share the record with
    user  kavya with read Access 
========================================
========================================
=========
    trigger CustomerShare on Customer__c ( after
insert ){

List<Customer_share> share=new
List<Customer_Share>();
User u=[select id from user where
username='kavya@capital.com'];

for(Customer__c c:Trigger.New){
if(c.status__c='Accepted'){

Customer_Share cs=new
Customer_Share();
cs.parentId=c.id;
cs.userOrGroupId=u.id;
cs.Accesslevel='Read';
cs.RowCause=Schema.Customer_Share.RowCause.
Manual;
share.add(cs);

}
}
insert share;

    }

========================================
========================================
========
11.When ever the phone no of the account is
modified  then set  corresponding contacts
homephone as new Phone no of Acctount 

otherPhone as Old Phone no of Account

========================================
========================================
========
class: AccountTriggerHandler :

public class AccountTriggerHandler {


    public static void beforeUpdate(Map<Id,Account>
oldMap,Map<Id,Account> newMap){
        List<Id> accIds=new List<Id>();
       
        for(Id key:oldMap.keySet()){
            Account old=oldMap.get(key);
            Account newAcc=newMap.get(key);
            if(old.phone!=newAcc.Phone){
                accIds.add(key);
            }
        }
        List<Contact> cons=[select
id,accountId,homephone,otherphone from Contact
where accountId in:accIds];
        for(Contact c:cons){
            Account a=newMap.get(c.accountId);
            Account b=oldMap.get(c.accountId);
            c.otherPhone=b.phone;
            c.homephone=a.phone;  
        }
        update cons;
    }
}

Trigger :

TestClass :

trigger AccountPhoneupdate on Account (before


update) {
AccountTriggerHandler.beforeUpdate(Trigger.oldMap
,Trigger.newMap);
}

@isTest
private class AccountPhoneTest {
    testmethod static void testme(){
        String oldPhone='111';
        Account a1=new Account();
        a1.name='Test';
        a1.phone=oldPhone;
        insert a1;
        Contact c1=new Contact();
        c1.accountId=a1.id;
        c1.lastname='myla';
        insert c1;
        String newPhone='3445';
        try{
            a1.phone=newPhone;
            update a1;
        }catch(Exception e){
            
        }
        Contact c2=[select id,otherphone,Homephone
from Contact where id=:c1.id];
        if(oldPhone!=newPhone){
            System.assertEquals(c2.homePhone,newPho
ne);
            System.assertEquals(c2.otherphone,oldphon
e);
        }else{
            System.assertEquals(c2.homephone,c1.home
phone);
            System.assertEquals(c2.otherphone,c1.other
Phone);
        }
        
    }
}

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

12. Create  a Following Custom Fields on Account


Object :

Field Name DataType


--------------------------------
Total_Amount Currency
PipeLine_Amount Currency
Won_Amount Currency

Lost_Amount Currency
Scenario 1: When a new Opportunity record is
created for an account  rollup the opportunity amount
to Corresponding Account 

1. If new Opportunity Stage is Close Won  then


add the amount to Account 's

Total_Amount=Total_Amount+Opportunity
Amount 

Won_Amount=Won_Amoutn+Opportuntiy
amount

2. If new Opportunity stage is closed Lost then


add the amount to  Accounts

Total_Amount=Total_Amount+Opportunity
Amount 

Lost_Amount=Lost_Amoutn+Opportuntiy
amount

3. If new Opportunity stage is not closed Lost or


closed won then add 
              the amount to  Accounts

Total_Amount=Total_Amount+Opportunity
Amount 
PipeLine_Amount=PipeLine_Amount+Opportuntiy
amount

Scenario 2: When a existing  opportunity stage is


modified to closed won or closed lost

  then  

1. If stageName is modified to Closed won

Remove the amount from PipleLine_Amount


and add it to WOn_Amount 

2. If StageName is modified to Closed Lost

Remove the amount from PipleLine_Amount


and add it Lost_Amount
========================================
========================================
========

Class :

public class OpptyTriggerHandler {

    public static void afterInsert(List<Opportunity>


optyList){
        Map<Id,List<Opportunity>> accMap=new
Map<Id,List<Opportunity>>(); // key
accountId value 
        for(Opportunity op:OptyList){

            if(accMap.containsKey(op.accountId)){

                List<Opportunity>
optList=accMap.get(op.accountId);
                optList.add(op);
                accMap.put(op.accountId,optList);

            }else{

                List<Opportunity> ops=new
List<Opportunity>{op}; 
                accMap.put(op.accountId,ops);

            } 
        }
       List<Account> accounts=[select
id,Total_Amount__c,Won_Amount__c,Lost_Amount_
_c,
PipeLine_Amount__c from Account where
Id in:accMap.keyset()];
       for(Account a: accounts){
        List<Opportunity>
oppList=accMap.get(a.id);

         for(Opportunity p:oppList){


        

a.Total_Amount__c=a.Total_Amount__c+p.amount;
         if(p.stageName=='Closed Won'){

             

a.Won_Amount__c=a.Won_Amount__c+p.amount;

         }else{

         if(p.stageName=='Closed Lost'){

        

a.Lost_Amount__c=a.Lost_Amount__c+p.amount;

         }else{

        

a.pipeLine_Amount__c=a.pipeLine_Amount__c+p.a
mount;

         } 
         }
      }
     }
            
        update accounts;
        
    }
    public Static void
afterUpdate(Map<Id,Opportunity>
oldMap,Map<Id,Opportunity>   newMap){
      List<Opportunity> optyChanged=new
List<Opportunity>();
        Map<Id,List<Opportunity>> accMap=new
Map<Id,List<Opportunity>>();
        for(Id key: oldMap.keyset()){
            Opportunity old=oldMap.get(key);
            Opportunity newOpp=newMap.get(key);
            if(old.stageName!=newOpp.stageName ){
                if((old.stageName!='Closed Won' &&
old.stageName!='closed Lost')&&                
(newOpp.StageName=='closed won' ||
newOpp.stageName=='Closed Lost')){
                    if(accMap.containsKey(newOpp.accountI
d)){
                        List<Opportunity>
myList=accMap.get(newopp.accountId);
                        myList.add(newOpp);
                        accMap.put(newopp.accountId,myList)
;
                    }else{
                        List<Opportunity> newList=new
List<Opportunity>();
                        newList.add(newOpp);
                        accMap.put(newOpp.accountId,newLi
st);
                    }
                }            
           }
        }
       List<Account> accounts=[select
id,Total_Amount__c,Won_Amount__c,Lost_Amount_
_c,
        PipeLine_Amount__c from Account where Id
in:accMap.keyset()];
       for(Account a: accounts){
        List<Opportunity>
oppList=accMap.get(a.id);
         for(Opportunity p:oppList){
         if(p.stageName=='Closed Won'){
             

a.Won_Amount__c=a.Won_Amount__c+p.amount;
                    a.pipeLine_Amount__c=a.pipeLine_Amo
unt__c-p.amount;
         }else{
         if(p.stageName=='Closed Lost'){
        

a.Lost_Amount__c=a.Lost_Amount__c+p.amount;
                        a.pipeline_Amount__c=a.pipeLine_A
mount__c-p.amount;
         }
         }
      }
     }
        
      update accounts;  
    }
}

Trigger :
---------
trigger OptyRollUp on Opportunity (after insert,after
update) {
    if(Trigger.isAfter && Trigger.isInsert){
OpptyTriggerHandler.afterInsert(Trigger.new);
    }
    if(Trigger.isAfter && Trigger.isUpdate){
      OpptyTriggerHandler.afterUpdate(Trigger.oldMap
,Trigger.NewMap);  
    }
}

========================================
========================================
========
13 .When ever the phone field in the contact is
updated then Update the corresponding 
   Account records phone no as Contacts new Phone
no
========================================
========================================
========
trigger contactPhone on Conact(before update){
List<Contact> contacts=new List<Contact>();

for(Id key: Trigger.oldMap.keyset()){

Contact old=Trigger.oldMap.get(key);
Contact newCon=Trigger.newMap.get(key);
if(old.phone!=newCon.phone){
contacts.add(newCon);
}

List<Account> accs=new List<Account>();


for(Contact c:contacts){
Account a=new Account();
a.id=c.accountId;
a.phone=c.phone;
accs.add(a);
}

update accs;
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------
Scenario 14:
Object   : Lead
Evernt : before Insert
Requirement : When ever new Lead is created with
lead source as Web  then assign wilson as owner
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--------------------
Triggers :
trigger OwnerAssign on Lead (before insert) {
User u=[select id from user where
username='wilson@dev.com'];
    for(Lead my:Trigger.new){
         if(my.leadsource=='Web'){
             my.ownerId=u.Id;
         }
     }
}

Test Class :
@isTest
private class OwnerAssignTest {
@isTest
    static void testme(){
         Lead my=new Lead();
         my.LastName='Kiran';
         my.company='Capital';
         my.AnnualRevenue=8000;
         my.LeadSource='Web';
         insert my;
         User u=[select id from User where
username='wilson@dev.com'];
         Lead l=[select ownerId from Lead
where id=:my.Id];
         if(my.leadSource=='Web'){
        
System.assertEquals(l.ownerId,u.Id);
         }
     }
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------
Scenario 15:
Object : Account
Event : before insert
Requirement : When ever new Account is created
with  Industry as 'banking' and Account Type as
'prospect'
  then assign the wilson as the owner of the
record
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------

trigger AccountInsert on Account (before insert) {


User u=[select id from User where
username='wilson@dev.com'];
    for(Account a:Trigger.New){
        if(a.industry=='Banking' && a.Type=='Prospect'){
            a.ownerId=u.id;
        }
    }
}

@isTest
private class AccountInsertTest {
@isTest
    static void testme(){
        Account acc=new Account();
        acc.Name='Testing';
        acc.Industry='Banking';
        acc.Type='Prospect';
        insert acc;
        User u=[select id from User where 
username='wilson@dev.com'];
        Account a=[select id,ownerId from Account
where id=:acc.id];
        if(acc.Industry=='Banking' &&
acc.Type=='Prospect')
            System.assertEquals(a.ownerId,u.id);
    }
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----
Scenario 16:
Object : Lead
Event : before Insert
Requirement : When ever new lead is created
calcualte the lead score
Field Name Entered Blank
FirstName :  10
AnnualRevenue :  20 0
Phone :  10 0
First Create : Custom Field 
Lead Score : Number(4)
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------
trigger LeadQualityTrig on Lead (before insert) {
    for(Lead my:Trigger.new){
        Integer count=0;
        if(my.firstName!=''&&my.firstName!=null)
            count=count+10;
        if(my.AnnualRevenue!=null)
            count=count+20;
        if(my.phone!='' &&my.phone!=null)
            count=count+10;
        my.LeadScore__c=count;
    }
}

@isTest
private class LeadQualityTest {
    testmethod static void testme(){
        Lead my=new Lead();
        my.lastname='Test1';
        my.firstName='Kiran';
        my.annualRevenue=9000;
        my.phone='123';
        insert my;
        Lead testlead=[select id ,LeadScore__c from
Lead where id=:my.Id];
        if(my.firstName!=null&&my.FirstName!=''
&&my.AnnualRevenue!=null && my.Phone!
=''&&my.phone!=null){
            System.assertEquals(testlead.leadScore__c,4
0);
        }
    }
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
---
Scenario : 17
Object : Opportunity
Event : After Insert
Requirement : When ever new opportunity is created
with opportuntiy Stage as closed won share the
record with
      user wilson
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-------------------
trigger OptyShare on Opportunity (after insert) {
    User u=[select id from user where
username='students@batch0275.com'];
   List<OpportunityShare> share=new
List<OpportunityShare>();
    for(Opportunity p:Trigger.New){
        if(p.stageName=='closed won'){
            OpportunityShare os=new
OpportunityShare();
            os.opportunityId=p.id;
            os.OpportunityAccessLevel='Read';
            os.UserorGroupId=u.id;
            os.rowCause='Manual';
            share.add(os);
        }
    }
    insert share;
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------
Scenario 18:
Object : Account
Event : After Insert
Requirement : When ever new account is creatd
with Industry as Energy and AnnualRevenue  more
than 20 lac
add wilson as Team memner on the Account
AccountTeamMember : 
AccountId
UserId
AccountAccessLevel
TeamMemberRole
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------
Apex Class :

public class AccountTeamHandler {


    public static void afterInsert(List<Account> accs){
        List<AccountTeamMember> teams=new
List<AccountTeamMember>();
        User u=[select id from User where
username='students@batch0275.com'];
        for(Account a: accs){
            if(a.industry=='Banking' &&
a.AnnualRevenue>2000000){
                AccountTeamMember atm=new
AccountTeamMember();
                atm.AccountId=a.id;
                atm.userId=u.id;
                atm.AccountAccessLevel='Read';
                atm.TeamMemberRole='Account Manager';
                teams.add(atm);
            }
        }
        insert teams;
    }
}

Trigger:
trigger AccountTeamTrigger on Account (after  insert)
{
AccountTeamHandler.afterInsert(Trigger.new);
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------
Scenario 19:
Object :Contact
Event : Before Update
Requirement : When ever the contacts phone
numner is ,modified ,Contact old phone number
should ne 
saved as Contacts other phone
-----------------------------------------------------------------------
-----------------------------------------------------------------------
------------------
Apex Class :
public class ContactTriggerHandler {
    public static void beforeUpdate(Map<Id,Contact>
oldMap,Map<Id,Contact> newMap){
        List<Id> modified=new List<Id>();
        for(Id key:oldMap.keySet()){
            Contact old=oldMap.get(key);
            Contact newRec=newMap.get(key);
            if(old.phone!=newRec.Phone){
                newRec.otherPhone=old.phone;
             
            }
        }
    }
}

Trigger :
trigger ContactUpdaterigger on Contact (before
update) {
ContactTriggerHandler.beforeUpdate(Trigger.oldMap
,Trigger.newMap);
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
---------------------
Scenario 20:
Create  Custom Object  :Course
Fields       : Status  : PicKList(Active,InActive)

Create Custom Object : Student


Fields : Course :Lookup(course)

Object :Course
Event : After Update
Requirement : When  the status of the course is
changed to InActive then Delete all the child records
or course.

public class CourseHandler{


public static void
afterUpdate(Map<Id,Course__c>
oldMap,Map<Id,Course__c> newMap){
List<Id> courseIds=new List<Id>();
for(Id key :oldMap.keySet()){
Course__C old=oldMap.get(key);
Course__c newCourse=newMap.get(key);
if(old.Status__c!='InActive' &&
newCourse.Status__c='InActive'){
courseId.add(key);
}
}
List<Students__c> stds=[select id from
Student__C where Course__c IN :courseIs];
delete stds;
}
}

trigger courseHandler on Course__c ( after update){


CourseHandler.afterUpdate(Trigger.oldMap,Trigger.n
ewMap);
}

==================1. Before Insert Trigger:

  Object :Account 

  Operation :Before Insert

 Scenario : When ever new account record is created


assign the owner of the 
    record 
  1. If Industry =Banking and  AnnualRevenue >
50 lac
then assign to satish otherwise assign to
karthic

trigger ownerRules on Account (before insert) {


    User kar=[select id from User where
username='developer@batch0265.com'];
    User sa=[select id from User Where
Username='batch0265@capital.com'];
    for(Account a: Trigger.New){
        if(a.industry=='Banking' &&
a.annualRevenue>5000000){
            a.ownerId=sa.id;
        }else{
            a.ownerId=kar.Id;
        }
    }
}

Test Class :
@isTest
private class OwerExample {
@isTest
    static void testme(){
        User kar=[select id from User where
username='developer@batch0265.com'];
     User sa=[select id from User Where
Username='batch0265@capital.com'];
        Account a1=new
Account(Name='Test1',Industry='Energy',AnnualReve
nue=30000);
        Account a2=new
Account(Name='Test2',Industry='Banking',AnnualRev
enue=6000000);
        try{
            insert a1;
         insert a2;
        }catch(Exception e){
            System.debug(e);
        }
        Account acc1=[select id ,ownerId from Account
where id=:a1.Id];
        System.assertEquals(acc1.ownerId,kar.id);
        Account acc2=[select id,ownerId from Account
where id=:a2.Id];
        System.assertEquals(acc2.ownerId,sa.id);
    }
}

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

Object :Opportunity 

Scenario :
When a new  opportunity is created with stageName
as 'Closed Won' then this 
 record should be shard with user karthic with read
access ;

trigger shareExample1 on Opportunity (after insert) {


User u=[select id from User where
username='developer@batch0265.com'];
    List<OpportunityShare> share=new
List<OpportunityShare>();
    for(Opportunity op:Trigger.new){
        if(op.stageName=='Closed Won'){
            OpportunityShare os=new
OpportunityShare();
            os.opportunityid=op.id;
            os.UserorGroupId=u.id;
            os.OpportunityAccessLevel='Read';
            os.RowCause='Manual';
            share.add(os);
        }
    }
insert share;
}

========================================
=================================
Object : Account :
Scenario : When ever Account phone no is modified
udpate the corresponding 
  contats otherphone with modified Account's
phone no

trigger phoneUpdate on Account (before update) {

Map<Id,Account> oldMap=Trigger.OldMap;

        Map<Id,Account> newMap=Trigger.NewMap;

    List<Id> accIds=new List<Id>();


    for(Id aid:oldMap.keySet()){

        if(oldMap.get(aid).Phone!
=newMap.get(aid).Phone){
            accIds.add(aid);
        }
    }
    List<Contact> cons=new List<Contact>();

    List<Account> accs=[select id,phone,(select


OtherPhone from Contacts) from Account where Id IN
:accIds];

    for(Account a:accs){
        for(Contact c:a.contacts){
            c.otherphone=newMap.get(a.id).phone;
            cons.add(c);
        }
    }
    update cons;
}

----------------
@isTest
private class PhoneTest {
    testmethod static void testme(){
        Account a1=new
Account(name='aaa',phone='111');
        insert a1;
        Contact c1=new
Contact(lastname='test',accountId=a1.id);
        insert c1;
        try{
            a1.phone='555';
            update a1;
        }catch(Exception e){
            System.debug(e);
        }
        Contact con=[select id ,otherphone from Contact
where accountId=:a1.id];
        System.assertEquals(con.otherPhone,a1.phone)
;
    }
}
========================================
====================================
Object : Account 

Scenario :
When ever account  industry field is  modified to
Banking then add 
karthic as accountTeam member

trigger accountTeamUpdate on Account (after


update) {
List<AccountTeamMember> team=new
List<AccountTeamMember>();
    User u=[select id from user where
username='developer@batch0265.com'];
    for(Account a:Trigger.new){
        if(a.industry=='Banking'){
            AccountTeamMember atm=new
AccountTeamMember();
            atm.accountId=a.id;
            atm.userId=u.id;
            atm.teamMemberRole='Account Manager';
            //atm.AccountAccessLevel='Read';
            team.add(atm); 
        }
    }
    insert team;
}
======================
Trigger Class : Date 21-02-2016 
========================================
========================================
=========================
Scenario  :1
========================================
========================================
=========================
1. Object :Opportunity 

  a. When Existing Opportunity with statge name as


'Closed Won' is 
     updated to any other stage it has throw error
message 

  b. When existing Opportunity record stageName is


changed to 
     closed won then  recalculate the Amount_Won for
the  Correspondng Account  (Which is a sum of all
closed                                                                           
opportunities)

  c. When ever the stage name is changed to Closed


and won 
     share that opportunity record with user 'karthic'

   public class ClosedOptHandler {


     public static void
beforeUpdate(Map<Id,Opportunity>
oldMap,Map<Id,Opportunity> newMap){
         Set<Id> accountIds=new Set<Id>();
         for(Id a:oldMap.keySet()){
         Opportunity newOpt=newMap.get(a);
         Opportunity oldOpt=oldMap.get(a);
            if(oldOpt.stageName=='Closed Won' &&
newOpt.stageName!='Closed Won'){
                newOpt.addError('Stage Name cannot be
updated');
            }
        }
    }
    public static void
afterUpdate(Map<Id,Opportunity>oldMap,Map<Id,Op
portunity> newMap){
        Set<Id> accountIds=new Set<Id>();
        for(Id a:oldMap.keySet()){
         Opportunity newOpt=newMap.get(a);
         Opportunity oldOpt=oldMap.get(a);
            if(newOpt.StageName=='Closed Won'){
                accountIds.add(newOpt.accountId);
            }
     }
     if(accountIds.size()>0){
         List<Account> accs=[select
Amount_Won__c ,(select Amount from
Opportunities where                                           
StageName='Closed Won') from Account where Id
in:accountIds ];
     Decimal sum=0;
         for(Account a:accs){
             for(Opportunity p:a.opportunities){
                 sum=sum+p.amount;
             }
             a.Amount_Won__c=sum;
         }
         update accs;
     }
    }
    public static void oppShare(List<Opportunity>
newOpt){
        User u=[select id from User where alias='kart'];
List<OpportunityShare> share=new
List<Opportunityshare>();
     for(Opportunity op: newOpt){
         if(op.stageName=='Closed Won'){
         OpportunityShare ops=new
OpportunityShare();
         ops.opportunityId=op.id;
         ops.OpportunityAccessLevel='Edit';
         ops.UserOrGroupId=u.id;
         ops.RowCause='Manual';
         share.add(ops);
         }
     }
     insert share;
    }
}

----------------------------------------------------------

Trigger :

trigger closedOppty on Opportunity (after


insert,before update,after update) {
    if(Trigger.isAfter && Trigger.isInsert){
        ClosedOptHandler.oppShare(Trigger.new);
    }
    if(Trigger.isBefore && Trigger.isUpdate){
        ClosedOptHandler.beforeUpdate(Trigger.oldMa
p, Trigger.newMap);
    }
    if(Trigger.isAfter && Trigger.isUpdate){
        ClosedOptHandler.afterUpdate(Trigger.oldMap,
Trigger.newMap);
        ClosedOptHandler.oppShare(Trigger.new);
    }
}

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

Scenario 2:
========================================
========================================
========================
Object 1: Opportunity : 
Create a Custm Fields : Field Name  
DataType
---------------------------------------
 
Total_Opportunities__c : 
Number

Total_Opportunity_Amount__c :
Currency
 

a .When  ever a new Opportunity is creatd 


recalculate the  total opportunites and Total
Opportunity
  amount for the corresponding Account

b. When a new Opportunity is created with out


entering the account value throw error

trigger opptScope on Opportunity (before insert,


after insert) {

if(Trigger.isBefore && Trigger.isInsert){

for(Opportunity opp=Trigger.new){
if(opp.accountId==null){
opp.addError('Opportuity Can not
created with out AccountId');
}
}
          }
  if(Trigger.isAfter && Trigger.isInsert){
     Set<Id> accId=new Set<Id>();
     for(Opportunity op:Trigger.New){
         accId.add(op.accountId);
     }
  List<Account> accounts=[select
Total_Opportunities__c,Total_Opportunity_Amount__
c,
               (select id,Amount from
Opportunities) from Account where Id in:accId];
     for(Account a:accounts){
        
a.Total_Opportunities__c=a.opportunities.size();
        Decimal sum=0;
         for(Opportunity p:a.opportunities){
             sum=sum+p.amount;
         }
         a.Total_Opportunity_Amount__c=sum;
     }
     update accounts;
 }
}
========================================
========================================
==========================
Scenario 3:
========================================
========================================
===========================

Object : Contact 
Custom Fields : Field Name DataType
----------------------------------------------
Source PickList: Sfdc
  SAPExternal

Account : 
Custom Fields : Field Name DataType
----------------------------------------------
Source PickList: Sfdc
  SAPExternal

a. When we are trying to delete any contact


record whoes source is SAP External it should throw
error

b. When we trying to delete a contact whose


account  source is SAP External it has to throw error 
trigger conDeletes on Contact (before delete) {
     //List<Contact> cons=[select
Source__c ,Account.Source__c from Contact where
Id in:Trigger.Old];
     for(Contact c:Trigger.old){
         if(c.Source__c=='SAP External' ||
c.Account.Source__c=='SAP External'){
             c.addError('You can not delete
Conatct');
         }
     }   
}

========================================
========================================
=====================
Scenario 4: 
========================================
========================================
=====================

Object : Opportunity : 
1. When ever a new Opportunity is created with
Amount more than 10 lakhs  and source as 'Web'
Then add  karthic as OpportunityTeamMember

Solution :

 trigger optyTeam on Opportunity (after insert) {


    User u=[select id from User where alias='kart'];
List<OpportunityTeamMember> teams=new
List<OpportunityTeamMember>();
    for(Opportunity op:Trigger.New){
        if(op.amount> 1000000 &&
op.LeadSource=='Web'){
            OpportunityTeamMember ot=new
OpportunityTeamMember();
            ot.OpportunityId=op.id;
            ot.OpportunityAccessLevel='Edit';
            ot.userId=u.id;
            ot.TeamMemberRole='Sales Manager';
            teams.add(ot);
        }
    }
    insert teams;
}
========================================
========================================
===============================
Scenario  5:
========================================
========================================
===========================
Object : Opportunity

1. When ever the opportunity stage is changed


create dummy record in the PipeLine object with 
following fieldMaping
PipleLine__c p=new PipeLine_C

p.Stage=Opportunity_OldStage---
Opportunity_NewStage

p.Days =Today()-
opportunity_LastmOdifiedDate

p.Name=opportunityName

Solution :

trigger optyStageChange on Opportunity (after


update) {
List<PipeLine__c> optList=new
List<PipeLine__c>();  
     for(Id opId:Trigger.OldMap.keySet()){
         Opportunity
oldOpt=Trigger.OldMap.get(opId);
         Opportunity
newOpt=Trigger.newMap.get(opId);
         if(oldOpt.stageName!
=newOpt.StageName){
            PipeLine__c p=new PipeLine__c();
            p.Name=newOpt.Name;
           

p.Stage__c=oldOpt.StageName+'-'+newOpt.StageNa
me;
            Date
modDate=oldOpt.LastModifiedDate.date();
            Integer
days=System.Today().daysBetween(modDate);
            p.Days__C=days;
            p.ConvertedDate__c=System.today();
             optlist.add(p);
         }
     }
     insert optlist;
}

========================================
========================================
=============================
Scenario :6
========================================
========================================
============================
Object : Application__c 

FieldName DataType Options


------------------------------------------------------
First Name Text -
Type PickList New Card
Cancel Card

Applicant PickList Business

Salaried

Status PicKList Pending


Approved
Rejected

Executive Lookup(user)

Email Email -

Object : BlackList 

Field Name DataType


------------------------------------
Name Text

Object : Customer 
Field Name DataType Options
-----------------------------------------------------
First Name Text
Applicatant PickList Business 
Salaried

Workflow : When a new Applciation is creatd  with 

Type =new Card 


Status=Pending 

Action : Task : Assing to the Owner 

Approval : When a ever a application  is submitted for


Approval

Entry Criteria : Type =New Card 

Automated Approved : Submited Executives


Manager

Approval steps : All Applications should enter


step 1 

Approval Action : Field Update Status=


Approved
Rejected Action : Field Update Status
='Rejected'

 1.  When a new Application is submited for Approvel


with  Application type as 'New Card'

a. check wheather Applicant name in black list


object 
b. If name is in the black list object Then update
the status to Rejected

2. When applicant name is not in the black list submit


the record for approval using trigger
and set the status as pending 

3. When ever the application Status is changed to


Approved 

a. Create a new Customer record based on


application details 

Customer FirstName =Application Firstname


Customer Type =Application -
ApplicantType

4.When ever the application status is rejected 


a. send a email to Executive ,Executive
manager, Applicant  and user with role : Verification

=========================
------------------------------------------------------------------
Scenario :1
1. When ever a we are inserting a new Account
record  before the
   record is inserted check the industry value

  a. if industry is 'Banking' set annualRevenue as


100000;

  b. If industry is 'Energy' set annualRevenue as


50000 
------------------------------------------------------------------
Trigger:

trigger example1 on Account (before insert) {


    for(Account a: Trigger.New){
        if(a.industry=='Banking'){
            a.AnnualRevenue=100000;
}else{
if(a.industry == 'Energy'){
             a.AnnualRevenue=50000;
}
    }
}
-------------
Test Class :
-------------
@isTest
private class Example1 {
    @isTest
    static void testme(){
        Account a1=new
Account(name='aaa',Industry='Banking');
        Account a2=new
Account(name='bbb',Industry='Energy');
        try{
            insert a1;
            insert a2;
        }catch(Exception e){
            System.debug(e);
        }
        Account acc1=[select id,annualRevenue from
Account where id=:a1.id];
        System.assertEquals(acc1.AnnualRevenue,100
000);
        Account acc2=[select id ,annualRevenue from
Account where id=:a2.id];
        System.assertEquals(acc2.AnnualRevenue,500
00);
    }
}
------------------------------------------------------------------
Scenario 2: 
 1. When a  new contact is created with lead source
web
 2. AccountId field can not be blank or null
----------------------------------------------------------------
Trigger :

trigger example2 on Contact (before insert) {

    for(Contact c:Trigger.New){

        if(c.leadsource=='Web' && 

(c.accountId==''||c.accountId==null)){

     c.addError('Web contact cannot be created with


out account');

        }
    }
}

TestClass:
----------
@isTest
private class Example2 {
    @isTest
    static void testme(){
        Contact c1=new
Contact(lastname='satish',leadSource='web');
        Contact c2=new Contact(lastname='Myla');
        List<Contact> cons=new List<Contact>{c1,c2};
        Integer count=[select count() from Contact];
        try{
           Database.insert(cons,false);
        }catch(Exception e){
            System.debug(e);
        }
        Integer size=[select count() from contact ];
        System.assertEquals(count+1,size);
    }
}
-----------------------------------------------------------------------
------
Scenario 3:
1. When a new opportunity is created with  following
details 
1.leadsourc is Web

2.amount > 50000

3. stagename!=closed won
 2. Reassign the owner to user karthic

-----------------------------------------------------------------------
-----
trigger example3 on Opportunity (after insert) {
    User u=[select id from user where alias='kart'];
    List<Opportunity> ops=[select
leadsource,Amount,StageName from Opportunity
where id in:Trigger.new];
    for(Opportunity p:ops){
        if(p.stageName!='Closed won' && p.amount
>50000 && p.leadsource=='Web'){
            p.ownerId=u.id;
        }
    }
    update ops;
    
}

TestClass :
------------
@isTest
private class ExampleTest3 {
@isTest
    static void testme(){
        Opportunity op=new Opportunity();
        op.name='Test';
        op.amount=10000;
        op.closeDate=System.today()+3;
        op.stageName='Qualification';
        op.leadSource='Web';
        try{
            insert op;
        }catch(Exception e){
            System.debug(e);
        }
        User u=[select id from user where alias='kart'];
        Opportunity p=[select ownerid from Opportunity
where id=:op.id];
        System.assertEquals(p.ownerId,u.id);
    }
}
-----------------------------------------------------------------------
-------
Scenario 4: 

1. Calculate the Lead quality score 

1. FirstName : 10 points 

2. Phone  :10 points 

3. Email  : 10 points 

 if the lead score is 20 then create a new contact


based on lead details
assign the owner of the lead as owner of new contact
-----------------------------------------------------------------------
----
Trigger :
trigger example5 on Lead (after insert) {
Integer total;
    List<Contact> contacts=new List<Contact>();
    for(Lead l:Trigger.New){
total=0;
        if(l.firstName!=null && l.firstname!='')
            total=total+10;
        if(l.phone!=null && l.phone!='')
            total=total+10;
        if(l.email!=null && l.email!='')
            total=total+10;
        if(total>=20){
            Contact c=new Contact();
            c.lastname=l.lastname;
            c.firstName=l.firstName;
            c.phone=l.phone;
            c.Email=l.email;
            c.ownerId=l.ownerId;
            contacts.add(c);
        }
    }
    insert contacts;
}

-----------------------------------------------------------------------
----
1. Deletion of account record should fail it has any
contact records

trigger example6 on Account (before delete) {


    List<Account> accs=[select id,(Select id from
Contacts) from Account where Id In:Trigger.Old];
    for(Account a:accs){
        if(a.contacts.size() > 0){
            a.addError('Account Record with contact can
not be deleted');
        }
    }
}
-----------------------------------------------------------------------
------
1. Create a Custom Field No_Of_Contats on Account
Object 

2. When ever new Contact is created  or deleted


update the 
 no_of_contacts fields with no of contacts that exits
for the parent records
-----------------------------------------------------------------------
-----
Trigger
--------

trigger contactsTriggers on Contact (after insert,after


delete) {
    if(Trigger.isInsert && Trigger.isAfter)
        TriggerContact.increment(Trigger.New);
    else
        TriggerContact.increment(Trigger.Old);

public class TriggerContact {


    public static void increment(List<Contact> cons){
        set<Id> accid=new Set<id>();
        for(Contact c:cons){
           accId.add(c.AccountId); 
        }
       List<Account> accs=[select
id,No_of_contacts__c ,(select id from Contacts ) from
Account where id in:accId];
        for(Account a:accs){
            a.no_of_contacts__c=a.contacts.size();
        }
        update accs;
    }

}
-----------------------------------------------------------------------
------

You might also like