function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sriram Varma 1Sriram Varma 1 

trigger on account object and populate owner name in any custom field.

AbhishekAbhishek (Salesforce Developers) 
Try the below code snippet,

trigger Accounts on Account (before insert) {
    if(trigger.isBefore){
        if(trigger.isInsert){
            set<id>setOwnerId = new set<id>();
            map<Id,User>mapUserIdWiseUser = new map<Id,User>();
            for(Account oAcc:trigger.new){
                setOwnerId.add(oAcc.OwnerId); 
            }
            if(setOwnerId.size()>0){
                for(User oUser:[Select Id,Name From User Where Id In:setOwnerId]){
                    mapUserIdWiseUser.put(oUser.Id,oUser);
                }
                if(!mapUserIdWiseUser.isEmpty()){
                    for(Account acc:trigger.new){
                        if(mapUserIdWiseUser.containsKey(acc.OwnerId)){
                            acc.Description = mapUserIdWiseUser.get(acc.OwnerId).Name;
                        }
                    }
                }
            }
        }
    }
}



Replace the "Description" field with your custom field.


Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.


Thanks.
ANUTEJANUTEJ (Salesforce Developers) 
Hi Sriram,

You can use the below snippet and modify it as per your use case:
 
trigger ac_tri on account(before insert)
{
if(trigger.isbefore && trigger.isinsert)
{
User objUser = new User();
objUser = [ SELECT Name, Id FROM User WHERE Id = : UserInfo.getUserId() ];
for(Account a: trigger.new)
{
a.Custom_field__c = objUser.Name;
}
}
}

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
Sriram Varma 1Sriram Varma 1
- ERROR--sri: data changed by trigger for field Sales Rep: data value too large: (value has been hidden)