Wednesday, 14 November 2018

Basic Pagination with Custom Controller



VF Code:

<apex:page controller="PaginationWithCustomControllerClass">
    <apex:form >
        <apex:pageBlock title="Pagination with Custom Controller
" id="pgBlock">
            <apex:pageBlockTable value="{!Accounts}" var="acc" id="pgTable">
                <apex:column value="{!acc.Name}"/>
                <apex:column value="{!acc.Industry}"/>
                <apex:column value="{!acc.Rating}"/>
                <apex:column value="{!acc.Phone}"/>
            </apex:pageBlockTable>
            <br/>
            <b><apex:outputText value="Total Number of Records are {!totalrecords}"/> </b>
       
            <apex:pageBlockButtons >
                <apex:commandButton value="Previous" action="{!Previous}" rerender="pgBlock"
                                    status="status" disabled="{!DisablePrevious}" />
                <apex:commandButton value="Next" action="{!Next}" reRender="pgBlock"
                                    status="status" disabled="{!DisableNext}" />
                <apex:actionStatus id="status" startText="Loading..."/>
             

            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>

</apex:page>




Controller Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public with sharing class PaginationWithCustomControllerClass{

    private Integer CountTotalRecords;
    private Integer OffsetSize = 0;
    private Integer QueryLimit = 10;
    public list <Account> lstAccount{get;set;}
    
    public PaginationWithCustomControllerClass(){
        CountTotalRecords= [select count() from Account];
    }
      
    public list <Account> getAccounts(){
        lstAccount = new list  <Account> ();
        lstAccount = [Select id, Name, Industry, Rating, Phone from Account order by Name limit :QueryLimit offset :OffsetSize];
        return lstAccount; 
    }
    
    public PageReference Next() {
        OffsetSize += QueryLimit;
        return null;
    }
    
    public PageReference Previous() {
        OffsetSize -= QueryLimit;
        return null;
    }
  
    public Boolean getDisablePrevious(){
        if(OffsetSize>0){
            return false;
        }else {
            return true;
        }
    }
    
    public Boolean getDisableNext() {
        if (OffsetSize + QueryLimit < countTotalRecords){
            return false;
        }else {
            return true;
        }
     }
    
    public integer gettotalrecords(){
        return [select count() from Account];
    }
}

Create Given Number of Child records On Parent Creation


Let's say In Account there is a custom field called NumberofContacts__c(Number Data Type). While we are creating an Account, if we give the NumberofContacts__c as '5' then this trigger will be automatically creates 5 contact records.

NOTE: We can give the number up to 10,000 since the Governer Limits fire the following error.

System.LimitException: Too many DML rows: 10001

.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
trigger CreateGivenNoOfContacts on Account (After Insert) {
    Map<Id,Decimal>AccLocMap =New Map<Id,Decimal>();
    List<Contact>ConInsert = New List<Contact> ();
    for(Account acc : trigger.new){
        AccLocMap.put(acc.Id,acc.NumberofContacts__c);
    }
    
    for(Account acc : trigger.new){

        for(integer i=0; i<AccLocMap.get(acc.id); i++){
            contact con = New Contact();
            con.LastName = acc.Name + ' Contact';
            con.AccountId = acc.Id;
            ConInsert.add(con);
        }
    }
    
    Insert ConInsert;
        
}

Trigger to Delete Child On Deletion of Parent


This trigger is to Delete the Child Records on Delete of Parent Record
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
trigger DeleteContact on Account (After Delete) {
    Set<Id>AccIdSet = New Set<Id>();
    List<Contact> ConDelList = New List<Contact>();
    
    for(Account acc : trigger.old){
        AccIdSet.add(acc.id);
    }
    
    for(contact con : [Select Id, AccountId from Contact WHERE AccountId In : AccIdSet]){
        ConDelList.add(con);
    }
    
    Delete ConDelList;
}

Sunday, 11 November 2018

Trigger to Create Child on insert of Parent


This trigger to create Contact(Child) automatically on insertion of Account(Parent)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
trigger CreateContact on Account (after insert) {
    
    List<contact> ConList = New List<Contact>();
    
    for(Account Acc : Trigger.New){
        Contact con = New Contact();
        con.LastName = Acc.Name + ' Contact';
        con.AccountId = Acc.Id;
        ConList.add(con);
    }
    
    if(ConList.Size()>0 && !(ConList.isEmpty()))
        insert ConList;
}

