I'm having some issues with some code I've adapted to work for my instance that was posted by @Brian Mansfield.
We have invoices pushed into a custom object and they link through to accounts fine, but I'm trying to get it linked to a user where possible to allow easier reporting.
On the invoice item there is a field "Sales_Rep_1" which should match the alias of a user. The code is working to some degree, but it seems to be case-sensitive. E.g. if the invoice has Sales_rep_1 value of "TEST" and there's a user with an alias "test", it throws a wobbly and I get the following error:
Error:Apex trigger SetSalesRep caused an unexpected exception, contact your administrator: SetSalesRep: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.SetSalesRep: line 19, column 1
Would be grateful if someone can find a fix for this.
Many thanks
trigger SetSalesRep on Invoice_Item__c (before update, before insert) {
Set<String> users = new Set<String>();
for (Invoice_Item__c collectNumFromOrder : Trigger.new) {
users.add(collectNumFromOrder.Sales_Rep_1__c);
}
List<User> UserList = [SELECT id, alias FROM USER WHERE alias IN :users];
Map<String, User> InvoiceToUserMap = new Map<String, User>();
for (User c : UserList) {
InvoiceToUserMap.put(c.alias, c);
}
for (Invoice_Item__c o : Trigger.new) {
if (!InvoiceToUserMap.Isempty() ) {
o.User__c = InvoiceToUserMap.get(o.Sales_Rep_1__c).id;
}
else {
o.User__c = null;
}
}
}