function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sindhu AmbarkarSindhu Ambarkar 

Getting the error while executing the code


trigger AccountDuplicateTrigger on Account (before insert, before update)
{
for(Account a:Trigger.new)
{
List<Account> acc="Select id from Account where Name=:a.Name";
if(acc.size()>0)
{
acc.Name.addError(‘You Cannot Create the Duplicate Account’);
}
}
}
It should display error when account name is duplicate please help me
 
Best Answer chosen by Sindhu Ambarkar
William TranWilliam Tran
This should work for you.

thx
 
trigger AccountDuplicateTrigger on Account (before insert, before update)
{
    for(Account a:Trigger.new){
            List<Account> acc=[Select id, Name from Account where Name=:a.Name];
            if(acc.size()>0){
                    a.Name.addError('You Cannot Create the Duplicate Account');
            }
     }
}

 

All Answers

William TranWilliam Tran
Can you post the error message?

Try this:
 
List<Account> acc=[Select id from Account where Name=:a.Name];
As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you. 

Thanks
Neetu_BansalNeetu_Bansal
Hi Sindhu,

Instead of writing trigger, you can create Duplicate rule for this. Follow these steps:
Setup -> Data.com Administration -> Duplicate Management -> Duplicate Rules.

Create your rule, and prevent inserting duplicating accounts.

For more info, refer this link:
https://help.salesforce.com/apex/HTViewHelpDoc?id=duplicate_rules_create.htm&language=en_US (https://help.salesforce.com/apex/HTViewHelpDoc?id=duplicate_rules_create.htm&language=en_US)

Let me know, if you need any other help.
If this posts help you, mark it as best answer, so will help others in future.

Thanks,
Neetu
Sindhu AmbarkarSindhu Ambarkar
Error: Compile Error: line 5:18 no viable alternative at character '"' at line 5 column 18
Sindhu AmbarkarSindhu Ambarkar
Hi Neeru,

I need to implement in trigger only.Please help me

Thanks,
Sindhu
William TranWilliam Tran
Did you try this for you line 5:


List<Account> acc=[Select id from Account where Name=:a.Name];


thx
Sindhu AmbarkarSindhu Ambarkar
I tried it but it is not working

Thanks,
Sindhu
William TranWilliam Tran
This should work for you.

thx
 
trigger AccountDuplicateTrigger on Account (before insert, before update)
{
    for(Account a:Trigger.new){
            List<Account> acc=[Select id, Name from Account where Name=:a.Name];
            if(acc.size()>0){
                    a.Name.addError('You Cannot Create the Duplicate Account');
            }
     }
}

 
This was selected as the best answer
Sindhu AmbarkarSindhu Ambarkar
Thankrs a lot  working fine.
Both are fine but what is the difference

Thanks,
Sindhu
William TranWilliam Tran
Difference is 

 a.Name.addError('You Cannot Create the Duplicate Account');

instead of

acc.Name.addError(‘You Cannot Create the Duplicate Account’);

since a is the record bound to the trigger not acc.

Be sure to choose best answer.

Thx.
Sindhu AmbarkarSindhu Ambarkar
Thanks it is very helpful

Thanks,
Sindhu.
Sindhu AmbarkarSindhu Ambarkar
When the account is not duplicate need to update the description field with account name.
Please help me 
William TranWilliam Tran
Sindhu,

It's a common practice to ask a new question, but that said, you can try this:
 
trigger AccountDuplicateTrigger on Account (before insert, before update)
{
    for(Account a:Trigger.new){
            List<Account> acc=[Select id, Name from Account where Name=:a.Name];
            if(acc.size()>0){
                    a.Name.addError('You Cannot Create the Duplicate Account');
            }
            else{a.Description = a.Name;}

     }
}

Thx
Sindhu AmbarkarSindhu Ambarkar
Thanks a lot for ur help.It helped me a lot

Thanks,
Sindhu.
Neetu_BansalNeetu_Bansal
Hi Sindhu,