Trigger to update child field with parent field


This trigger is to update the Child field with Parent field. In the below example, we will be updating the Contact's LastName with Account's Name.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
trigger UpdateChildWithParent on Contact (Before insert, before update) {
 
    Set<id> AccId = New Set<id>();
    Map<Id,Account> AccountMap = New Map<Id,Account>();

    
    For(contact contact : trigger.new){
        AccId.add(contact.AccountId);
    }
    
    for(Account acc : [Select Id,Name from Account WHERE ID IN : AccId]){
        AccountMap.put(acc.Id,Acc);
    }

    For(contact contact : trigger.new){
        if(AccountMap.containsKey(Contact.AccountId)){
            contact.LastName = AccountMap.get(contact.AccountId).Name;
        }
    }

}

Thursday, 1 November 2018

How To Fetch Anniversary Records for a Selected Record

Hello..!!

Today We will be Discussing about writing SOQL to fetch Anniversary records.

Scenario:

I have an opportunity with some CloseDate (9/3/2015).
Now by writing SOQL, I need to fetch the records of last five years opportunity record where the CloseDate as Same as the selected Opportunity Record (i.e., 9/3)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Date fromDate = [Select Id, CloseDate from Opportunity WHERE ID = '0066F00000v4dB2'].CloseDate;



integer startYear = fromDate.addYears(-5).year();

integer thisMonth = fromDate.month();

integer thisDay = fromDate.day();

system.debug('*****'+startYear);

system.debug('---'+[Select Id, CloseDate from Opportunity WHERE 

                    CALENDAR_MONTH(CloseDate)=:thisMonth  AND 

                    CALENDAR_YEAR(CloseDate)>=:startYear AND 

                    DAY_IN_MONTH(CloseDate) =: thisDay]);


 This query will return the Following results

Sunday, 16 September 2018

Trigger for All Rollup Summary calculations on Lookup Relation- Count, Minimum, Maximum, Sum and Average

This trigger will help you to update all the Rollup Summary calculations on Look up RelationShip.

Objects and Fields Information :
Contact (Object) --> Amount__c(Custom Field)
Account (Object) --> Sum__c (Custom Field)
                            --> Avg__c (Custom Field)
                           --> Min__c (Custom Field)
                           --> Max__c (Custom Field)
                           --> Count__c (Custom Field)

Here we are updating all the Account fields based on Contact's Amount__c Field data


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
trigger FullRollup on Contact (after insert, after update, after delete, after undelete){
   
    set<Id>Parent_set = new set<id>();
    List<Account>AccUpdateList = New List<Account>();
   
    if(trigger.isdelete || trigger.isupdate){
        for(Contact con : Trigger.old){
            Parent_set.add(con.AccountId);
        }
    }
   
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
        for(Contact con : Trigger.New){
            Parent_set.add(con.AccountId);
        }
    }
   
   
    for(AggregateResult aggcon : [Select AccountId,
                                      Count(Id)countt, Sum(amount__c)summ, avg(amount__c)avgg, min(amount__c)minn, max(amount__c)maxx
                                      From contact Where AccountId IN :Parent_set Group By AccountId]){
        Account Acc = New Account();
        Acc.Id     = (Id)aggcon.get('AccountId');
        Acc.Sum__c = (Decimal)aggcon.get('summ');
        Acc.Avg__c = (Decimal)aggcon.get('avgg');
        Acc.Min__c = (Decimal)aggcon.get('minn');
        Acc.Max__c = (Decimal)aggcon.get('maxx');
        Acc.Count__c = (Decimal)aggcon.get('countt');  
       
        AccUpdateList.add(Acc);    
       
    }
    Update AccUpdateList;
   
}

Friday, 14 September 2018

Sample Rest Class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@RestResource(URLMapping = '/Interaction__c/*')

