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
Dilip Kulkarni 12Dilip Kulkarni 12 

Defaulting the record owner

Hi Experts,
I have one object 'service contract' where there is field 'owner' (lookup with user). In this field the value is put as owner. But I want to default the user creating the record as 'owner' (means owner of record) and he should have ability to reassign/change the value. In short I want to pull 'created by' value in 'owner' field once record is created. What will be trigger for it?

Regards.
Best Answer chosen by Dilip Kulkarni 12
Hemant_SoniHemant_Soni
Hi Dilip Kulkarni 12,
Please try below trigger.
I think this may help you.
trigger FilOwner on service_contract__c(After insert) {
list<service_contract__c>lstservicecontract = new list<service_contract__c>();
service_contract__c oServicecontract;
if(trigger.isAfter){
system.debug('@developer-->After:');
if(trigger.isInsert){
system.debug('@developer-->isInsert:');
for(service_contract__c oSC:trigger.new){
oServicecontract = new service_contract__c();
oServicecontract.Id = oSC.Id;
oServicecontract.Owner = oSC.CreatedById;
lstservicecontract.add(oServicecontract); 
system.debug('@developer-->oServicecontract:'+oServicecontract);
}
if(lstservicecontract.size()>0){
update oServicecontract;
}
}
}
}
Thanks
Hemant
 

All Answers

Hemant_SoniHemant_Soni
Hi Dilip Kulkarni 12,
Please try below trigger.
I think this may help you.
trigger FilOwner on service_contract__c(After insert) {
list<service_contract__c>lstservicecontract = new list<service_contract__c>();
service_contract__c oServicecontract;
if(trigger.isAfter){
system.debug('@developer-->After:');
if(trigger.isInsert){
system.debug('@developer-->isInsert:');
for(service_contract__c oSC:trigger.new){
oServicecontract = new service_contract__c();
oServicecontract.Id = oSC.Id;
oServicecontract.Owner = oSC.CreatedById;
lstservicecontract.add(oServicecontract); 
system.debug('@developer-->oServicecontract:'+oServicecontract);
}
if(lstservicecontract.size()>0){
update oServicecontract;
}
}
}
}
Thanks
Hemant
 
This was selected as the best answer
Dilip Kulkarni 12Dilip Kulkarni 12
Thanks Hemant. I will check and revert.
HARSHIL U PARIKHHARSHIL U PARIKH
I think you can do this via workflow OR Process buidler as well though.

Just create a workflow which would fire everytime record is created or edited and then pulls userID from CreatedBy field and throws the UserId into Owner field.

Hope this helps!