Might be you need to write trigger, but in this trigger, you are using SOQL in for loop which exploits salesforce best practices and you may get exceptions in case of bulk handling. (101 SOQL). I suggest you to use the below code to avoid exceptions:
trigger AccountDuplicateTrigger on Account( before insert, before update )
{
	Set<String> accountNames = new Set<String>();
	for( Account acc : [ Select Id, Name from Account ])
	{
		accountNames.add( acc.Name );
	}
	
    for( Account a : trigger.new )
	{
        if( accountNames.contains( a.Name ))
		{
			a.Name.addError( 'You Cannot Create the Duplicate Account' );
        }
        else
		{
			a.Description = a.Name;
			accountNames.add( a.Name );
		}
	}
}
You can use this code, if only you need to handle bulk data.

Thanks,
Neetu
Sindhu AmbarkarSindhu Ambarkar
In the example you are using the query inside for loop.It is a SOQL right.
Please help me out 

Thanks,
Sindhu
Neetu_BansalNeetu_Bansal
Hi Sindhu,

The code which I provided is not using SOQL or query inside for loop. You can use this code, this is following all the best practices of programming.
trigger AccountDuplicateTrigger on Account( before insert, before update )
{
    Set<String> accountNamesToBeInserted = new Set<String>();
    for( Account acc : trigger.new )
    {
        if( trigger.isInsert 
            || ( trigger.isUpdate && trigger.oldMap.get( acc.Id ).Name != acc.Name ))
        {
            accountNamesToBeInserted.add( acc.Name );
        }
    }
    
    Set<String> accountNames = new Set<String>();
    for( Account acc : [ Select Id, Name from Account where Name IN: accountNamesToBeInserted ])
    {
        accountNames.add( acc.Name );
    }
    
    for( Account a : trigger.new )
    {
        if( trigger.isInsert 
            || ( trigger.isUpdate && trigger.oldMap.get( a.Id ).Name != a.Name ))
        {
            if( accountNames.contains( a.Name ))
            {
                a.Name.addError( 'You Cannot Create the Duplicate Account' );
            }
            else
            {
                a.Description = a.Name;
                accountNames.add( a.Name );
            }
        }
    }
}
If this helps, mark it as best answer.

Thanks,
Neetu
PRIYAN NEERUDUPRIYAN NEERUDU
trigger CONUP on Contact (after update,after insert) {
    Map<Id, Decimal> acctIdToAmount = new Map<Id, Decimal>();
    List<Account> accountsToUpdate = new List<Account>();
    Map<ID,RecordType> typeMap = New Map<ID,RecordType>([Select ID, DeveloperName From RecordType Where sObjectType = 'CONTACT']);
    for (CONTACT CON : trigger.new) {
          // If the Record Type = Intake Form
          if (typeMap.get(CON.RecordTypeId).DeveloperName == 'C2B' || typeMap.get(CON.RecordTypeId).DeveloperName == 'D2B') {
            //    Get the Contact Amount into a temp variable
            Decimal sum = CON.PAID_AMOUNT__c == null ? 0 : CON.PAID_AMOUNT__c;
            //    Sum it up with the already collected Amount    
            if(acctIdToAmount.containsKey(CON.AccountId))
                sum += acctIdToAmount.get(CON.AccountId); 
            
            //    Make a map with AccountId as Key and Amount as value     
             acctIdToAmount.put(CON.AccountId, sum);
          }
          else if(typeMap.get(CON.RecordTypeId).DeveloperName == 'E2B') {
              Decimal sum = 0;

            if(acctIdToAmount.containsKey(CON.AccountId))
                sum = acctIdToAmount.get(CON.AccountId);

            sum -= CON.PAID_AMOUNT__c == null ? 0 : CON.PAID_AMOUNT__c; 
                 
             acctIdToAmount.put(CON.AccountId, sum);    
          }      
    }

    for(Id accId : acctIdToAmount.keyset()) {
        Account acc;
        if(acctIdToAmount.get(accId) >= 0)
               acc = new Account(Id = accId, TOTAL_AMOUNT__c = acctIdToAmount.get(accId));
        else
               acc = new Account(Id = accId, PENDING_AMOUNT__c = acctIdToAmount.get(accId));
        accountsToUpdate.add(acc);
    }

    if(!accountsToUpdate.isEmpty())
        update accountsToUpdate;
}



and the error m facing is:duplicate value found: <unknown> duplicates value on record with id: <unknown>
can anyone help resolve dis issue.....