trigger DuplicatUsingMap on Account (before insert, before update)
{
Map<Id,Account> acMap = new Map<Id,Account>([select id, name from account]);
for(Account a : trigger.new)
{
if(a.name != null && a.name == acMap.get(a.Id).name)
a.addError('Account already exist');
}
}
1 Answer
You are not writing code in correct way:
just making a query:
Map<Id,Account> acMap = new Map<Id,Account>([select id, name from account]);
Which would results all accounts available in your org. So if there is no Account exist, it would throw null pointer exception.
If you have accounts in your org, still it would throw error in case of before insert operation, because new records have never been committed to database till that time, hence would not be available in acMap
and will throw error while accessing .name
.
Write code with context of events and make queries only if needed and always add where clause in queries...
Here are the best practices to develop trigger..https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices
oldMap
rather than querying the entire database. (Or use duplicate rules or some other method of duplicate management).