Browsing "Older Posts"

Browsing Category "Salesforce Triggers Real time scenarios"
  • Trigger Scenario: Whenever New Account Record is created then needs to create associated Contact Record automatically

    salesforcepoint Saturday, 18 March 2017

    Object : Account
    Trigger: After Insert

    Description : When ever new Account record is successfully created  then
         create the corresponding  contact record for the account 
    with 
    account name as contact lastname 
    account phone as contact phone

    Trigger Code:

    trigger accountAfter on Account (after insert) {
        List<Contact> cons=new List<Contact>();
        for(Account a: Trigger.New){
            Contact c=new Contact();
            c.accountid=a.id;
            c.lastname=a.name;
            c.phone=a.phone;
            cons.add(c);
        }
        insert cons;

    }


    Test Class  :

    @isTest
    private class AccountAfter {
    @isTest
        static void testme(){
            Integer count=[select count() from Account];
            Integer size=[select count() from Contact];
            Account a=new Account(Name='Testing',phone='111');
            try{
                insert a;
            }catch(Exception e){
                System.debug(e);
            }
            Integer newCount=[select count() from Account];
            Integer newsize=[select count() from Contact];
            Contact c=[select lastname,phone from Contact where accountid=:a.id];
            System.assertEquals(c.lastname,a.name);
            System.assertEquals(c.phone,a.phone);
        }
    }
  • Create trigger to assign lead owners based on web domain

    salesforcepoint Sunday, 26 February 2017
    Object   : Lead
    Evernt : before Insert
    Requirement : When ever new Lead is created with lead source as Web  then assign Venkatesh as owner

    Trigger :
    trigger OwnerAssign on Lead (before insert) {
    User u=[select id from user where username='Venkatesh@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='Ram';
            my.company='Salesforce';
            my.AnnualRevenue=8000;
            my.LeadSource='Web';
            insert my;
            User u=[select id from User where username='venkatesh@dev.com'];
            Lead l=[select ownerId from Lead where id=:my.Id];
            if(my.leadSource=='Web'){
            System.assertEquals(l.ownerId,u.Id);
            }
        }
    }