Wednesday, July 5, 2017

TRigger scenario 7 in salesforce :

Duplicate Name:
trigger duplicateAccName on Account (before insert,before update) {               /* for(account acc :trigger.new){         if(trigger.newmap.get(acc.id).name == trigger.oldmap.get(acc.id).name){             acc.name.adderror('You cannot create a dulplicate account......');                     }     }         */     list<string> accnames = new list<string>();     for(account acc : trigger.new){         accnames.add(acc.name);     }     list<account> acclst = [select id,name from account where name IN: accnames];     for(account acc1 : trigger.new){         if(acclst.size()>0){                 acc1.name.adderror('You cannot create a dulplicate account');          
   }         } }
-----------------------------------------------------------------
trigger triggername on Account (before update,before insert) {

    Map<string,Account> accMap = new Map<string,Account>();
    set<string> accSet = new set<string>();
    for(Account acc : Trigger.new){
        accSet.add(acc.name);
    }
    for(Account a : [select id,name from Account where name in : accSet]){
        accMap.put(a.name,a);
    }
    for(Account acc1 : trigger.new)
        {
         if(accMap.containskey(acc1.name)){
           if(Trigger.isInsert){
             acc1.name.addError('Account name Already Exist For Insert!');
           }
           else if(Trigger.isUpdate){
             acc1.name.addError('Account name Already Exist For Update!!'); 
           }
            }
        }
    
    /* for(account a : trigger.new){
      //  a.accountnumber = a.site;
        if(trigger.oldmap.get(a.id).name == trigger.newmap.get(a.id).name){
            a.name.adderror('Duplicate name');
        }
        
    }  */

}
------------------------------------------------------------------
Scenario:Create 'sales rep' text field in 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.
trigger AcctoconTrigger on Account (before insert ,before update) {
    map<id,account> mapusr = new map<id,account>();
    if(trigger.isbefore && (trigger.isupdate || trigger.isinsert)){
        for(account acc : trigger.new){
            mapusr.put(acc.OwnerId,acc);
        }
        map<id,user> mapusr1 = new map<id,user>([select id,name from user where id IN:mapusr.keyset()]);
        for(account acc : trigger.new){
            acc.sales_rep__c = mapusr1.get(acc.OwnerId).name;
        }
    }
}

No comments:

Post a Comment