We've had a community deployment and my brain is fried and I just whipped up a quick class that is throwing the below error. What have I done wrong here?
Error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MSI_UserTrigger:
execution of AfterInsert caused by: System.StringException: Invalid
id: () : [] () : []: ()
What I am trying to accomplish is:
- When a new user is created and is active, if they are linked to a ContactId and part of a specific profile (by name), add their ContactId to a Set<ID>
- Then loop through contacts where the Id is in the set, and update the Community_User__c field to TRUE
Trigger:
trigger MSI_UserTrigger on User (after insert) {
if(Trigger.isAfter){
if(Trigger.isInsert){
MSIUserTriggerHandler.executeAfterInsert(Trigger.new);
}
}
}
Class:
public with sharing class MSIUserTriggerHandler {
private static final String COMMUNITY_PROFILE = 'Community Knowledge User';
private MSIUserTriggerHandler() {}
public static void executeAfterInsert(List<User> newList){
setCreatedCommunityUsers(newList);
}
private static void setCreatedCommunityUsers(List<User> newList){
List<User> usersWithContacts = new List<User>();
List<Contact> contactsToUpdate = new List<Contact>();
Set<ID> contactIds = new Set<ID>();
for(User u: newList){
if(u.ContactId == null && u.ContactId == ''){
continue;
}
if((u.ContactId != null && u.ContactId != '') && u.Profile.Name == COMMUNITY_PROFILE && u.isActive == true){
contactIds.add(u.ContactId);
}
}
for(Contact c : [Select Id,Name,Community_User_Created__c from Contact where Id in :contactIds]){
if(!c.Community_User_Created__c){
c.Community_User_Created__c = true;
contactsToUpdate.add(c);
}
}
update contactsToUpdate;
}
}
Am I not adding the ID correctly to the Set<ID>, or am I querying wrong in my for(Contacts)
loop?
Best Answer
When you perform a comparison between a String and an Id (e.g. ==, !=, or <>), then the other argument is "promoted" to an Id value. All Id values must be 15 or 18 characters long, and must contain only A-Z, a-z, and 0-9, so '' is not a valid Id.
Proof:
Edit:
Also, there's a more efficient way you could write this trigger's function:
Since we need to query for the Profile Name anyways, we can just perform all of the branch logic at once in the query, then update any records that are returned.