You need to sign in to do that
Don't have an account?

Null Point Exception
Cant figure out why this code is giving me a null point exception.
trigger Account_BeforeUpdate on Account (before update)
{
Set<String> billCountry = new Set<String>();
for(Account acc : trigger.new)
{
billCountry.add(acc.BillingCountry);
}
Map<String, Country__c> accountMap = new Map<String, Country__c>([SELECT Region__c FROM Country__c WHERE Name IN :billCountry]);
for(Account acc: trigger.new)
{
acc.Region__c = accountMap.get(acc.BillingCountry).Region__c;
}
}
Can you spot any errors in the Code?
Map<String, Country__c> accountMap=new Map<String,Country__c>();
for(Country__c c: [SELECT Region__c FROM Country__c WHERE Name IN :billCountry])
accountMap.put(c.Name,c);
for(Account acc: trigger.new) {
acc.Region__c = accountMap.get(acc.BillingCountry).Region__c;
}
Hope this will solve your problem!!
All Answers
I think you need to account for null values in the BillingCountry field, as well as the lookup in Country__c not returning a value.
At the moment, I was just trying to update one record, and it was still throwing an exception. And I'm sure that the BillingCountry and region values are there in the object.
BTW, what I'm trying to do it, when a account is updated, I want to look in the countries object to find the region field associated with the country based on the billing country of the account and update the region field in the account accordingly.
I think the error is in the line "acc.Region__c = accountMap.get(acc.BillingCountry).Region__c;" because according to your code....key for that map will be id of Country__c but not the billing counry of Account.
To make this work....Declare the map ...write query separately and fill the map with required key and value pair by looping over query results.
Can you please show me how. I'm fairly new and I wrote this code from another example. Thanks
Map<String, Country__c> accountMap=new Map<String,Country__c>();
for(Country__c c: [SELECT Region__c FROM Country__c WHERE Name IN :billCountry])
accountMap.put(c.Name,c);
for(Account acc: trigger.new) {
acc.Region__c = accountMap.get(acc.BillingCountry).Region__c;
}
Hope this will solve your problem!!
Thanks a lot. It's working perfectly now.
You're welcome......please mark this as solved...