'I want to change opportunity.createdby to lead.ownerid,rectify my code

I want to change opportunity.CreatedById to lead.ownerid,rectify my code

trigger on opportunity(after insert)
lst<ooportunity> opps=[select opportunityId,CreatedById from opportunity where opportunityId IN 
                               : Trigger.New];
list<lead> leads=[SELECT Id,ConvertedOpportunityId,OwnerId From lead where isConverted=true];
for(opportunity ops:opps)
{if(leads.Id==opps.OpportunityId)
{ opps.CreatedById=leads.OwnerId;
ops.add(opps);
}
update ops;


Solution 1:[1]

You can't, at least not like that.

Audit fields (createdbyid, createddate, lastmodifiedbyid, lastmodifieddate) are readonly and modified by SF internally.

There's a trick to open them up for example for data migrations (you're loading 7 years worth of opportunities, you want to record their real creation date so it doesn't show as a spike in reports). But you have only 1 shot at this. Only during insert.

https://help.salesforce.com/s/articleView?id=000334139&type=1 and https://help.salesforce.com/s/articleView?id=000331038&type=1

You'd need to tick something in setup, this causes 2 magic checkboxes to show up in profiles/permission sets. Then you'd edit your profile (or create new permission set and assign to yourself).

You'd need to change your trigger to before insert (but if it's before - the lead is still being converted, the opp id isn't known yet - so you can't match it by Lead.OpportunityId)... And even then - this feature is aimed at sysadmins, I doubt normal user without "Modify All Data" can do it.

Rethink your business scenario. Maybe you want to set Opportunity.OwnerId, not CreatedById?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eyescream