global with Sharing class MyFirstRestClass{

    @httpGet
    global static interaction__c getInteraction(){
    
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        string interactionId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        interaction__c result = [Select id, name, status__c from interaction__c WHERE ID =:interactionId];
        return result;        
    }
//    /services/data/v34.0/sobjects/interaction__c
    
    @HttpPost
    global static string createInteraction(string Name, String status){
       
        interaction__c inter = new interaction__c();
        inter.Name = Name;
        inter.status__c = status;
        insert inter;
        return inter.name;
    }
    
    @HttpPut
    global static interaction__c upsertInteraction(){
        RestRequest request = RestContext.request;
        string interId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        interaction__c interact = [Select Id, Name, Status__c from interaction__c WHERE ID =:interId];
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());

        for(String fieldName : params.keySet()) {
            interact .put(fieldName, params.get(fieldName));
        }
        upsert interact ;
        return interact;
    
    }
    
    @HttpPatch
    global static string updateInteraction(){
        
        RestRequest request = RestContext.request;
        string interId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        interaction__c thisInteraction = [Select Id, Name, Status__c from interaction__c WHERE ID =:interId];
        
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());

        for(String fieldName : params.keySet()) {
            thisInteraction.put(fieldName, params.get(fieldName));
        }
        update thisInteraction;
        
        return thisInteraction.name;
    }
//    /services/data/v34.0/sobjects/interaction__c/a076F00000qz2w4QAA


    @HttpDelete
    global static string DeleteInteraction() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String interactionId= req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        interaction__c inter= [SELECT Id FROM interaction__c WHERE Id = :interactionId];
        delete inter;
        
        return 'Deleted SuccessFully';
    }
    
}

Batch Apex Example to Update Contact Email Id

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
global class ContactEmailUpdateBatch implements Database.Batchable < sObject > {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = SELECT Id, Email FROM Contact;
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List < Contact > scope) {

        for (Contact a: scope) {
            a.email = a.email + .test;
        }
        update scope;
    }

    global void finish(Database.BatchableContext BC) {}
}


Executing the above batch class from the anonymous window of developer console:



1
2
ContactEmailUpdateBatch CEUB = new ContactEmailUpdateBatch();
Database.Executebatch(CEUB ,1);

Tuesday, 20 March 2018

Trigger to Avoid Duplicate Combination of Parents in Junction Object

This trigger will help you to avoid duplicate entries on the Junction object with the same set of parent records.

For Ex: Let's consider we have three objects Parent1, Parent2, and Child1(Junction Object between Parent1 and Parent2).



  • We have inserted a record in Junction Object (CH1) with values as a parent1 record (P1) and Parent2 Record (P2). 
  • If we try to enter another Child record with again same parent combination i.e., P1 and P2 then the below trigger throw an error message saying duplicates not allowed.

Trigger:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
trigger AvoidDuplicateOnJunctionObject on Child1__c (before insert,before Update) {
 
    set<Id> Parent1Set = new set<Id>();
    set<Id> Parent2Set = new set<Id>();

    Set<Id> AvailableParent1Set = new set<Id>();
    set<Id> AvailableParent2Set = new set<Id>();   
    
    for(Child1__c vp : trigger.new){
        Parent1Set.add(vp.Parent1__c);
        Parent2Set.add(vp.Parent2__c);
    }
    
    
    for(Child1__c vp : [Select id, Parent1__c, Parent2__c from Child1__c WHERE Parent1__c IN: Parent1Set AND Parent2__c IN: Parent2Set]){
        AvailableParent1Set.add(vp.Parent1__c);
        AvailableParent2Set.add(vp.Parent2__c);        
    }
    
    for(Child1__c vp : trigger.new){
        if(AvailableParent1Set.contains(vp.Parent1__c) && AvailableParent2Set.contains(vp.Parent2__c)){
            vp.adderror('Duplicate Combination Values are Not Allowed');
        }        
    }
}

Monday, 5 March 2018

Trigger to Update the Child record with Parent field data - Using Map(only on insert)

This trigger is to show the use of Map in apex. Here we are updating the contact's type field with the corresponding parent(Account)'s name.

for ex:
       if Account name = 'Prestige';
          Contact name = 'contact 3'
       then the 'Type' field from the contact will get updated with 
          Contact Type - 'Prestige - Contact'


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
trigger UpdateContactFieldWithAccountUsingMap on Contact (before insert) {

    set<id> Accountids = New set<id>();
    for(contact con : trigger.new){
        Accountids.add(con.AccountId);
    }
    map<Id,Account> IdAccountMap = new map<Id, Account>([select id, name from account where id in : Accountids]);
    for(contact con : trigger.new){
        if(con.accountId!=null && IdAccountMap.containskey(con.accountId)){
            con.Title = IdAccountMap.get(con.AccountId).name + '- Contact';
        }
    }    
}

Friday, 2 March 2018

Aggregate Result Query- Sum, Minimum, Maximum, Average and Count

