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;
}