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
himanshu huske 7himanshu huske 7 

change owner of record

please correct my code below,
  I have one object Customer__c,In this there are one  picklist User_to_b__c.
if valid userName is input in User_to_b__c field. owner field should update with value in User_to_b__c
trigger Cust_User_to_be on Customer__c (before insert, before update) {
     Set<string> strSet = new Set<String>();
      for(Customer__c cs : trigger.new)
      {
              strSet.add(cs.User_to_b__c);
       }
    map<string,id> csMap = new map<string,id>();  
    for(User u : [Select id,Name from user where Name IN :strSet])
    {
            csMap.put(u.Name,u.Id);
     }
    for (Customer__c cs : Trigger.new)
    {
             if (cs.OwnerId <> csMap.get(cs.User_to_b__c) )          
             {
                   cs.OwnerId = csMap.get(cs.User_to_b__c);
              }

    }
}

 
Sainath VenkatSainath Venkat
trigger UpdateOwnerID on Customer__c (before insert, before update) {
     Set<string> aliasscope = new Set<String>();
      for(Customer__c opp : trigger.new)
      {
              aliasscope.add(opp.User_to_b__c);
       }
    map<string,id> userIdbyAlias = new map<string,id>();  //Keep in mind this will only store one user id per alias
    for(User u : [Select id from user where Alias IN :aliasscope])
    {
            userIdbyAlias.put(u.Alias,u.Id);
     }
    for (Customer__c objOpp : Trigger.new)
    {
        if(userIdbyAlias.containskey(objOpportunity.User_to_b__c)
        {

             if (objOpportunity.Name <> userIdByAlias.get(objOpp.User_to_b__c) )           
             {
                   objOpp.OwnerId = userIdByAlias.get(objOpp.User_to_b__c);
              }
         }
    }

}

Can you please try above code, mark it best if it solves your problem.