I have custom junction object between user and custom object. I need to update user record with junction object values for given user. Each user may have more than one record in junction object.
Example: User1 will have account1,account 2 in junction object and I need to update user record custom field with account1, account2.
I have written code like this but it will overwrite the previous value with new value in given batch when I issue single update list statement. How can I achieve it?
trigger UpdateUserGUL on GUL_Account_to_User_Junction__c (after insert) {
String AccountName;
String ChatterGrpName;
List<User> userList = new List<User>();
for (GUL_Account_to_User_Junction__c j: Trigger.New) {
User userRecord = new User();
userRecord.Id = j.UserId__c;
//check to see if it is having any value
AccountName = userRecord.GUL_Account_Default__c;
if(AccountName == null) {
userRecord.GUL_Account_Default__c = j.GUL_Account_Name__c;
} else {
userRecord.GUL_Account_Default__c = AccountName + ',' + j.GUL_Account_Name__c;
}
userList.add(userRecord);
}
update userList;
}
Best Answer
If I were you, I would implement this with dlrs.
User
UserId__c
GUL_Account_to_User_Junction__c
GUL_Account_Name__c
Concatenate Distinct
GUL_Account_Default__c
,
If you want to roll your own solution, you are going to have to query the sibling records, and don't forget you need to worry about the delete case.
You should really consider adding error handling to the
update
operation. You may also need to put this functionality in awithout sharing
class, since most users won't be able to update otherUser
records.