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
Soujanya Uppal 9Soujanya Uppal 9 

i want to change owner through trigger on new record when industry = agriculture

i want to change owner through trigger on new record when industry = agriculture else shows error

Please anyone give me code for this
i have tried this much

trigger changeownerTrigger on Account (before insert) {

    for(Account ac: trigger.new){
        
        if(ac.Industry=='Agriculture')
            
    }
}
Prasanthi_s1505Prasanthi_s1505
trigger changeownerTrigger on Account (Before Insert) {
 if(trigger.isBefore && trigger.isInsert )
    {
    for(Account ac: trigger.new){
        
        if(ac.Industry=='Agriculture'){
         ac.OwnerId = '0055g00000Ai5NfAAS';  // Here give the User Id to which owner the record has to assign
        }
    }
    }
}

You can get the User Id from the URL of the User page also.
Kindly, check this below link it may help in finding the User Id..
https://help.salesforce.com/s/articleView?id=000312782&type=1

If it worked kindly mark it as best answer and Like it.
Thank you.,
Prasanthi_s1505Prasanthi_s1505
Add., 
else
{
//Error statement example., it can be in your requirement as below
ac.Industry.addError('Error Message');
}

Thank you.
Suraj Tripathi 47Suraj Tripathi 47
Hi Soujanya Uppal,
Use this code for Trigger : 
trigger changeownerTrigger on Account (after insert) {
    for(Account ac: trigger.new){        
    if(ac.Industry=='Agriculture'){
    ac.OwnerId = '<write an User Id which you want to assign>' ;
    }            
  }
}
you can get reference from this for getting User Id :
https://help.salesforce.com/s/articleView?id=000312782&type=1

If you find your Solution then mark this as the best answer.
Thank you!
Regards,
Suraj Tripathi

 
Maharajan CMaharajan C
Hi Soujanya,

Please try the below code:

Don't hardcode the user id inside trigger... You query the user id based on name or alias or username from user object....
 
trigger changeownerTrigger on Account (before insert) 
{
	List<user> u = [Select Id,Name,Alias,UserName from user where UserName = 'Maharajansfdc@gmail.com' limit 1];
    for(Account ac: Trigger.New)
    {
        if(ac.Industry=='Agriculture')
        {
			if(!u.IsEmpty()){
				ac.Ownerid=u[0].Id;
			}
        }
		else{
			ac.addError('Only Agri accounts are allowed... ');
		}
    }
}

Thanks,
Maharajan.C