+ Start a Discussion
Force.platformForce.platform 

trigger to get user name into text field

i want to write trigger to popolate account owner name into SalesRep__c(Text) field on the account object.
Davy HuijgensDavy Huijgens
trigger AccountTrigger on Account (before insert) {
    for(Account a : Trigger.New) {
        a.SalesRep__c = a.Owner.Name;
    }   
}
This is if you want to do it before insert.
 
Vinod Chokkula 3Vinod Chokkula 3
You can use a formula field instead
data type: text
formula:  Owner.Username 
 
Force.platformForce.platform
hi Davy,
        i tried this, 
                 trigger AccountTrigger on Account (before insert)
                   { for(Account a : Trigger.New)
                       { a.SalesRep__c = a.Owner.Name; } }

but it's showing Owner Id into salesRep__c field. i want Owner name.
Shiva RajendranShiva Rajendran
HI Arati,

Do use this code.It should work.
trigger AccountTrigger on Account (before insert)
                   {
Set<Id> userIds=new set<Id>();
 for(Account a : Trigger.New)
{
userIds.add( a.OwnerId);
}
Map<ID, Account> allUserMap = new Map<ID, User>([SELECT Id, Name FROM User where id in :userIds]);
 for(Account a : Trigger.New)
{
 a.SalesRep__c = allUserMap.get(a.OwnerId);
}


 }
Let me know if you face any issues or  need further help .

Thanks and Regards,
Shiva RV