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
Satheesh27Satheesh27 

how to change owner of the lead record using triggers

 I am getting this error
Compile Error: Field is not writeable: Lead.Owner at line 7 column 16
Best Answer chosen by Satheesh27
Deepak Maheshwari 7Deepak Maheshwari 7

Please use below code:

 

Trigger LeadTrigger on Lead(before Insert)
{
    for(Lead ld: Trigger.New)
    {
        if(ld.LeadSource=='Web')
        {
            ld.Ownerid='please put id of user';
        }
    }
}

All Answers

Deepak Maheshwari 7Deepak Maheshwari 7

Hi Satheesh,

 

Can you please share your trigger which you have written?

So that I can analyze.

 

Thanks

Satheesh27Satheesh27
Hi,
Here is my code:

Trigger LeadTrigger on Lead(After Insert)
{
    for(Lead ld: Trigger.New)
    {
        if(ld.LeadSource=='Web')
        {
            ld.Owner='Wilson';
        }
    }
}

Thank You
Deepak Maheshwari 7Deepak Maheshwari 7

Please use below code:

 

Trigger LeadTrigger on Lead(before Insert)
{
    for(Lead ld: Trigger.New)
    {
        if(ld.LeadSource=='Web')
        {
            ld.Ownerid='please put id of user';
        }
    }
}

This was selected as the best answer
Satheesh27Satheesh27
Thank You Maheshwari
Its working...
David Roberts 4David Roberts 4
I solved this by creating a custom field "Assign To" on the Lead object.
I then used a trigger to force the new owner when the Lead was created:

trigger ChangeOwner on Lead (before insert) {

 for(Lead theNewLead: Trigger.New)
 {
    
    if (theNewLead.Assign_To__c != null){
     theNewLead.Ownerid=theNewLead.Assign_To__c;
     }
 }

}
David Roberts 4David Roberts 4
Test code for this is:

@isTest(seeAllData=false)
private class TestChangeLeadOwnerTrigger
{
    static testMethod void TestLead()
    { 
       Lead testLead = new Lead();
       testLead.Lastname ='Test Name';
       testLead.Company ='Test Co';
       testLead.Assign_To__c = '[your user's id here]';
       insert testLead;
    }
}
David Roberts 4David Roberts 4
Hi Niven, Here’s my trigger code. Feel free to remove the debug lines. trigger ChangeOwner on Lead (before insert,before update) { for(Lead theNewLead: Trigger.New) { system.debug('was '+theNewLead.Ownerid); system.debug('attempt change to '+theNewLead.Assign_To__c); if (theNewLead.Assign_To__c != null){ theNewLead.Ownerid=theNewLead.Assign_To__c; system.debug('changed'); } } } Best regards, Dave.