0

Hello Guys, I have wrote a trigger on account object that whenever a user enter duplicate phone number or email then it will show an error on page and the info will not stored in the account object.

trigger AccountTrigger on Account (before insert, before update)
{
    //Account duplicate protection system.
    if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate))
    {
        Map<String, Account> anAccountMap = new Map<String, Account>();
        for (Account anAccount : System.Trigger.new)
        {
            // Make sure we don't treat an mobile phone that  
            // isn't changing during an update as a duplicate.  
            if ((anAccount.Phone != null) && (Trigger.isInsert || 
                      (anAccount.Phone != Trigger.oldMap.get(anAccount.Id).Phone)))
            {
                // Make sure another new Account isn't also a duplicate  
                if (anAccountMap.containsKey(anAccount.Phone))
                {
                    anAccount.Phone.addError('Another new Account has the same mobile phone.');
                    System.debug('*** Error: found account with dublicate mobile phone: ' + anAccount);
                } else
                {
                    anAccountMap.put(anAccount.Phone, anAccount);
                }
            }
        }  
        // Using a single database query, find all the Accounts in  
        // the database that have the same mobile phone as any  
        // of the Accounts being inserted or updated.  
        for (Account aDBAccount : [SELECT Phone FROM Account WHERE Phone IN :anAccountMap.KeySet()])
        {
            Account newAccount = anAccountMap.get(aDBAccount.Phone);
            newAccount.Phone.addError('An Account with this mobile phone already exists.');
            System.debug('*** Error: found account with dublicate mobile phone: ' + newAccount);
        }
    }
}

Note:-- The thing is that its working but its not showing any error on my particular page. Any help from the MVP's or the consultant will be great.

  • 1
    Is this a visualforce page? If so, please include the page source. – Guy Clairbois Mar 23 '15 at 14:07
0

I checked this in

  1. standard edit layout of Account
  2. vf page of Account (standard controller)
  3. Vf page of Account (custom Controller)

This code is working perfectly fine and giving error messsage properly at field level(phone)

Seems like some other issue in your page. did you check with

 '<apex:pageMessages />' 

tag, if you're getting some other errors or not ?

  • @ curious_techy yes i included this one also but nothing happen? actually i want to show the error message on the particular filed on my customize VF page not the standard page. – Anurag Pareek Mar 24 '15 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.