I have created a wrapper class in which I have Name and Rating variables which are string type.
1)I have pulled out Account with the name and Rating and wrapped it in a wrapper class and stored the object as a key in the map which is of type class AccountWrap.
Map<AccountWrap,Account>MapbyObject=new Map<AccountWrap,Account>();
2)Then I pulled account record from the trigger.new list and looped through,while looping I pulled out the Account name and rating and wrapped them in the wrapper class and passed it to the map to check if the map has key which matches the object's Name and rating.
AccountWrap accwr=new AccountWrap(acc.name,acc.rating);
Account acc20=MapbyObject.get(accwr);
I was hoping that map will match the key which I passed and it will return Account asscoiated with the key which means it is a duplicate record and then I will show an error to the user.
However,I am always getting null values. I have a before insert trigger in which I am calling class and it's method.
Here is the code:-
public class AccTrigger {
Map<AccountWrap, Account> MapbyObject = new Map<AccountWrap, Account>();
public void CompareRecords(list<account> AccRecords) {
for (Account rec : [
SELECT name, rating
FROM Account
WHERE name = 'james constructions'
LIMIT 1
]) {
AccountWrap acwrap = new AccountWrap(rec.name, rec.rating);
MapbyObject.put(acwrap, rec);
System.debug('The map has the following values' + MapbyObject);
//The map has the following values{AccountWrap:[Name=james constructions, Rating=Warm]=Account:
// {
// Name=james constructions, Rating=Warm, Id=0015e000003lp6rAAA}}
// }
for (Account acc : AccRecords) {
System.debug('The account has the following record' + acc);
AccountWrap accwr = new AccountWrap(acc.name, acc.rating);
System.debug('the accountwrap has' + accwr);
//The accountwrap hasAccountWrap:[Name=james construction, Rating=Warm]
Account acc20 = MapbyObject.get(accwr);
//Here I am only getting null value when I was expecting non null value;
System.debug('The map has the follogin values' + acc20);
if (acc20 != null) {
acc.adderror('dupe');
}
}
}
}
public class AccountWrap {
public String Name;
public String Rating;
public AccountWrap(String name, string rating) {
System.debug('I am in the wrapper class constructor');
this.name = name;
this.rating = rating;
}
}
}