Below query is on Opportunity object and on Amount Field.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Aggregateresult[] aggresult= [Select COUNT(amount)countt, SUM(amount)sum, MIN(amount)min, MAX(amount)max, AVG(amount)avg from Opportunity];

System.debug('opportunity Count amount******'+aggresult[0].get('countt'));

System.debug('opportunity SUM amount******'+aggresult[0].get('sum'));

System.debug('opportunity MIN amount******'+aggresult[0].get('min'));

System.debug('opportunity MAX amount******'+aggresult[0].get('max'));

System.debug('opportunity Average amount******'+aggresult[0].get('avg'));

Thursday, 1 March 2018

Trigger to calculate the minimum date of Child records and populate on Parent record

Here Child -> Buyers__c

         Parent -> oneplus__c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
trigger FirstBuyer on Buyers__c (after Insert, after update, after Delete, after Undelete) {

   set<id>OnePlusIds = new set<Id>();
   
   if(trigger.isInsert || trigger.isUndelete || trigger.isUpdate){
           for(Buyers__c buy : Trigger.new){
               OnePlusIds.add(buy.oneplus__c);
           }
       }    

   if(trigger.isDelete || trigger.isUpdate){   
       for(Buyers__c buy : Trigger.old){
           OnePlusIds.add(buy.oneplus__c);
       } 
   }   
   
   List<OnePlus__c>Parent_List = [Select Id, name, First_Buying_Date__c,  (Select Id, Name,
                                  Buying_date__c From Buyers__r ORDER BY Buying_date__c ASC 
                                  LIMIT 1) From oneplus__c WHERE ID IN: OnePlusIds];
   
   List<OnePlus__c>Update_Parent_List = New List<OnePlus__c>();
   
   for(Oneplus__c oneplus : Parent_List){                         
       oneplus.First_Buying_Date__c =  oneplus.Buyers__r[0].Buying_date__c; 
       Update_Parent_List.add(oneplus);                                                
   }
   
   Update Update_Parent_List;
}

Monday, 26 February 2018

Trigger Context Variables Explanation

Trigger:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
trigger EventsFind on Account (Before Insert, After Insert, Before Update, After Update, Before Delete, After Delete, After undelete) {

    List<Account>TriggerNewList = Trigger.New;
    List<Account>TriggerOldList = Trigger.Old;
    Map<Id,Account>TriggerNewMapList = Trigger.NewMap;
    Map<Id,Account>TriggerOldMapList = Trigger.OldMap;
   
   
    If(Trigger.IsBefore && Trigger.IsInsert){
        system.debug('Before Insert - Trigger.New details****'+TriggerNewList);
        system.debug('Before Insert - Trigger.Old details****'+TriggerOldList); 
        system.debug('Before Insert - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('Before Insert - Trigger.OldMap details****'+TriggerOldMapList); 
    }
   
    If(Trigger.IsAfter && Trigger.IsInsert){
        system.debug('After Insert - Trigger.New details****'+TriggerNewList);
        system.debug('After Insert - Trigger.Old details****'+TriggerOldList); 
        system.debug('After Insert - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('After Insert - Trigger.OldMap details****'+TriggerOldMapList); 
    }         

    If(Trigger.IsBefore && Trigger.IsUpdate){
        system.debug('Before Update - Trigger.New details****'+TriggerNewList);
        system.debug('Before Update - Trigger.Old details****'+TriggerOldList); 
        system.debug('Before Update - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('Before Update - Trigger.OldMap details****'+TriggerOldMapList); 
    }
   
    If(Trigger.IsAfter && Trigger.IsUpdate){
        system.debug('After Update - Trigger.New details****'+TriggerNewList);
        system.debug('After Update - Trigger.Old details****'+TriggerOldList); 
        system.debug('After Update - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('After Update - Trigger.OldMap details****'+TriggerOldMapList); 
    }   

    If(Trigger.IsBefore && Trigger.IsDelete){
        system.debug('Before Delete - Trigger.New details****'+TriggerNewList);
        system.debug('Before Delete - Trigger.Old details****'+TriggerOldList); 
        system.debug('Before Delete - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('Before Delete - Trigger.OldMap details****'+TriggerOldMapList); 
    } 
   
    If(Trigger.IsAfter && Trigger.IsDelete){
        system.debug('After Delete - Trigger.New details****'+TriggerNewList);
        system.debug('After Delete - Trigger.Old details****'+TriggerOldList); 
        system.debug('After Delete - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('After Delete - Trigger.OldMap details****'+TriggerOldMapList); 
    }     
   
    If(Trigger.IsAfter && Trigger.IsUnDelete){
        system.debug('After UnDelete - Trigger.New details****'+TriggerNewList);
        system.debug('After UnDelete - Trigger.Old details****'+TriggerOldList); 
        system.debug('After UnDelete - Trigger.NewMap details****'+TriggerNewMapList);
        system.debug('After UnDelete - Trigger.OldMap details****'+TriggerOldMapList); 
    }     
}

Explanation:



The above trigger will give all the details about context variables in Debug Logs.
To Understand the context variables on your own, Please do the following steps on your Organization.
1. Please Save the above trigger in your organization and enable.
2. Enable Debug Logs on the running username.
3. Create an account and elaborate the debug logs.
4. Update an account and elaborate the debug logs.
5. Delete an account and elaborate the debug logs.
6. Undelete an account and elaborate the debug logs.

You can find the below observations in debug logs.

Insert : New Values stored in Trigger.New and Trigger.NewMap
Trigger.Old and Trigger.OldMap - NULL

Update : Old values are storing in Trigger.old and Trigger.OldMap
New Values are stored in Trigger.New and Trigger.NewMap

Delete : Old values are storing in Trigger.old and Trigger.OldMap
Trigger.New and Trigger.NewMap - NULL

Undelete :  New Values stored in Trigger.New and Trigger.NewMap
Trigger.Old and Trigger.OldMap - NULL


Insert : 
Before Insert : Trigger.New - Having NewValues
After  Insert : Trigger.New - Having NewValues
After  Insert : Trigger.NewMap - Having Map of NewValues

Update : 
Before Update : Trigger.New - Having NewValues
Before Update : Trigger.Old - Having OldValues
Before Update : Trigger.NewMap - Having Map of NewValues
Before Update : Trigger.Oldmap - Having Map of OldValues
After  Update : Trigger.New - Having NewValues
After  Update : Trigger.Old - Having OldValues
After  Update : Trigger.NewMap - Having Map of NewValues
After  Update : Trigger.Oldmap - Having Map of OldValues

Delete : 
Before Delete : Trigger.Old - Having Old Values
Before Delete : Trigger.OldMap - Having Map Of Old Values
After  Delete : Trigger.Old - Having Old Values
After  Delete : Trigger.OldMap - Having Map Of Old Values

Undelete : 
After Undelete : Trigger.New - Having NewValues
After Undelete : Trigger.NewMap - Having Map of NewValues



Tuesday, 13 February 2018

Count of Child on Parent with Lookup Relation - Trigger

Here Child -> Buyers__c
              Parent -> oneplus__c

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
trigger ChildCountOnParent on Buyers__c (After Insert,after Delete, After Update, After Undelete) {

    Set<Id> Parent_Set = New Set<Id>();
   
    if(Trigger.isDelete || Trigger.isUpdate){
        for(Buyers__c b : trigger.old){
            Parent_Set.add(b.oneplus__c);
        }
    }

    if(Trigger.isInsert || Trigger.isUndelete || || Trigger.isUpdate){
        for(Buyers__c b : trigger.new){
            Parent_Set.add(b.oneplus__c);
        }
    }
   
    List<OnePlus__c> Parent_List = [Select id, Name,No_of_Buyers__c, (Select id, oneplus__c                                           from buyers__r) from OnePlus__c WHERE ID IN :Parent_Set];
   
    for(OnePlus__c one : Parent_List){
        one.No_of_Buyers__c = one.buyers__r.size();
    }
   
    Update Parent_List;
}

Tuesday, 2 January 2018

Trigger to avoid duplicate records on insert/update

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
trigger FindDuplicate on Account (before insert, before update) {

    set<string> NameSet = New set<string>();

    for(Account onn : Trigger.new){
        NameSet.add(onn.Name);
    }    

    if(NameSet.size()>0 && NameSet.size()!=null){  

        List<Account > NameList = [Select id, Name from Account WHERE Name in: Nameset];
        Map<string,Account > NameCompareMap = new Map<String,Account >();

        for(Account One : NameList){
            NameCompareMap.put(one.Name, one);
        }        

        for(Account On1 : trigger.new){
            if(NameCompareMap.containsKey(on1.Name)){
                On1.Name.adderror('NaMe AlReAdY eXiStS');
            }
        }
    }
}